Skip to content

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

TypeScript

DropdownMenu: under a finger, the opening finger picks only after UIMenu's handoff (AST-094 FR29) (#8627)

Christopher Chedeaufbb81c6cc782
diff --git a/.changeset/menu-press-handoff.md b/.changeset/menu-press-handoff.md
new file mode 100644
index 0000000000..0e9cc37349
--- /dev/null
+++ b/.changeset/menu-press-handoff.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feature] Under a finger, on every device, the finger that opened a DropdownMenu or MoreMenu now picks a row only after it has moved 10 px (`spec:AST-094` FR29, FR43), so a menu that appears under a resting finger never picks the row beneath it, however long the finger rests. To keep the previous behavior, where that finger's lift picked once the press had lasted 300 ms, pass `presentation="popover"`. A mouse and the public `useMenuPress` hook are unchanged.
+
+@vjeux
diff --git a/.changeset/menu-press-lit-row.md b/.changeset/menu-press-lit-row.md
new file mode 100644
index 0000000000..28dc0c36df
--- /dev/null
+++ b/.changeset/menu-press-lit-row.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] While a finger or a pen is held in a DropdownMenu, MoreMenu or ContextMenu, the row under it now takes the pressed overlay, and no other row keeps it, so the highlight can be seen following it (`spec:AST-094` FR27, FR43). A held mouse, the keyboard and a hover keep the hover overlay.
+
+@vjeux
diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.ts
index d393cc0abd..366bf074b9 100644
--- a/apps/docsite/src/__tests__/data-extraction.test.ts
+++ b/apps/docsite/src/__tests__/data-extraction.test.ts
@@ -1489,7 +1489,10 @@ describe('DropdownMenu adaptive-presentation example', () => {
);
expect(presentation?.type).toBe("'popover' | 'bottom-sheet' | 'adaptive'");
- expect(presentation?.default).toBe("'popover'");
+ // Unset by default: the menu is anchored, with the touch modes under a
+ // finger. 'popover' pins the pointer behavior.
+ expect(presentation?.default).toBeUndefined();
+ expect(presentation?.description).toContain("Pass 'popover'");
const defaults = dropdownMenu?.playground?.defaults as
Record<string, unknown> | undefined;
diff --git a/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md b/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
index 0d0af7180c..35f3766c4a 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenuItem.spec.md
@@ -101,16 +101,16 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
-| FR1 | The pointer row exposes one `role="menuitem"` root. Label, description, icon, and end content are presentational content of that row rather than nested controls. | `spec:AST-020` FR15; current source and docs |
-| FR2 | Enabled activation runs the row callback before optional close. Disabled rows expose `aria-disabled=true`, remove link destinations, and run neither callback nor close. | Current behavior and tests |
-| FR3 | A destination row renders as the link root through LinkProvider. Plain activation runs the callback then closes and navigates; a modified click does not run the callback, closes the menu, and is left to the browser; a middle click closes the menu (`hasCloseOnSelect`), then runs the caller's `onAuxClick`; blocked schemes are inert. | `family:navigation-destinations` FR1–FR5; current tests |
-| FR4 | The parent menu is the only keyboard owner. It synthesizes click activation with modifiers, moves focus, and runs typeahead; the row focuses itself on mouse hover and creates no second roving-focus model. | `architecture:interaction-modality`; current parent tests |
-| FR5 | The visible root carries `dropdown-menu-item`; size and destructive state reflect on it (`data-size`, `data-variant`); semantic tokens own layout and paint before caller styling inputs compose. | `architecture:component-theming-surface`; current source and tests |
-| FR6 | Ref, supported host attributes and handlers, `className`, `style`, and `xstyle` reach or compose on the row root without replacing owned role, tab stop, disabled behavior, destination handling, or activation order. | `architecture:public-component-api` INV5–INV9; current tests |
-| FR7 | Disabled menu rows are inert, and the parent menu's arrow keys and typeahead skip them. Shipped behavior, not a requirement until OQ1 is ruled. | `component:DropdownMenu` FR17, OQ1 |
-| FR8 | Keyboard focus draws the shared focus ring inside the row, inset by the ring's own width, in every color mode; forced colors keep that ring as the focus indicator. After pointer input the row shows only its hover background (`architecture:interaction-modality` INV1); the focused row owns the indicator (INV3). | Current source; `architecture:interaction-modality` INV1, INV3 |
+| ID | Invariant | Basis |
+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
+| FR1 | The pointer row exposes one `role="menuitem"` root. Label, description, icon, and end content are presentational content of that row rather than nested controls. | `spec:AST-020` FR15; current source and docs |
+| FR2 | Enabled activation runs the row callback before optional close. Disabled rows expose `aria-disabled=true`, remove link destinations, and run neither callback nor close. | Current behavior and tests |
+| FR3 | A destination row renders as the link root through LinkProvider. Plain activation runs the callback then closes and navigates; a modified click does not run the callback, closes the menu, and is left to the browser; a middle click closes the menu (`hasCloseOnSelect`), then runs the caller's `onAuxClick`; blocked schemes are inert. | `family:navigation-destinations` FR1–FR5; current tests |
+| FR4 | The parent menu is the only keyboard owner. It synthesizes click activation with modifiers, moves focus, and runs typeahead; the row focuses itself on mouse hover and creates no second roving-focus model. | `architecture:interaction-modality`; current parent tests |
+| FR5 | The visible root carries `dropdown-menu-item`; size and destructive state reflect on it (`data-size`, `data-variant`); semantic tokens own layout and paint before caller styling inputs compose. | `architecture:component-theming-surface`; current source and tests |
+| FR6 | Ref, supported host attributes and handlers, `className`, `style`, and `xstyle` reach or compose on the row root without replacing owned role, tab stop, disabled behavior, destination handling, or activation order. | `architecture:public-component-api` INV5–INV9; current tests |
+| FR7 | Disabled menu rows are inert, and the parent menu's arrow keys and typeahead skip them. Shipped behavior, not a requirement until OQ1 is ruled. | `component:DropdownMenu` FR17, OQ1 |
+| FR8 | Keyboard focus draws the shared focus ring inside the row, inset by the ring's own width, in every color mode; forced colors keep that ring as the focus indicator. After pointer input the row shows only its hover background (`architecture:interaction-modality` INV1), or the pressed overlay while a held finger or pen lights it (`spec:AST-094` FR27); the focused row owns the indicator (INV3). | Current source; `architecture:interaction-modality` INV1, INV3 |
### Allowed variation
@@ -155,7 +155,7 @@ Consumer migration instructions belong in consumer docs and release notes.
the item remains a single row in that model.
- **AR4 — Focus perception.** After keyboard input the focused row draws the
shared focus ring inside its edge in every color mode, forced colors
- included; after pointer input it shows only its hover background (FR8).
+ included; after pointer input its background follows FR8.
## Design relationships
diff --git a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md
index 6b613357e9..6410692997 100644
--- a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md
+++ b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md
@@ -206,8 +206,10 @@ Consumer migration instructions belong in consumer docs and release notes.
- **AR1 — Highlight is focus in a menu.** In a menu the highlighted row is the
focused row, moved with `preventScroll`, so keyboard, mouse and finger share
- one highlight and one paint; a row whose root takes no focus is highlighted
- through the control inside it.
+ one highlight and one paint; in Core's menus, a held finger or pen paints its
+ lit row with the pressed overlay (a public `useMenuPress` caller gets the
+ highlight, the lit row's focus, and styles it itself); a row whose root takes
+ no focus is highlighted through the control inside it.
- **AR2 — A picker keeps its combobox focus.** In a Selector listbox the model
drives `highlightedIndex` and `aria-activedescendant`; DOM focus never moves
into the listbox.
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index c2121be176..43a75cb0e5 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -201,8 +201,7 @@ export const docs = {
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
description:
- "Presentation surface for data-driven items. 'popover' stays anchored, 'bottom-sheet' always renders the actions in a modal BottomSheet, and 'adaptive' uses a BottomSheet on compact coarse-pointer layouts while remaining anchored elsewhere. Compound children currently support popover only.",
- default: "'popover'",
+ "Presentation surface for data-driven items. 'popover' stays anchored, 'bottom-sheet' always renders the actions in a modal BottomSheet, and 'adaptive' uses a BottomSheet on compact coarse-pointer layouts while remaining anchored elsewhere. Compound children currently support popover only. Omitted, the menu is anchored, and under a finger, on every device, the finger that opened it picks a row only after moving 10 px. Pass 'popover' to keep the pointer behavior on every device, the settle rule included.",
},
{
name: 'isMenuOpen',
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index c76e5622f0..93de5e8543 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -36,6 +36,10 @@ import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {spacingVars} from '../theme/tokens.stylex';
import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
+import {MENU_PRESS_LONG_PRESS_MS} from '../hooks/useMenuPress';
+import {MENU_PRESS_SETTLE_MS} from '../hooks/menuPressGesture';
+import {TOUCH_QUERY} from '../utils/touchPresentation';
+import {UIKIT_GESTURES} from '../motion/uikit/gestures';
// Mock showPopover and hidePopover methods since they're not implemented in jsdom
beforeEach(() => {
@@ -2949,6 +2953,24 @@ describe('DropdownMenu press model', () => {
const item = (name: string) =>
screen.getByRole('menuitem', {name, hidden: true});
+ // A phone or tablet's primary pointer.
+ function stubCoarsePointer() {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: query === TOUCH_QUERY,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ expect(window.matchMedia(TOUCH_QUERY).matches).toBe(true);
+ }
+
it('a finger that lands on one row and lifts on another acts on the second, once', async () => {
const onPick = vi.fn();
const user = userEvent.setup();
@@ -3099,20 +3121,27 @@ describe('DropdownMenu press model', () => {
expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
});
- it('a held touch on the trigger opens with the finger down and a slide picks', () => {
+ it('a held touch on the trigger opens with the finger down, and a slide past the handoff picks (spec:AST-094 FR29, FR43)', () => {
vi.useFakeTimers();
try {
const onPick = vi.fn();
const trigger = renderMenu(onPick);
- fireEvent.pointerDown(trigger, touch);
+ fireEvent.pointerDown(trigger, {...touch, clientX: 0, clientY: 0});
expect(trigger).toHaveAttribute('aria-expanded', 'false');
act(() => {
vi.advanceTimersByTime(500);
});
expect(trigger).toHaveAttribute('aria-expanded', 'true');
- fireEvent.pointerMove(item('Delete'), touch);
+ // The handoff counts from the first position the open menu sees.
+ fireEvent.pointerMove(item('Delete'), {...touch, clientX: 0, clientY: 3});
+ const past = {
+ ...touch,
+ clientX: 0,
+ clientY: 3 + UIKIT_GESTURES.menuPress.handoff.value,
+ };
+ fireEvent.pointerMove(item('Delete'), past);
expect(item('Delete')).toHaveFocus();
- fireEvent.pointerUp(item('Delete'), touch);
+ fireEvent.pointerUp(item('Delete'), past);
expect(onPick).toHaveBeenCalledWith('Delete');
// The click the browser aims at the trigger for this gesture is spent.
fireEvent.click(trigger, {detail: 1});
@@ -3122,6 +3151,101 @@ describe('DropdownMenu press model', () => {
}
});
+ it('under a coarse pointer the finger that opened the menu picks only once it travels the handoff (spec:AST-094 FR29)', () => {
+ stubCoarsePointer();
+ vi.useFakeTimers();
+ try {
+ const onPick = vi.fn();
+ const trigger = renderMenu(onPick);
+ fireEvent.pointerDown(trigger, {...touch, clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ // A still lift picks nothing, however long the finger rested.
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_SETTLE_MS);
+ });
+ fireEvent.pointerMove(item('Delete'), {...touch, clientX: 0, clientY: 3});
+ expect(item('Delete')).not.toHaveFocus();
+ // UIMenu's handoff: the finger picks once it travels from the first
+ // sample the menu saw.
+ fireEvent.pointerMove(item('Delete'), {
+ ...touch,
+ clientX: 0,
+ clientY: 3 + UIKIT_GESTURES.menuPress.handoff.value,
+ });
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.pointerUp(item('Delete'), {
+ ...touch,
+ clientX: 0,
+ clientY: 3 + UIKIT_GESTURES.menuPress.handoff.value,
+ });
+ expect(onPick).toHaveBeenCalledWith('Delete');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('on a fine primary pointer too, the finger that opened the menu picks only once it travels the handoff, as on a phone (spec:AST-094 FR29, FR43)', () => {
+ vi.useFakeTimers();
+ try {
+ const onPick = vi.fn();
+ const trigger = renderMenu(onPick);
+ fireEvent.pointerDown(trigger, {...touch, clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_SETTLE_MS);
+ });
+ fireEvent.pointerMove(item('Delete'), {...touch, clientX: 0, clientY: 3});
+ expect(item('Delete')).not.toHaveFocus();
+ fireEvent.pointerMove(item('Delete'), {
+ ...touch,
+ clientX: 0,
+ clientY: 3 + UIKIT_GESTURES.menuPress.handoff.value,
+ });
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.pointerUp(item('Delete'), {
+ ...touch,
+ clientX: 0,
+ clientY: 3 + UIKIT_GESTURES.menuPress.handoff.value,
+ });
+ expect(onPick).toHaveBeenCalledWith('Delete');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('presentation="popover" pins the settle rule under a finger: once the opening press has settled, a still lift picks the row under it', () => {
+ // spec:AST-094 FR25: a moved touch default comes back through
+ // `presentation`, never through a public threshold.
+ stubCoarsePointer();
+ vi.useFakeTimers();
+ try {
+ const onPick = vi.fn<(label: string) => void>();
+ render(
+ <DropdownMenu button={{label: 'Pinned'}} presentation="popover">
+ <DropdownMenuItem label="Edit" onClick={() => onPick('Edit')} />
+ <DropdownMenuItem label="Delete" onClick={() => onPick('Delete')} />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: /Pinned/});
+ fireEvent.pointerDown(trigger, {...touch, clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS + MENU_PRESS_SETTLE_MS);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.pointerMove(item('Delete'), {...touch, clientX: 0, clientY: 2});
+ fireEvent.pointerUp(item('Delete'), {...touch, clientX: 0, clientY: 2});
+ expect(onPick).toHaveBeenCalledWith('Delete');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('a menu a held finger opens keeps its trigger as the invoker until the finger lifts', () => {
// A release on the trigger is outside the `popover="auto"` menu, so the
// browser's light dismiss would close it; holding the invoker through
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 8e6bd78a2d..c0c4ff0264 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -70,7 +70,7 @@ import {
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {useListFocus} from '../hooks/useListFocus';
-import {useMenuPress} from '../hooks/useMenuPress';
+import {useDropdownMenuPress} from '../hooks/useMenuPress';
import type {MenuPressPointerType} from '../hooks/menuPressGesture';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
@@ -460,7 +460,10 @@ interface DropdownMenuDataProps extends DropdownMenuBaseProps {
* Surface used to present the actions. Pass a value selected by product
* policy (for example, a compact-touch media query) when the presentation
* should adapt. Bottom-sheet presentation is intended for short action sets.
- * @default 'popover'
+ * Omitted, the menu is the anchored popover. Under a finger, on every
+ * device, the finger that opened it picks as UIMenu's does, once it has
+ * moved. `'popover'` pins the anchored popover with the pointer behavior on
+ * every device (the opening press follows the settle rule, as before).
*/
presentation?: DropdownMenuPresentation;
items: DropdownMenuOption[];
@@ -468,6 +471,11 @@ interface DropdownMenuDataProps extends DropdownMenuBaseProps {
}
interface DropdownMenuCompoundProps extends DropdownMenuBaseProps {
+ /**
+ * `'popover'` pins the pointer behavior on every device (the opening press
+ * follows the settle rule, as before). Omitted, on every device, the finger
+ * that opened the menu picks as UIMenu's does, once it has moved.
+ */
presentation?: 'popover';
items?: undefined;
children: ReactNode;
@@ -881,6 +889,7 @@ function DropdownMenuPopover({
placement = 'below',
alignment = 'start',
presentation: _presentation,
+ pressTouchModel = 'uikit',
header,
footer,
className,
@@ -888,7 +897,13 @@ function DropdownMenuPopover({
xstyle,
'data-testid': testId,
...props
-}: DropdownMenuProps) {
+}: DropdownMenuProps & {
+ /**
+ * How a finger's press runs, on every device: UIMenu's, unless the caller
+ * pins `presentation="popover"`.
+ */
+ pressTouchModel?: 'pointer' | 'uikit';
+}) {
const t = useComponentTranslator();
const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)};
@@ -1359,12 +1374,15 @@ function DropdownMenuPopover({
// The press model: the row under a release acts, the highlight follows a
// held pointer. A mouse released outside the menu dismisses it; a finger
// released outside leaves it open, so the hook never calls onDismiss then.
- const menuPress = useMenuPress({
+ const menuPress = useDropdownMenuPress({
menuRef: listRef,
triggerRef: buttonRef,
itemSelector: MENU_ITEM_SELECTOR,
onTriggerPress: handleTriggerPress,
onDismiss: closeMenu,
+ // Under a finger, on every device, the opening finger picks as UIMenu's
+ // does. `presentation="popover"` pins the pointer model.
+ touchModel: pressTouchModel,
});
cancelMenuPressRef.current = menuPress.cancel;
@@ -1786,7 +1804,13 @@ export function DropdownMenu(props: DropdownMenuProps) {
);
}
- return <DropdownMenuPopover {...sharedProps} presentation="popover" />;
+ return (
+ <DropdownMenuPopover
+ {...sharedProps}
+ presentation="popover"
+ pressTouchModel={props.presentation === 'popover' ? 'pointer' : 'uikit'}
+ />
+ );
}
DropdownMenu.displayName = 'DropdownMenu';
diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
index e1e343f708..08802d9c0b 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
@@ -38,6 +38,7 @@ import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {menuPressLitRowStyle} from '../privateAttributes/menuPressLit.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
import {colorVars, focusVars, spacingVars} from '../theme/tokens.stylex';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
@@ -50,7 +51,9 @@ const styles = stylex.create({
color: colorVars['--color-text-primary'],
backgroundColor: {
default: 'transparent',
- ':focus': colorVars['--color-overlay-hover'],
+ // menuPressLitRowStyle sets the variable on the row a held finger or pen
+ // lights.
+ ':focus': `var(--_menu-row-focus-paint, ${colorVars['--color-overlay-hover']})`,
},
cursor: {
default: 'pointer',
@@ -231,6 +234,7 @@ export function DropdownMenuCheckboxItem({
xstyle={[
focusOutlineStyles.focusVisible,
styles.root,
+ menuPressLitRowStyle,
isDisabled && styles.disabled,
xstyle,
]}
diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
index 72980e4bc5..ee009a52de 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
@@ -49,6 +49,7 @@ import {composeEventHandlers, mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {menuPressLitRowStyle} from '../privateAttributes/menuPressLit.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
import {isModifiedClick} from './menuItemRoles';
import {themeProps} from '../utils/themeProps';
@@ -66,14 +67,16 @@ const menuItemStyles = stylex.create({
color: colorVars['--color-text-primary'],
backgroundColor: {
default: 'transparent',
- ':focus': colorVars['--color-overlay-hover'],
+ // menuPressLitRowStyle sets the variable on the row a held finger or pen
+ // lights.
+ ':focus': `var(--_menu-row-focus-paint, ${colorVars['--color-overlay-hover']})`,
// The pressed look only where hover exists. Under a finger the row a
// press BEGAN on would otherwise stay painted while the highlight (focus)
- // moves to the row under the finger — two rows lit.
+ // moves to the row under the finger — two rows lit. A held finger or pen
+ // sets the variable on the menu. Then only the lit row keeps the look.
'@media (hover: hover)': {
default: null,
- ':active:where(:not(:disabled,[aria-disabled="true"]))':
- colorVars['--color-overlay-pressed'],
+ ':active:where(:not(:disabled,[aria-disabled="true"]))': `var(--_menu-row-active-paint, ${colorVars['--color-overlay-pressed']})`,
},
},
borderWidth: 0,
@@ -303,6 +306,7 @@ export function DropdownMenuItem({
xstyle={[
focusOutlineStyles.focusVisible,
menuItemStyles.root,
+ menuPressLitRowStyle,
itemSizeStyles[menuSize],
isDestructive && menuItemStyles.destructive,
isDisabled && menuItemStyles.disabled,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
index b543714f0c..a81615fb71 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
@@ -34,6 +34,7 @@ import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {menuPressLitRowStyle} from '../privateAttributes/menuPressLit.stylex';
import {focusMenuItemOnHover} from './menuItemHover';
import {colorVars, focusVars, spacingVars} from '../theme/tokens.stylex';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
@@ -47,7 +48,9 @@ const styles = stylex.create({
color: colorVars['--color-text-primary'],
backgroundColor: {
default: 'transparent',
- ':focus': colorVars['--color-overlay-hover'],
+ // menuPressLitRowStyle sets the variable on the row a held finger or pen
+ // lights.
+ ':focus': `var(--_menu-row-focus-paint, ${colorVars['--color-overlay-hover']})`,
},
cursor: {
default: 'pointer',
@@ -218,6 +221,7 @@ export function DropdownMenuRadioItem({
xstyle={[
focusOutlineStyles.focusVisible,
styles.root,
+ menuPressLitRowStyle,
isDisabled && styles.disabled,
xstyle,
]}
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index 943d4fba4f..587058bff3 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -99,6 +99,7 @@ import {
rtlStyles,
} from '../utils';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {menuPressLitRowStyle} from '../privateAttributes/menuPressLit.stylex';
import {getInteractionModality} from '../utils/interactionModality';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {useDevWarning} from '../hooks/useDevWarning';
@@ -146,7 +147,9 @@ const triggerStyles = stylex.create({
color: colorVars['--color-text-primary'],
backgroundColor: {
default: 'transparent',
- ':focus': colorVars['--color-overlay-hover'],
+ // menuPressLitRowStyle sets the variable on the row a held finger or pen
+ // lights.
+ ':focus': `var(--_menu-row-focus-paint, ${colorVars['--color-overlay-hover']})`,
},
borderWidth: 0,
borderStyle: 'none',
@@ -1243,6 +1246,7 @@ export function DropdownMenuSubMenu(
xstyle={[
focusOutlineStyles.focusVisible,
triggerStyles.root,
+ menuPressLitRowStyle,
triggerSizeStyles[menuSize],
isOpen && triggerStyles.open,
isDisabled && triggerStyles.disabled,
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuDragHighlight.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDragHighlight.interaction.browser.spec.ts
new file mode 100644
index 0000000000..3b4158e7cc
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDragHighlight.interaction.browser.spec.ts
@@ -0,0 +1,408 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuDragHighlight.interaction.browser.spec.ts
+ * @input The built Default DropdownMenu story under the harness's phone
+ * profile, with real finger, pen and mouse input (touch.ts, webInput.ts and
+ * Playwright's mouse)
+ * @output Interaction proofs that the highlight follows a held pointer
+ * (`spec:AST-094` FR27, FR43): dragged from the trigger across the rows,
+ * each enabled row lights in turn and nothing is lit once the pointer
+ * leaves the menu. Under a finger or a pen, the lit row is painted
+ * stronger than a row the keyboard focuses. Under a mouse, it keeps that
+ * hover tint. Under a desktop mouse, a press that begins on one row and
+ * drags onto another leaves the row under it told apart from the first.
+ * Under a desktop pen, only the row under it keeps the pressed overlay
+ * @position Evidence for the lit row's paint in DropdownMenu's rows; the
+ * press model's mark on that row is unit-tested in useMenuPress.test.tsx
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ frames,
+ openStory,
+ path,
+ PEN_SKIP,
+ touchDriver,
+ waitForRest,
+ webInputDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+const ROWS = ['Edit', 'Duplicate', 'Delete'] as const;
+
+/** The element's rendered box; a missing one fails the spec. */
+async function boxOf(locator: Locator) {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error('the element has no rendered box');
+ }
+ return box;
+}
+
+interface Layout {
+ trigger: Locator;
+ /** The trigger's center x and its bottom edge. */
+ x: number;
+ triggerBottom: number;
+ /** The open menu's bottom edge, and each row's vertical center. */
+ menuBottom: number;
+ rowCenters: Map<string, number>;
+ /** The alpha of a row's paint while the keyboard focuses it. */
+ keyboardAlpha: number;
+}
+
+/** The alpha of a computed `rgb()`/`rgba()` color: 0 for none. */
+function alphaOf(color: string): number {
+ const parts = color.match(/[\d.]+/g)?.map(Number) ?? [];
+ if (parts.length < 3) {
+ return 0;
+ }
+ return parts.length >= 4 ? parts[3] : 1;
+}
+
+async function paintOf(row: Locator): Promise<string> {
+ return row.evaluate(element => getComputedStyle(element).backgroundColor);
+}
+
+/**
+ * The story with the open menu measured once its entrance has come to rest:
+ * a tap opens it, the keyboard focuses its first row for the paint a
+ * keyboard focus gets, and Escape closes it again.
+ */
+async function openLayout(page: Page): Promise<Layout> {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ const driver = await touchDriver(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ const box = await boxOf(trigger);
+ const x = Math.round(box.x + box.width / 2);
+ await driver.tap({x, y: Math.round(box.y + box.height / 2)});
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const popover = page.locator('[popover]:has([role="menu"])').first();
+ await waitForRest(popover);
+ const rowCenters = new Map<string, number>();
+ for (const name of ROWS) {
+ const row = await boxOf(page.getByRole('menuitem', {name}));
+ rowCenters.set(name, row.y + row.height / 2);
+ }
+ const menu = await boxOf(popover);
+ await page.keyboard.press('ArrowDown');
+ const first = page.getByRole('menuitem', {name: ROWS[0]});
+ await expect(first).toBeFocused();
+ // Past any color transition.
+ await frames(page, 30);
+ const keyboardAlpha = alphaOf(await paintOf(first));
+ expect(keyboardAlpha).toBeGreaterThan(0);
+ await page.keyboard.press('Escape');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await waitForRest(popover);
+ return {
+ trigger,
+ x,
+ triggerBottom: box.y + box.height,
+ menuBottom: menu.y + menu.height,
+ rowCenters,
+ keyboardAlpha,
+ };
+}
+
+interface Frame {
+ /** The focused row's name, or null. */
+ readonly focused: string | null;
+ /** Each row's paint alpha, by name. */
+ readonly alpha: Readonly<Record<string, number>>;
+}
+
+/** Records, each frame, the focused row and every row's paint alpha. */
+async function recordFrames(page: Page) {
+ await page.evaluate(
+ names => {
+ const log: Frame[] = [];
+ (window as unknown as {__frames: Frame[]}).__frames = log;
+ const tick = () => {
+ const alpha: Record<string, number> = {};
+ let focused: string | null = null;
+ for (const row of document.querySelectorAll<HTMLElement>(
+ '[role="menuitem"]',
+ )) {
+ const name = row.textContent?.trim() ?? '';
+ if (!names.includes(name)) {
+ continue;
+ }
+ const parts =
+ getComputedStyle(row)
+ .backgroundColor.match(/[\d.]+/g)
+ ?.map(Number) ?? [];
+ alpha[name] =
+ parts.length >= 4 ? parts[3] : parts.length === 3 ? 1 : 0;
+ if (row === document.activeElement) {
+ focused = name;
+ }
+ }
+ log.push({focused, alpha});
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ },
+ ROWS as unknown as string[],
+ );
+}
+
+async function readFrames(page: Page): Promise<ReadonlyArray<Frame>> {
+ return page.evaluate(
+ () => (window as unknown as {__frames: Frame[]}).__frames,
+ );
+}
+
+/**
+ * Each enabled row lit in turn, and no row lit or painted once the pointer has
+ * left the menu. A `pressed` row is painted stronger than a keyboard focus; a
+ * `hover` one, as strong as it.
+ */
+function expectLitInTurn(
+ log: ReadonlyArray<Frame>,
+ keyboardAlpha: number,
+ paint: 'pressed' | 'hover',
+) {
+ const order: string[] = [];
+ const peak = new Map<string, number>();
+ for (const frame of log) {
+ if (frame.focused == null) {
+ continue;
+ }
+ if (order.at(-1) !== frame.focused) {
+ order.push(frame.focused);
+ }
+ peak.set(
+ frame.focused,
+ Math.max(peak.get(frame.focused) ?? 0, frame.alpha[frame.focused] ?? 0),
+ );
+ }
+ expect(order).toEqual([...ROWS]);
+ for (const name of ROWS) {
+ const lit = peak.get(name) ?? 0;
+ if (paint === 'pressed') {
+ expect(lit, `${name}'s paint while lit`).toBeGreaterThan(keyboardAlpha);
+ } else {
+ expect(lit, `${name}'s paint while lit`).toBeCloseTo(keyboardAlpha, 3);
+ }
+ }
+ const last = log.at(-1);
+ expect(last?.focused).toBeNull();
+ for (const name of ROWS) {
+ expect(last?.alpha[name], `${name}'s paint off the menu`).toBe(0);
+ }
+}
+
+test('a held finger dragged from the trigger across the rows lights each enabled row in turn, and none off the menu', async ({
+ page,
+}) => {
+ const layout = await openLayout(page);
+ const driver = await touchDriver(page);
+ await recordFrames(page);
+ const start = {x: layout.x, y: Math.floor(layout.triggerBottom) - 1};
+ const endY = Math.ceil(layout.menuBottom) + 40;
+ // The finger holds until the menu has opened under it, then slides down
+ // across every row and off the menu, and rests there before the lift.
+ await driver.play(
+ path(
+ progress =>
+ progress === 0
+ ? start
+ : {x: layout.x, y: start.y + (endY - start.y) * progress},
+ {holdMs: 1200, durationMs: 1800, hz: 30, restMs: 400},
+ ),
+ );
+ expectLitInTurn(await readFrames(page), layout.keyboardAlpha, 'pressed');
+});
+
+test('a held pen dragged from the trigger across the rows lights each enabled row in turn, and none off the menu', async ({
+ page,
+}) => {
+ const layout = await openLayout(page);
+ const pen = await webInputDriver(page);
+ test.skip(!pen.pens, PEN_SKIP);
+ await recordFrames(page);
+ const startY = Math.floor(layout.triggerBottom) - 1;
+ const endY = Math.ceil(layout.menuBottom) + 40;
+ const points = [
+ {x: layout.x, y: startY, t: 0},
+ {x: layout.x, y: startY, t: 1200},
+ ];
+ for (let step = 1; step <= 54; step++) {
+ points.push({
+ x: layout.x,
+ y: startY + ((endY - startY) * step) / 54,
+ t: 1200 + step * 33,
+ });
+ }
+ points.push({x: layout.x, y: endY, t: 1200 + 54 * 33 + 400});
+ await pen.pen(points);
+ expectLitInTurn(await readFrames(page), layout.keyboardAlpha, 'pressed');
+});
+
+test('a held mouse dragged from the trigger across the rows lights each enabled row in turn on the hover tint, and none off the menu', async ({
+ page,
+}) => {
+ const layout = await openLayout(page);
+ await recordFrames(page);
+ const triggerBox = await boxOf(layout.trigger);
+ await page.mouse.move(layout.x, triggerBox.y + triggerBox.height / 2);
+ await page.mouse.down();
+ await expect(layout.trigger).toHaveAttribute('aria-expanded', 'true');
+ for (const name of ROWS) {
+ await page.mouse.move(layout.x, layout.rowCenters.get(name) ?? 0, {
+ steps: 6,
+ });
+ await frames(page, 20);
+ }
+ await page.mouse.move(layout.x, Math.ceil(layout.menuBottom) + 40, {
+ steps: 6,
+ });
+ await frames(page, 20);
+ const log = await readFrames(page);
+ await page.mouse.up();
+ expectLitInTurn(log, layout.keyboardAlpha, 'hover');
+});
+
+test.describe('under a desktop mouse', () => {
+ // A desktop pointer hovers, so the row the press began on keeps its own
+ // `:active` paint while the press drags on.
+ test.use({
+ isMobile: false,
+ hasTouch: false,
+ viewport: {width: 1280, height: 720},
+ deviceScaleFactor: 1,
+ });
+
+ test('a press that begins on a row and drags onto another lights the row under it on the hover tint, told apart from the first', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.click();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await waitForRest(page.locator('[popover]:has([role="menu"])').first());
+ // The paint a keyboard focus gets, for the hover tint.
+ await page.keyboard.press('ArrowDown');
+ const first = page.getByRole('menuitem', {name: ROWS[0]});
+ await expect(first).toBeFocused();
+ await frames(page, 30);
+ const keyboardAlpha = alphaOf(await paintOf(first));
+ expect(keyboardAlpha).toBeGreaterThan(0);
+ const centerOf = async (name: string) => {
+ const box = await boxOf(page.getByRole('menuitem', {name}));
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ };
+ const edit = await centerOf('Edit');
+ const duplicate = await centerOf('Duplicate');
+ await page.mouse.move(edit.x, edit.y);
+ await page.mouse.down();
+ await frames(page, 20);
+ await page.mouse.move(duplicate.x, duplicate.y, {steps: 6});
+ await frames(page, 20);
+ const paints = {
+ Edit: alphaOf(await paintOf(page.getByRole('menuitem', {name: 'Edit'}))),
+ Duplicate: alphaOf(
+ await paintOf(page.getByRole('menuitem', {name: 'Duplicate'})),
+ ),
+ };
+ const focused = await page.evaluate(
+ () => document.activeElement?.textContent?.trim() ?? null,
+ );
+ await page.mouse.up();
+ expect(focused).toBe('Duplicate');
+ expect(paints.Duplicate).toBeCloseTo(keyboardAlpha, 3);
+ // The row the release acts on must not share the paint of the row the
+ // press began on.
+ expect(paints.Duplicate).not.toBeCloseTo(paints.Edit, 3);
+ });
+});
+
+test.describe('under a desktop pen', () => {
+ // A desktop pointer hovers, so a row a press began on would keep its own
+ // `:active` paint while a pen drags on.
+ test.use({
+ isMobile: false,
+ hasTouch: false,
+ viewport: {width: 1280, height: 720},
+ deviceScaleFactor: 1,
+ });
+
+ test('a press that begins on a row and drags onto another leaves only the row under it at the pressed overlay', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ const pen = await webInputDriver(page);
+ test.skip(!pen.pens, PEN_SKIP);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.click();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await waitForRest(page.locator('[popover]:has([role="menu"])').first());
+ const centerOf = async (name: string) => {
+ const box = await boxOf(page.getByRole('menuitem', {name}));
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ };
+ const edit = await centerOf('Edit');
+ const duplicate = await centerOf('Duplicate');
+ // Each frame's paints until the lift, which ends every row's `:active`.
+ await page.evaluate(() => {
+ const state = {isDown: true, frames: [] as [number, number][]};
+ (window as unknown as {__pen: typeof state}).__pen = state;
+ window.addEventListener(
+ 'pointerup',
+ () => {
+ state.isDown = false;
+ },
+ {capture: true, once: true},
+ );
+ const alpha = (name: string) => {
+ const row = [
+ ...document.querySelectorAll<HTMLElement>('[role="menuitem"]'),
+ ].find(each => each.textContent?.trim() === name);
+ const parts =
+ (row ? getComputedStyle(row).backgroundColor : '')
+ .match(/[\d.]+/g)
+ ?.map(Number) ?? [];
+ return parts.length >= 4 ? parts[3] : parts.length === 3 ? 1 : 0;
+ };
+ const tick = () => {
+ if (!state.isDown) {
+ return;
+ }
+ state.frames.push([alpha('Edit'), alpha('Duplicate')]);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+ const points = [
+ {x: edit.x, y: edit.y, t: 0},
+ {x: edit.x, y: edit.y, t: 300},
+ ];
+ for (let step = 1; step <= 12; step++) {
+ points.push({
+ x: edit.x + ((duplicate.x - edit.x) * step) / 12,
+ y: edit.y + ((duplicate.y - edit.y) * step) / 12,
+ t: 300 + step * 33,
+ });
+ }
+ points.push({x: duplicate.x, y: duplicate.y, t: 300 + 12 * 33 + 500});
+ await pen.pen(points);
+ const frames = await page.evaluate(
+ () =>
+ (window as unknown as {__pen: {frames: [number, number][]}}).__pen
+ .frames,
+ );
+ // The last frame before the lift: the pen rests on Duplicate.
+ const [editAlpha, duplicateAlpha] = frames.at(-1) ?? [Number.NaN, 0];
+ expect(duplicateAlpha).toBeGreaterThan(0);
+ expect(editAlpha).toBe(0);
+ });
+});
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuTouchHandoff.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuTouchHandoff.interaction.browser.spec.ts
new file mode 100644
index 0000000000..d2e1f5a102
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuTouchHandoff.interaction.browser.spec.ts
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuTouchHandoff.interaction.browser.spec.ts
+ * @input The built Default DropdownMenu story under the harness's phone
+ * profile, real touch input (Chromium CDP / WebKit's input command), and
+ * UIMenu's handoff distance from the UIKit constants table
+ * @output Interaction proofs for the finger that opened DropdownMenu from its
+ * trigger (`spec:AST-094` FR29): once the menu is open under the held
+ * finger, a move shorter than the handoff onto a row and a lift act on
+ * nothing and leave the menu open, however long the finger rested; a
+ * finger that travels past it picks the row it lifts on, once
+ * @position Evidence for the handoff in DropdownMenu (and MoreMenu, which
+ * renders it); the machine itself is unit-tested in menuPressGesture.test.ts
+ * and useMenuPress.test.tsx
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ frames,
+ openStory,
+ path,
+ touchDriver,
+ waitForRest,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
+
+const storybook = withStorybook(test);
+
+const HANDOFF_PX = UIKIT_GESTURES.menuPress.handoff.value;
+
+/** The element's rendered box; a missing one fails the spec. */
+async function boxOf(locator: Locator) {
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error('the element has no rendered box');
+ }
+ return box;
+}
+
+/** Page-side capture of the rows the story reports as picked. */
+async function installPickLog(page: Page) {
+ await page.evaluate(() => {
+ const picked: string[] = [];
+ (window as unknown as {__picked: string[]}).__picked = picked;
+ // The story reports a pick by logging "<label> clicked".
+ // eslint-disable-next-line no-console -- see above
+ const original = console.log.bind(console);
+ // eslint-disable-next-line no-console -- see above
+ console.log = (...args: unknown[]) => {
+ if (typeof args[0] === 'string' && args[0].endsWith(' clicked')) {
+ picked.push(args[0].replace(' clicked', ''));
+ }
+ original(...args);
+ };
+ });
+}
+
+const readPicked = async (page: Page) =>
+ page.evaluate(() => (window as unknown as {__picked: string[]}).__picked);
+
+interface Layout {
+ driver: TouchDriver;
+ trigger: Locator;
+ /** The trigger's bottom edge, its center x, and the rows' boxes. */
+ triggerBottom: number;
+ x: number;
+ rows: Map<string, {top: number; bottom: number}>;
+}
+
+/**
+ * The story under a finger, with the open menu's rows measured once its
+ * entrance has come to rest: a tap opens it (its lift's click), Escape
+ * closes it again.
+ */
+async function openLayout(page: Page): Promise<Layout> {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ await installPickLog(page);
+ const driver = await touchDriver(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ const box = await boxOf(trigger);
+ const x = Math.round(box.x + box.width / 2);
+ await driver.tap({x, y: Math.round(box.y + box.height / 2)});
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const popover = page.locator('[popover]:has([role="menu"])').first();
+ await waitForRest(popover);
+ const rows = new Map<string, {top: number; bottom: number}>();
+ for (const name of ['Edit', 'Duplicate']) {
+ const row = await boxOf(page.getByRole('menuitem', {name}));
+ rows.set(name, {top: row.y, bottom: row.y + row.height});
+ }
+ await page.keyboard.press('Escape');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await waitForRest(popover);
+ return {driver, trigger, triggerBottom: box.y + box.height, x, rows};
+}
+
+test('a move shorter than the handoff onto a row, after the menu opened under the held finger, picks nothing and leaves it open', async ({
+ page,
+}) => {
+ const layout = await openLayout(page);
+ const edit = layout.rows.get('Edit');
+ if (edit == null) {
+ throw new Error('no Edit row');
+ }
+ // The finger rests on the trigger's edge nearest the menu until the menu
+ // is open and the press has long settled, then moves 1 px (the first
+ // sample the menu sees, where the distance counts from) and on, short of
+ // the handoff, onto the first row.
+ const start = {x: layout.x, y: Math.floor(layout.triggerBottom) - 1};
+ const origin = {x: layout.x, y: start.y + 1};
+ const end = {x: layout.x, y: Math.ceil(edit.top) + 1};
+ expect(end.y - origin.y).toBeLessThan(HANDOFF_PX);
+ expect(end.y).toBeLessThan(edit.bottom);
+ await layout.driver.play(
+ path(
+ progress =>
+ progress === 0
+ ? start
+ : {x: layout.x, y: origin.y + (end.y - origin.y) * progress},
+ {holdMs: 1200, durationMs: 120, hz: 30, restMs: 150},
+ ),
+ );
+ await frames(page, 2);
+ expect(await readPicked(page)).toEqual([]);
+ await expect(layout.trigger).toHaveAttribute('aria-expanded', 'true');
+});
+
+test('the finger that opened the menu picks the row it lifts on once it has travelled past the handoff, once', async ({
+ page,
+}) => {
+ const layout = await openLayout(page);
+ const duplicate = layout.rows.get('Duplicate');
+ if (duplicate == null) {
+ throw new Error('no Duplicate row');
+ }
+ const start = {x: layout.x, y: Math.floor(layout.triggerBottom) - 1};
+ const end = {
+ x: layout.x,
+ y: Math.round((duplicate.top + duplicate.bottom) / 2),
+ };
+ expect(end.y - start.y).toBeGreaterThan(HANDOFF_PX);
+ await layout.driver.play(
+ path(
+ progress => ({
+ x: layout.x,
+ y: start.y + (end.y - start.y) * progress,
+ }),
+ {holdMs: 800, durationMs: 250, hz: 60, restMs: 100},
+ ),
+ );
+ await expect(layout.trigger).toHaveAttribute('aria-expanded', 'false');
+ await frames(page, 2);
+ expect(await readPicked(page)).toEqual(['Duplicate']);
+});
diff --git a/packages/core/src/MoreMenu/MoreMenu.doc.mjs b/packages/core/src/MoreMenu/MoreMenu.doc.mjs
index 514bc166cb..202e323019 100644
--- a/packages/core/src/MoreMenu/MoreMenu.doc.mjs
+++ b/packages/core/src/MoreMenu/MoreMenu.doc.mjs
@@ -104,8 +104,7 @@ export const docs = {
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
- description: 'Presentation policy forwarded to DropdownMenu. `adaptive` keeps the anchored popover on pointer-based layouts and uses a BottomSheet on a compact touch screen: a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px.',
- default: "'popover'",
+ description: 'Presentation policy forwarded to DropdownMenu. `adaptive` keeps the anchored popover on pointer-based layouts and uses a BottomSheet on a compact touch screen: a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px. Omitted, the menu is the anchored popover, and under a finger, on every device, the finger that opened it picks a row only after moving 10 px. Pass \'popover\' to keep the pointer behavior on every device, the settle rule included.',
},
{
name: 'onOpenChange',
@@ -204,8 +203,7 @@ export const docsZh = {
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
- description: '菜单呈现策略。`adaptive` 在指针布局中使用锚定浮层,在主指针为粗略指针且视口宽度小于主题的 `md` 断点(默认 768px)或高度小于 500px 时使用 BottomSheet。',
- default: "'popover'",
+ description: '菜单呈现策略。`adaptive` 在指针布局中使用锚定浮层,在主指针为粗略指针且视口宽度小于主题的 `md` 断点(默认 768px)或高度小于 500px 时使用 BottomSheet。省略时,菜单为锚定浮层;在任何设备上用手指操作时,打开菜单的手指移动 10 px 后才会选择菜单项。传入 \'popover\' 可在所有设备上保持指针行为,包括稳定规则。',
},
{
name: 'xstyle',
diff --git a/packages/core/src/MoreMenu/MoreMenu.tsx b/packages/core/src/MoreMenu/MoreMenu.tsx
index 4054286ebf..3f83d7a4b7 100644
--- a/packages/core/src/MoreMenu/MoreMenu.tsx
+++ b/packages/core/src/MoreMenu/MoreMenu.tsx
@@ -97,9 +97,11 @@ export interface MoreMenuProps extends Pick<
alignment?: LayerAlignment;
/**
- * Menu presentation policy. `adaptive` uses a BottomSheet on compact
- * coarse-pointer viewports and an anchored popover elsewhere.
- * @default 'popover'
+ * Menu presentation policy, forwarded to DropdownMenu. `adaptive` uses a
+ * BottomSheet on compact coarse-pointer viewports and an anchored popover
+ * elsewhere. Omitted, the menu is the anchored popover, and the finger that
+ * opened it follows UIMenu's handoff on every device. `'popover'` pins the
+ * pointer behavior on every device.
*/
presentation?: DropdownMenuPresentation;
diff --git a/packages/core/src/hooks/menuPressGesture.test.ts b/packages/core/src/hooks/menuPressGesture.test.ts
index 8ec3f80468..08ddc8923e 100644
--- a/packages/core/src/hooks/menuPressGesture.test.ts
+++ b/packages/core/src/hooks/menuPressGesture.test.ts
@@ -10,19 +10,22 @@
import {describe, it, expect} from 'vitest';
import {
IDLE_MENU_PRESS,
+ MENU_PRESS_HANDOFF_PX,
MENU_PRESS_SETTLE_MS,
menuPressStep,
+ menuPressTransition,
+ type MenuPressInput,
+ type MenuPressState,
type MenuPressEvent,
- type MenuPressGesture,
} from './menuPressGesture';
type Row = 'A' | 'B';
-function run(events: MenuPressEvent<Row>[]) {
- let gesture: MenuPressGesture<Row> = IDLE_MENU_PRESS;
+function run(events: MenuPressInput<Row>[]) {
+ let gesture: MenuPressState<Row> = IDLE_MENU_PRESS;
const effects = [];
for (const event of events) {
- const step = menuPressStep(gesture, event);
+ const step = menuPressTransition(gesture, event);
gesture = step.gesture;
effects.push(step.effect);
}
@@ -33,7 +36,7 @@ const downInMenu = (
row: Row | null,
pointerType: 'mouse' | 'touch' = 'touch',
) => ({type: 'down', target: 'menu', pointerType, row, time: 0}) as const;
-const downOnTrigger = (pointerType: 'mouse' | 'touch', time = 0) =>
+const downOnTrigger = (pointerType: 'mouse' | 'touch' | 'pen', 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;
@@ -119,10 +122,10 @@ describe('menuPressStep — inside the menu', () => {
});
it('ignores a move or a release with no gesture live', () => {
- expect(menuPressStep(IDLE_MENU_PRESS, move('A')).effect).toEqual({
+ expect(menuPressTransition(IDLE_MENU_PRESS, move('A')).effect).toEqual({
type: 'none',
});
- expect(menuPressStep(IDLE_MENU_PRESS, up('A')).effect).toEqual({
+ expect(menuPressTransition(IDLE_MENU_PRESS, up('A')).effect).toEqual({
type: 'none',
});
});
@@ -251,3 +254,213 @@ describe('menuPressStep — the trigger', () => {
expect(last).toEqual({type: 'settle', stray: false, dismiss: false});
});
});
+
+describe('menuPressStep — a finger that opened the menu hands off after travelling (UIMenu)', () => {
+ // UIKit on iOS 26.2: the menu opens under a held finger; the finger picks
+ // only once it has moved the handoff distance from the first sample the
+ // menu saw. Positions are viewport px.
+ const held = (pointerType: 'touch' | 'pen' = 'touch') =>
+ [
+ downOnTrigger(pointerType, 0),
+ {type: 'opened', time: 150},
+ ] as MenuPressInput<Row>[];
+ const moveTo = (x: number, y: number, row: Row | null = 'A', time = 400) =>
+ ({type: 'move', row, isInMenu: row != null, time, x, y}) as const;
+ const upAt = (
+ x: number,
+ y: number,
+ row: Row | null = 'A',
+ {isInMenu = row != null, isOnTrigger = false, time = 600} = {},
+ ) => ({type: 'up', row, isInMenu, isOnTrigger, time, x, y}) as const;
+
+ it('the handoff distance is the one in the UIKit constants table', () => {
+ expect(MENU_PRESS_HANDOFF_PX).toBe(10);
+ });
+
+ it('Open → Idle: the opening finger lifted without moving picks nothing, however long it rested', () => {
+ for (const time of [200, 600, 5000]) {
+ const {gesture, last} = run([...held(), upAt(200, 182, 'A', {time})]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ }
+ });
+
+ it('Open → Open: the first sample after the open is where the distance counts from', () => {
+ const {gesture, last} = run([...held(), moveTo(200, 189)]);
+ expect(gesture).toMatchObject({
+ phase: 'open',
+ handoffFrom: {x: 200, y: 189},
+ });
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('Open → Open: under the handoff distance nothing is highlighted', () => {
+ const {gesture, last} = run([
+ ...held(),
+ moveTo(200, 189),
+ moveTo(200, 189 + MENU_PRESS_HANDOFF_PX - 1),
+ ]);
+ expect(gesture.phase).toBe('open');
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('Open → Tracking: at the handoff distance the highlight follows the finger', () => {
+ const {gesture, last} = run([
+ ...held(),
+ moveTo(200, 189),
+ moveTo(200, 189 + MENU_PRESS_HANDOFF_PX, 'B'),
+ ]);
+ expect(gesture).toMatchObject({
+ phase: 'tracking',
+ origin: 'trigger',
+ row: 'B',
+ });
+ expect(last).toEqual({type: 'highlight', row: 'B'});
+ });
+
+ it('counts from the first sample, not from where the finger was when the menu opened (b4 capture: 7.3 pt, then 11 pt)', () => {
+ // The finger rested at y 182 when the menu opened; samples then came at
+ // 189.33, 196.67 (14.7 from the open point, 7.3 from the first sample)
+ // and 200.33 (11 from the first sample), where UIKit began.
+ const samples = [189.33, 196.67, 200.33];
+ const phases = samples.map(
+ (_, i) =>
+ run([...held(), ...samples.slice(0, i + 1).map(y => moveTo(200, y))])
+ .gesture.phase,
+ );
+ expect(phases).toEqual(['open', 'open', 'tracking']);
+ });
+
+ it('measures a straight-line distance, as UIMenu does (iOS 26.2: after a 1 pt first step)', () => {
+ // UIKit lab: (0, 9) and (7, 7) [9.9] pick nothing; (0, 10), (10, 0) and
+ // (9, 9) [12.7] pick.
+ const phaseAfter = (dx: number, dy: number) =>
+ run([...held(), moveTo(100, 100), moveTo(100 + dx, 100 + dy)]).gesture
+ .phase;
+ expect(phaseAfter(0, 9)).toBe('open');
+ expect(phaseAfter(7, 7)).toBe('open');
+ expect(phaseAfter(0, 10)).toBe('tracking');
+ expect(phaseAfter(10, 0)).toBe('tracking');
+ expect(phaseAfter(9, 9)).toBe('tracking');
+ expect(phaseAfter(0, -10)).toBe('tracking');
+ });
+
+ it('counts from the first sample, not from where the finger was at the open (iOS 26.2: a 9 pt step, then 3 more, picks nothing)', () => {
+ const {gesture, last} = run([
+ ...held(),
+ moveTo(200, 191),
+ moveTo(200, 194),
+ upAt(200, 194, 'A'),
+ ]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Open → Tracking → Acted: after the handoff, the lift acts on the row under it', () => {
+ const {last} = run([
+ ...held(),
+ moveTo(200, 189),
+ moveTo(200, 230, 'A'),
+ moveTo(200, 280, 'B'),
+ upAt(200, 292, 'B'),
+ ]);
+ expect(last).toEqual({type: 'act', row: 'B'});
+ });
+
+ it('Open → Idle: a finger that moved under the distance and lifted over a row picks nothing', () => {
+ const {last} = run([
+ ...held(),
+ moveTo(200, 189),
+ moveTo(200, 195),
+ upAt(200, 195, 'A'),
+ ]);
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('a pen follows the finger rules', () => {
+ expect(run([...held('pen'), upAt(200, 182, 'A')]).last).toEqual({
+ type: 'settle',
+ stray: true,
+ dismiss: false,
+ });
+ });
+
+ it('a mouse keeps the settle rule: entering the menu tracks at once', () => {
+ const {gesture, last} = run([
+ downOnTrigger('mouse', 0),
+ moveTo(200, 189, 'A', 40),
+ ]);
+ expect(gesture).toMatchObject({phase: 'tracking', row: 'A'});
+ expect(last).toEqual({type: 'highlight', row: 'A'});
+ expect(
+ run([
+ downOnTrigger('mouse', 0),
+ upAt(200, 182, 'A', {time: MENU_PRESS_SETTLE_MS}),
+ ]).last,
+ ).toEqual({type: 'act', row: 'A'});
+ });
+});
+
+describe('menuPressStep, the released public machine', () => {
+ it('keeps the settle rule when a caller\u2019s events carry positions: the opening finger picks the row it lifts on', () => {
+ type Positioned = MenuPressEvent<Row> & {x: number; y: number};
+ let gesture = menuPressStep<Row>(IDLE_MENU_PRESS, {
+ type: 'down',
+ target: 'trigger',
+ pointerType: 'touch',
+ row: null,
+ time: 0,
+ }).gesture;
+ gesture = menuPressStep(gesture, {type: 'opened', time: 500}).gesture;
+ const move: Positioned = {
+ type: 'move',
+ row: 'B' as Row,
+ isInMenu: true,
+ time: 1000,
+ x: 0,
+ y: 60,
+ };
+ gesture = menuPressStep(gesture, move).gesture;
+ const up: Positioned = {
+ type: 'up',
+ row: 'B' as Row,
+ isInMenu: true,
+ isOnTrigger: false,
+ time: 1100,
+ x: 0,
+ y: 60,
+ };
+ expect(menuPressStep(gesture, up).effect).toEqual({type: 'act', row: 'B'});
+ });
+
+ it('keeps the released shapes: no handoff state', () => {
+ let gesture = menuPressStep(IDLE_MENU_PRESS, {
+ type: 'down',
+ target: 'menu',
+ pointerType: 'touch',
+ row: 'A' as Row,
+ time: 0,
+ }).gesture;
+ gesture = menuPressStep(gesture, {
+ type: 'move',
+ row: 'B' as Row,
+ isInMenu: true,
+ time: 10,
+ }).gesture;
+ const {effect} = menuPressStep(gesture, {type: 'cancel'});
+ expect(effect).toEqual({type: 'settle', stray: false, dismiss: false});
+ const opened = menuPressStep(
+ menuPressStep(IDLE_MENU_PRESS, {
+ type: 'down',
+ target: 'trigger',
+ pointerType: 'touch',
+ row: null,
+ time: 0,
+ }).gesture,
+ {type: 'opened', time: 500},
+ ).gesture;
+ expect(Object.keys(opened).sort()).toEqual(
+ ['openedAt', 'phase', 'pointerType'].sort(),
+ );
+ });
+});
diff --git a/packages/core/src/hooks/menuPressGesture.ts b/packages/core/src/hooks/menuPressGesture.ts
index 362cb57961..c707c1a673 100644
--- a/packages/core/src/hooks/menuPressGesture.ts
+++ b/packages/core/src/hooks/menuPressGesture.ts
@@ -4,7 +4,7 @@
* @file menuPressGesture.ts
* @input A menu press gesture and one pointer event, both as plain data
* @output The pure `menuPressStep` state machine, its state, event and effect
- * types, and the settle constant
+ * types, the settle constant, and the finger's handoff distance
* @position Pure module under `useMenuPress`. It has no DOM and no React, so
* a unit test can check each transition without a browser.
*
@@ -13,12 +13,24 @@
* - /packages/core/src/hooks/useMenuPress.ts
*/
-/** How long the opening press must last before its release may act. */
+import {MENU_PRESS_HANDOFF_PX as UIKIT_MENU_PRESS_HANDOFF_PX} from './menuPressValues';
+
+/**
+ * How long the opening press must last before its release may act, unless a
+ * finger's handoff applies.
+ */
export const MENU_PRESS_SETTLE_MS = 300;
+/**
+ * How far a finger that opened the menu travels, from the first sample the
+ * menu sees, before it starts picking (UIMenu's scrub handoff).
+ */
+export const MENU_PRESS_HANDOFF_PX: number = UIKIT_MENU_PRESS_HANDOFF_PX;
+
export type MenuPressPointerType = 'mouse' | 'touch' | 'pen';
-export type MenuPressGesture<T> =
+/** @internal The machine's own shape, with the finger's handoff; not public contract. */
+export type MenuPressState<T> =
| {phase: 'idle'}
| {
phase: 'triggerPress';
@@ -29,6 +41,12 @@ export type MenuPressGesture<T> =
phase: 'open';
pointerType: MenuPressPointerType;
openedAt: number;
+ /**
+ * A finger's handoff: the first position the menu saw after it opened,
+ * which the scrub distance is counted from. Unset until that sample.
+ * @internal Not public contract.
+ */
+ handoffFrom?: {x: number; y: number};
}
| {
phase: 'tracking';
@@ -39,7 +57,8 @@ export type MenuPressGesture<T> =
row: T | null;
};
-export type MenuPressEvent<T> =
+/** @internal The machine's own shape, with the finger's handoff; not public contract. */
+export type MenuPressInput<T> =
| {
type: 'down';
target: 'trigger' | 'menu';
@@ -50,18 +69,38 @@ export type MenuPressEvent<T> =
}
/** The menu opened while the trigger press is still held. */
| {type: 'opened'; time: number}
- | {type: 'move'; row: T | null; isInMenu: boolean; time: number}
+ | {
+ type: 'move';
+ row: T | null;
+ isInMenu: boolean;
+ time: number;
+ /**
+ * Viewport position, for a finger's handoff distance.
+ * @internal Not public contract.
+ */
+ x?: number;
+ /** @internal See `x`. */
+ y?: number;
+ }
| {
type: 'up';
row: T | null;
isInMenu: boolean;
isOnTrigger: boolean;
time: number;
+ /**
+ * Viewport position, for a finger's handoff distance.
+ * @internal Not public contract.
+ */
+ x?: number;
+ /** @internal See `x`. */
+ y?: number;
}
/** The browser took the gesture: pointercancel, a second pointer, a scroll. */
| {type: 'cancel'};
-export type MenuPressEffect<T> =
+/** @internal The machine's own shape, with the finger's handoff; not public contract. */
+export type MenuPressOutcome<T> =
| {type: 'none'}
/** A mouse pressed the trigger: open the menu now, under the held pointer. */
| {type: 'open'}
@@ -71,27 +110,52 @@ export type MenuPressEffect<T> =
/**
* The gesture ended without a row acting. `stray` says whether the browser
* will still report a `click` for this gesture that must not act; `dismiss`
- * says the menu should close (a mouse released outside it).
+ * says the menu should close: a mouse released outside it.
*/
| {type: 'settle'; stray: boolean; dismiss: boolean};
-export interface MenuPressStep<T> {
- gesture: MenuPressGesture<T>;
- effect: MenuPressEffect<T>;
+/** @internal The machine's own shape, with the finger's handoff; not public contract. */
+export interface MenuPressTransition<T> {
+ gesture: MenuPressState<T>;
+ effect: MenuPressOutcome<T>;
}
-export const IDLE_MENU_PRESS: MenuPressGesture<never> = {phase: 'idle'};
+export const IDLE_MENU_PRESS: MenuPressState<never> = {phase: 'idle'};
-const NONE: MenuPressEffect<never> = {type: 'none'};
+const NONE: MenuPressOutcome<never> = {type: 'none'};
-function idle<T>(effect: MenuPressEffect<T>): MenuPressStep<T> {
+function idle<T>(effect: MenuPressOutcome<T>): MenuPressTransition<T> {
return {gesture: {phase: 'idle'}, effect};
}
-function highlightEffect<T>(row: T | null): MenuPressEffect<T> {
+function highlightEffect<T>(row: T | null): MenuPressOutcome<T> {
return row == null ? {type: 'clear'} : {type: 'highlight', row};
}
+/** A finger or a pen: UIKit's touch rules apply. */
+function isFinger(pointerType: MenuPressPointerType): boolean {
+ return pointerType !== 'mouse';
+}
+
+function hasPosition(event: {
+ x?: number;
+ y?: number;
+}): event is {x: number; y: number} {
+ return event.x != null && event.y != null;
+}
+
+/**
+ * Whether a finger has travelled the handoff distance from `from`. The
+ * distance is a straight line, as UIMenu measures it: a diagonal 7 pt each
+ * way does not hand off, 9 pt each way does.
+ */
+function hasPassedHandoff(
+ from: {x: number; y: number},
+ to: {x: number; y: number},
+): boolean {
+ return Math.hypot(to.x - from.x, to.y - from.y) >= MENU_PRESS_HANDOFF_PX;
+}
+
/**
* Resolve a release while the highlight is tracking the pointer: over an
* enabled row it acts, over the menu's chrome it acts on nothing, outside the
@@ -100,8 +164,8 @@ function highlightEffect<T>(row: T | null): MenuPressEffect<T> {
*/
function release<T>(
pointerType: MenuPressPointerType,
- event: Extract<MenuPressEvent<T>, {type: 'up'}>,
-): MenuPressStep<T> {
+ event: Extract<MenuPressInput<T>, {type: 'up'}>,
+): MenuPressTransition<T> {
if (event.row != null) {
return idle({type: 'act', row: event.row});
}
@@ -119,10 +183,15 @@ function release<T>(
* - `idle`: no gesture is live.
* - `triggerPress`: a finger rests on the trigger, and the menu is not open
* yet. A mouse press on the trigger skips this state and opens at once.
- * - `open`: the menu opened under a held pointer, and the pointer has not
- * entered it yet.
+ * - `open`: the menu opened under a held pointer, and the pointer does not
+ * pick yet.
* - `tracking`: the pointer is held, and the highlight follows it.
*
+ * A finger or a pen that opened the menu picks only after it travels
+ * `MENU_PRESS_HANDOFF_PX` from the first position the menu sees. UIMenu
+ * hands off the same way. Until then nothing lights, and its lift acts on
+ * nothing. A host that reports no positions keeps the settle rule.
+ *
* The settle rule: the release of the opening gesture acts only after the
* pointer entered the menu or the press lasted `MENU_PRESS_SETTLE_MS`. Else a
* menu that opens under the pointer would pick a row that nobody chose.
@@ -130,11 +199,14 @@ function release<T>(
* Rows are opaque (`T`). The hook feeds in the enabled row under the
* pointer, or `null` over a divider, a heading, a disabled row, or outside
* the menu.
+ *
+ * @internal The machine's own shape, with the finger's handoff; not public
+ * contract.
*/
-export function menuPressStep<T>(
- gesture: MenuPressGesture<T>,
- event: MenuPressEvent<T>,
-): MenuPressStep<T> {
+export function menuPressTransition<T>(
+ gesture: MenuPressState<T>,
+ event: MenuPressInput<T>,
+): MenuPressTransition<T> {
switch (gesture.phase) {
case 'idle':
return stepIdle(gesture, event);
@@ -148,9 +220,9 @@ export function menuPressStep<T>(
}
function stepIdle<T>(
- gesture: Extract<MenuPressGesture<T>, {phase: 'idle'}>,
- event: MenuPressEvent<T>,
-): MenuPressStep<T> {
+ gesture: Extract<MenuPressState<T>, {phase: 'idle'}>,
+ event: MenuPressInput<T>,
+): MenuPressTransition<T> {
if (event.type !== 'down') {
return {gesture, effect: NONE};
}
@@ -186,9 +258,9 @@ function stepIdle<T>(
}
function stepTriggerPress<T>(
- gesture: Extract<MenuPressGesture<T>, {phase: 'triggerPress'}>,
- event: MenuPressEvent<T>,
-): MenuPressStep<T> {
+ gesture: Extract<MenuPressState<T>, {phase: 'triggerPress'}>,
+ event: MenuPressInput<T>,
+): MenuPressTransition<T> {
switch (event.type) {
case 'opened':
return {
@@ -216,11 +288,34 @@ function stepTriggerPress<T>(
}
function stepOpen<T>(
- gesture: Extract<MenuPressGesture<T>, {phase: 'open'}>,
- event: MenuPressEvent<T>,
-): MenuPressStep<T> {
+ gesture: Extract<MenuPressState<T>, {phase: 'open'}>,
+ event: MenuPressInput<T>,
+): MenuPressTransition<T> {
switch (event.type) {
- case 'move':
+ case 'move': {
+ if (isFinger(gesture.pointerType) && hasPosition(event)) {
+ // UIMenu counts from the first sample after the open, not from the
+ // open point.
+ const from = gesture.handoffFrom;
+ if (from == null) {
+ return {
+ gesture: {...gesture, handoffFrom: {x: event.x, y: event.y}},
+ effect: NONE,
+ };
+ }
+ if (!hasPassedHandoff(from, event)) {
+ return {gesture, effect: NONE};
+ }
+ return {
+ gesture: {
+ phase: 'tracking',
+ pointerType: gesture.pointerType,
+ origin: 'trigger',
+ row: event.row,
+ },
+ effect: highlightEffect(event.row),
+ };
+ }
if (!event.isInMenu) {
return {gesture, effect: NONE};
}
@@ -233,7 +328,14 @@ function stepOpen<T>(
},
effect: highlightEffect(event.row),
};
+ }
case 'up': {
+ if (isFinger(gesture.pointerType) && hasPosition(event)) {
+ // The finger never travelled the handoff distance, so the row under it
+ // appeared under a press nobody moved. Nothing acts, the menu stays,
+ // and the trigger's click for this press is spent.
+ return idle({type: 'settle', stray: true, dismiss: false});
+ }
const hasSettled = event.time - gesture.openedAt >= MENU_PRESS_SETTLE_MS;
if (!hasSettled) {
// The pointer never entered the menu and the press was short: the
@@ -245,7 +347,7 @@ function stepOpen<T>(
}
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.
+ // menu stays open: a cancelled pointer did not ask to close it.
return idle({type: 'settle', stray: false, dismiss: false});
case 'down':
case 'opened':
@@ -254,11 +356,11 @@ function stepOpen<T>(
}
function stepTracking<T>(
- gesture: Extract<MenuPressGesture<T>, {phase: 'tracking'}>,
- event: MenuPressEvent<T>,
-): MenuPressStep<T> {
+ gesture: Extract<MenuPressState<T>, {phase: 'tracking'}>,
+ event: MenuPressInput<T>,
+): MenuPressTransition<T> {
switch (event.type) {
- case 'move': {
+ case 'move':
if (event.row === gesture.row) {
return {gesture, effect: NONE};
}
@@ -266,7 +368,6 @@ function stepTracking<T>(
gesture: {...gesture, row: event.row},
effect: highlightEffect(event.row),
};
- }
case 'up':
return release(gesture.pointerType, event);
case 'cancel':
@@ -278,3 +379,107 @@ function stepTracking<T>(
return {gesture, effect: NONE};
}
}
+
+// ---------------------------------------------------------------------------
+// The released public shape (`@astryxdesign/core/hooks`). The handoff
+// positions and `handoffFrom` stay internal: a caller of
+// `menuPressStep` keeps the settle rule, as released.
+// ---------------------------------------------------------------------------
+
+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;
+ };
+
+export type MenuPressEvent<T> =
+ | {
+ type: 'down';
+ target: 'trigger' | 'menu';
+ pointerType: MenuPressPointerType;
+ /** 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';
+ row: T | null;
+ isInMenu: boolean;
+ isOnTrigger: boolean;
+ time: number;
+ }
+ /** The browser took the gesture: pointercancel, a second pointer, a scroll. */
+ | {type: 'cancel'};
+
+export type MenuPressEffect<T> =
+ | {type: 'none'}
+ /** 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}
+ /**
+ * The gesture ended without a row acting. `stray` says whether the browser
+ * will still report a `click` for this gesture that must not act; `dismiss`
+ * says the menu should close (a mouse released outside it).
+ */
+ | {type: 'settle'; stray: boolean; dismiss: boolean};
+
+export interface MenuPressStep<T> {
+ gesture: MenuPressGesture<T>;
+ effect: MenuPressEffect<T>;
+}
+
+/**
+ * The menu press machine, as released: one step from a gesture and an event
+ * to the next gesture and the effect to apply. Pure.
+ */
+export function menuPressStep<T>(
+ gesture: MenuPressGesture<T>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ // The released machine keeps the settle rule. Positions start the handoff,
+ // so a caller's event reaches the transition without them.
+ const {
+ x: _x,
+ y: _y,
+ ...released
+ } = event as MenuPressEvent<T> & {x?: number; y?: number};
+ const {gesture: next, effect} = menuPressTransition(
+ gesture,
+ released as MenuPressEvent<T>,
+ );
+ return {
+ gesture: publicGesture(next),
+ effect,
+ };
+}
+
+function publicGesture<T>(gesture: MenuPressState<T>): MenuPressGesture<T> {
+ if (gesture.phase !== 'open') {
+ return gesture;
+ }
+ return {
+ phase: 'open',
+ pointerType: gesture.pointerType,
+ openedAt: gesture.openedAt,
+ };
+}
diff --git a/packages/core/src/hooks/menuPressValues.test.ts b/packages/core/src/hooks/menuPressValues.test.ts
new file mode 100644
index 0000000000..ad7efd867e
--- /dev/null
+++ b/packages/core/src/hooks/menuPressValues.test.ts
@@ -0,0 +1,11 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {UIKIT_GESTURES} from '../motion/uikit/gestures';
+import {MENU_PRESS_HANDOFF_PX} from './menuPressValues';
+
+describe('menuPressValues', () => {
+ it('copies the UIKit table exactly', () => {
+ expect(MENU_PRESS_HANDOFF_PX).toBe(UIKIT_GESTURES.menuPress.handoff.value);
+ });
+});
diff --git a/packages/core/src/hooks/menuPressValues.ts b/packages/core/src/hooks/menuPressValues.ts
new file mode 100644
index 0000000000..e9ffedfe5f
--- /dev/null
+++ b/packages/core/src/hooks/menuPressValues.ts
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menuPressValues.ts
+ * @input None
+ * @output The UIKit value the menu press model reads
+ * @position A copy of one UIKit table entry, motion/uikit gestures.ts
+ * `UIKIT_MENU_PRESS.handoff`. A menu then bundles this number, not the
+ * table with its measurement records. The table stays the source and
+ * documents the measurement. menuPressValues.test.ts fails when the copy
+ * drifts.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/motion/uikit/gestures.ts
+ */
+
+/** How far the opening finger travels after the menu opens before it picks. */
+export const MENU_PRESS_HANDOFF_PX = 10;
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index f2a7f13c0c..8be9db06d1 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -10,6 +10,8 @@
* is covered by menuPressGesture.test.ts.
*/
+import {readFileSync} from 'node:fs';
+import {resolve} from 'node:path';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, fireEvent, render, screen, within} from '@testing-library/react';
import {useRef, useState} from 'react';
@@ -18,9 +20,14 @@ import {
MENU_PRESS_LONG_PRESS_MS,
MENU_PRESS_STRAY_CLICK_MS,
__resetMenuPressForTest,
+ useDropdownMenuPress,
useMenuPress,
} from './useMenuPress';
-import {MENU_PRESS_SETTLE_MS} from './menuPressGesture';
+import {MENU_PRESS_HANDOFF_PX, MENU_PRESS_SETTLE_MS} from './menuPressGesture';
+import {
+ isMenuPressLit,
+ isMenuPressPaintHeld,
+} from '../privateAttributes/menuPressLit.stylex';
const ITEM_SELECTOR = '[role="menuitem"]:not([aria-disabled="true"])';
@@ -31,6 +38,7 @@ interface HarnessProps {
hitTest?: (x: number, y: number) => Element | null;
getScroller?: () => HTMLElement | null;
onHighlight?: (row: HTMLElement | null) => void;
+ touchModel?: 'pointer' | 'uikit';
}
function Harness({
@@ -40,6 +48,7 @@ function Harness({
hitTest,
getScroller,
onHighlight,
+ touchModel,
}: HarnessProps) {
const menuRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
@@ -48,7 +57,9 @@ function Harness({
setIsOpen(next);
onOpenChange?.(next);
};
- const press = useMenuPress({
+ // DropdownMenu's own entry, so the harness can also drive its touch model;
+ // without `touchModel` it behaves as the public hook.
+ const press = useDropdownMenuPress({
menuRef,
triggerRef,
itemSelector: ITEM_SELECTOR,
@@ -64,6 +75,7 @@ function Harness({
hitTest,
getScroller,
onHighlight,
+ touchModel,
});
return (
<>
@@ -232,6 +244,120 @@ describe('useMenuPress — tracking inside the menu', () => {
});
});
+describe('useMenuPress — the row a held press lights (spec:AST-094 FR27, FR43)', () => {
+ const lit = () =>
+ screen
+ .getAllByRole('menuitem')
+ .filter(each => isMenuPressLit(each))
+ .map(each => each.textContent);
+
+ it.each([
+ ['finger', touch()],
+ ['pen', {pointerType: 'pen', pointerId: 1}],
+ ])(
+ 'marks the row under a held %s as it moves, no row off the rows, and none once the press ends',
+ (_name, pointer) => {
+ render(<Harness />);
+ fireEvent.pointerDown(row('A'), pointer);
+ expect(lit()).toEqual(['A']);
+ fireEvent.pointerMove(row('B'), pointer);
+ expect(lit()).toEqual(['B']);
+ fireEvent.pointerMove(row('C'), pointer);
+ expect(lit()).toEqual(['C']);
+ fireEvent.pointerMove(screen.getByTestId('divider'), pointer);
+ expect(lit()).toEqual([]);
+ fireEvent.pointerMove(row('D (disabled)'), pointer);
+ expect(lit()).toEqual([]);
+ fireEvent.pointerMove(row('B'), pointer);
+ expect(lit()).toEqual(['B']);
+ fireEvent.pointerUp(screen.getByTestId('outside'), pointer);
+ expect(lit()).toEqual([]);
+ expect(row('B')).toHaveFocus();
+ },
+ );
+
+ it.each([
+ ['finger', touch()],
+ ['pen', {pointerType: 'pen', pointerId: 1}],
+ ])(
+ 'holds the rows off their own pressed paint while a held %s presses, and gives it back once the press ends',
+ (_name, pointer) => {
+ render(<Harness />);
+ const menu = screen.getByRole('menu');
+ expect(isMenuPressPaintHeld(menu)).toBe(false);
+ fireEvent.pointerDown(row('A'), pointer);
+ expect(isMenuPressPaintHeld(menu)).toBe(true);
+ fireEvent.pointerMove(screen.getByTestId('divider'), pointer);
+ expect(isMenuPressPaintHeld(menu)).toBe(true);
+ fireEvent.pointerUp(screen.getByTestId('outside'), pointer);
+ expect(isMenuPressPaintHeld(menu)).toBe(false);
+ },
+ );
+
+ it('leaves the rows their own pressed paint under a held mouse', () => {
+ render(<Harness />);
+ const menu = screen.getByRole('menu');
+ fireEvent.pointerDown(row('A'), mouse());
+ fireEvent.pointerMove(row('B'), mouse());
+ expect(isMenuPressPaintHeld(menu)).toBe(false);
+ fireEvent.pointerUp(screen.getByTestId('outside'), mouse());
+ expect(isMenuPressPaintHeld(menu)).toBe(false);
+ });
+
+ it('lights the row under a held mouse with focus alone, so it keeps the hover tint', () => {
+ render(<Harness />);
+ fireEvent.pointerDown(row('A'), mouse());
+ expect(row('A')).toHaveFocus();
+ expect(lit()).toEqual([]);
+ fireEvent.pointerMove(row('B'), mouse());
+ expect(row('B')).toHaveFocus();
+ expect(lit()).toEqual([]);
+ fireEvent.pointerUp(screen.getByTestId('outside'), mouse());
+ expect(lit()).toEqual([]);
+ });
+
+ it('marks the row under the finger that opened the menu once it hands off, and clears it at the lift', () => {
+ vi.useFakeTimers();
+ render(<Harness touchModel="uikit" />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 0, clientY: 4});
+ expect(lit()).toEqual([]);
+ const past = {...touch(), clientX: 0, clientY: 4 + MENU_PRESS_HANDOFF_PX};
+ fireEvent.pointerMove(row('A'), past);
+ expect(lit()).toEqual(['A']);
+ fireEvent.pointerMove(row('B'), {...past, clientY: past.clientY + 30});
+ expect(lit()).toEqual(['B']);
+ fireEvent.pointerCancel(row('B'), past);
+ expect(lit()).toEqual([]);
+ });
+
+ it('paints every menu row family: each composes the lit style and reads its variable', () => {
+ for (const family of [
+ 'DropdownMenuItem',
+ 'DropdownMenuCheckboxItem',
+ 'DropdownMenuRadioItem',
+ 'DropdownMenuSubMenu',
+ ]) {
+ const source = readFileSync(
+ resolve(__dirname, `../DropdownMenu/${family}.tsx`),
+ 'utf8',
+ );
+ expect(source).toContain('menuPressLitRowStyle,');
+ expect(source).toContain('var(--_menu-row-focus-paint, ');
+ }
+ // The one family with an :active background reads its variable there.
+ const item = readFileSync(
+ resolve(__dirname, '../DropdownMenu/DropdownMenuItem.tsx'),
+ 'utf8',
+ );
+ expect(item).toContain('var(--_menu-row-active-paint, ');
+ });
+});
+
describe('useMenuPress — one gesture, one activation', () => {
it('a tap on a row acts once even though the browser also reports a click', () => {
const onSelect = vi.fn();
@@ -779,6 +905,141 @@ describe('useMenuPress — the trigger', () => {
});
});
+describe('useMenuPress — the opening finger hands off (DropdownMenu\u2019s touch model, spec:AST-094 FR29)', () => {
+ it('the finger that opened the menu from the trigger picks only once it travels the handoff from the first sample', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ const onOpenChange = vi.fn();
+ render(
+ <Harness
+ touchModel="uikit"
+ onSelect={onSelect}
+ onOpenChange={onOpenChange}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ // The first sample after the open is where the distance counts from.
+ fireEvent.pointerMove(row('C'), {...touch(), clientX: 0, clientY: 4});
+ fireEvent.pointerMove(row('C'), {
+ ...touch(),
+ clientX: 0,
+ clientY: 4 + MENU_PRESS_HANDOFF_PX - 1,
+ });
+ expect(row('C')).not.toHaveFocus();
+ fireEvent.pointerMove(row('C'), {
+ ...touch(),
+ clientX: 0,
+ clientY: 4 + MENU_PRESS_HANDOFF_PX,
+ });
+ expect(row('C')).toHaveFocus();
+ fireEvent.pointerUp(row('C'), {
+ ...touch(),
+ clientX: 0,
+ clientY: 4 + MENU_PRESS_HANDOFF_PX,
+ });
+ expect(onSelect).toHaveBeenCalledWith('C');
+ });
+
+ it('the finger that opened the menu lifts without travelling the handoff: nothing acts and the menu stays', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ const onOpenChange = vi.fn();
+ render(
+ <Harness
+ touchModel="uikit"
+ onSelect={onSelect}
+ onOpenChange={onOpenChange}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ // The row under the finger is not highlighted however long it rests.
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 0, clientY: 1});
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 0, clientY: 9});
+ expect(row('A')).not.toHaveFocus();
+ fireEvent.pointerUp(row('A'), {...touch(), clientX: 0, clientY: 9});
+ // The browser's click for the press is spent too.
+ fireEvent.click(row('A'), {detail: 1});
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('the pointer model (the public hook\u2019s) keeps the settle rule: once the press has settled, a still finger\u2019s lift over a row acts', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS + MENU_PRESS_SETTLE_MS);
+ });
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 0, clientY: 2});
+ fireEvent.pointerUp(row('A'), {...touch(), clientX: 0, clientY: 2});
+ expect(onSelect).toHaveBeenCalledWith('A');
+ });
+});
+
+describe('useMenuPress — the public hook takes no touch model option', () => {
+ function PublicHarness({onSelect}: {onSelect: (label: string) => void}) {
+ const menuRef = useRef<HTMLDivElement>(null);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const [isOpen, setIsOpen] = useState(false);
+ const press = useMenuPress({
+ menuRef,
+ triggerRef,
+ itemSelector: ITEM_SELECTOR,
+ onTriggerPress: () => {
+ setIsOpen(true);
+ return true;
+ },
+ // An untyped caller passing DropdownMenu's own option gets nothing
+ // from it: the touch model is not part of the public hook.
+ ...({touchModel: 'uikit'} as object),
+ });
+ return (
+ <>
+ <button type="button" ref={triggerRef} {...press.triggerProps}>
+ Open
+ </button>
+ {isOpen ? (
+ <div ref={menuRef} role="menu" {...press.menuProps}>
+ <div role="menuitem" tabIndex={-1} onClick={() => onSelect('A')}>
+ A
+ </div>
+ </div>
+ ) : null}
+ </>
+ );
+ }
+
+ it('the opening finger keeps the settle rule, though an untyped caller passes the touch model', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ render(<PublicHarness onSelect={onSelect} />);
+ fireEvent.pointerDown(screen.getByRole('button', {name: 'Open'}), {
+ ...touch(),
+ clientX: 0,
+ clientY: 0,
+ });
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS + MENU_PRESS_SETTLE_MS);
+ });
+ // No handoff: the settled press's still lift acts, as released.
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 0, clientY: 2});
+ fireEvent.pointerUp(row('A'), {...touch(), clientX: 0, clientY: 2});
+ expect(onSelect).toHaveBeenCalledWith('A');
+ });
+});
+
describe('useMenuPress — edge autoscroll', () => {
it('a pointer resting near the bottom edge scrolls the menu down and stops when it leaves the zone', () => {
vi.useFakeTimers();
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index 56da934682..733cd87867 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -6,7 +6,8 @@
* @file useMenuPress.ts
* @input The menu root, its trigger, the enabled-row selector, and callbacks
* for opening, highlighting, activating and dismissing
- * @output useMenuPress, the marker attributes, and the activation mark
+ * @output useMenuPress, the marker attributes, the activation mark, and the
+ * internal useDropdownMenuPress entry with its touch model
* @position Core hook for DropdownMenu, ContextMenu, DropdownMenuSubMenu,
* Selector and MenuBottomSheetActionList. The transition table lives in
* menuPressGesture.ts.
@@ -29,10 +30,10 @@ import {
import {currentGesture} from '../Layer/gestureCounter';
import {
IDLE_MENU_PRESS,
- menuPressStep,
- type MenuPressEffect,
- type MenuPressEvent,
- type MenuPressGesture,
+ menuPressTransition,
+ type MenuPressOutcome,
+ type MenuPressInput,
+ type MenuPressState,
type MenuPressPointerType,
} from './menuPressGesture';
import {MENU_PRESS_MARKER} from './menuPressMarker';
@@ -45,6 +46,12 @@ import {edgeAutoscroll} from '../utils/edgeAutoscroll';
import {focusForLastInput} from '../utils/focusReturn';
import {useInteractionModalityTrackingFor} from '../utils/interactionModality';
import {LONG_PRESS_DURATION_MS} from '../motion/uikit/longPress';
+import {
+ clearMenuPressLit,
+ holdMenuPressPaint,
+ markMenuPressLit,
+ releaseMenuPressPaint,
+} from '../privateAttributes/menuPressLit.stylex';
import {
__resetClickGuardForTest,
armClickGuard,
@@ -235,6 +242,44 @@ interface ResolvedPoint {
isOnTrigger: boolean;
}
+/**
+ * DropdownMenu's options for the press model: everything the public hook
+ * takes, plus its touch model. DropdownMenu reaches the touch model through
+ * its `presentation`, so the public hook has no such option.
+ *
+ * @internal
+ */
+export interface DropdownMenuPressOptions extends UseMenuPressOptions {
+ /**
+ * How the finger that opened the menu from the trigger picks.
+ * `'pointer'`: its opening press follows the settle rule. `'uikit'`: it
+ * picks only after UIMenu's handoff distance, so the row that appeared
+ * under it never acts on a still lift. A mouse is unaffected.
+ * @default 'pointer'
+ */
+ touchModel?: 'pointer' | 'uikit';
+}
+
+/**
+ * What core's own menus get from {@link useDropdownMenuPress}: the public
+ * return. Not exported from the hooks entry point.
+ *
+ * @internal
+ */
+export type DropdownMenuPressReturn = UseMenuPressReturn;
+
+/**
+ * Where a pointer is, for a finger's handoff distance. Positions reach the
+ * machine only under `touchModel: 'uikit'`. Without them, it keeps the settle
+ * rule.
+ */
+function handoffPosition(
+ event: PointerEvent,
+ hasHandoff: boolean,
+): {x?: number; y?: number} {
+ return hasHandoff ? {x: event.clientX, y: event.clientY} : {};
+}
+
/**
* The press model for a menu: the row under the release acts, the highlight
* follows a held pointer, and a mouse opens the menu on press.
@@ -271,13 +316,30 @@ interface ResolvedPoint {
* ```
*/
export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
+ // The touch model is DropdownMenu's alone; an untyped caller's
+ // `touchModel` does not reach the model.
+ const {touchModel: _touchModel, ...publicOptions} =
+ options as DropdownMenuPressOptions;
+ return useDropdownMenuPress({...publicOptions, touchModel: 'pointer'});
+}
+
+/**
+ * The press model with DropdownMenu's touch model
+ * ({@link DropdownMenuPressOptions.touchModel}). Not exported from the hooks
+ * entry point.
+ *
+ * @internal
+ */
+export function useDropdownMenuPress(
+ options: DropdownMenuPressOptions,
+): DropdownMenuPressReturn {
const optionsRef = useRef(options);
optionsRef.current = options;
// The highlight, and the hover focus of the rows in this menu, follow the
// last input, which this tracks for the menu's own document.
useInteractionModalityTrackingFor(options.menuRef);
- const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);
+ const gestureRef = useRef<MenuPressState<HTMLElement>>(IDLE_MENU_PRESS);
const pointerIdRef = useRef<number | null>(null);
const detachRef = useRef<(() => void) | null>(null);
// `useLongPress` detects the held finger, as in ContextMenu, so the hold
@@ -374,8 +436,18 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
autoscrollRef.current = null;
}, [autoscroll]);
+ const litRowRef = useRef<HTMLElement | null>(null);
+ const heldMenuRef = useRef<HTMLElement | null>(null);
const endGesture = useCallback(() => {
longPressApiRef.current?.cancel();
+ if (litRowRef.current != null) {
+ clearMenuPressLit(litRowRef.current);
+ litRowRef.current = null;
+ }
+ if (heldMenuRef.current != null) {
+ releaseMenuPressPaint(heldMenuRef.current);
+ heldMenuRef.current = null;
+ }
touchMovePreventerRef.current?.();
touchMovePreventerRef.current = null;
stopAutoscroll();
@@ -388,7 +460,34 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
const highlight = useCallback(
(row: HTMLElement | null) => {
+ // A held finger or pen marks the row it lights, for the row's pressed
+ // paint. A held mouse keeps the hover tint, as on a desktop.
+ const gesture = gestureRef.current;
+ const isHeld =
+ gesture.phase !== 'idle' && gesture.pointerType !== 'mouse';
+ const lit = isHeld ? row : null;
+ if (litRowRef.current !== lit) {
+ if (litRowRef.current != null) {
+ clearMenuPressLit(litRowRef.current);
+ }
+ litRowRef.current = lit;
+ if (lit != null) {
+ markMenuPressLit(lit);
+ }
+ }
const {onHighlight, menuRef} = optionsRef.current;
+ // The row the press began on stays :active where a pointer hovers, so
+ // the menu holds every row but the lit one off that paint.
+ const held = isHeld ? menuRef.current : null;
+ if (heldMenuRef.current !== held) {
+ if (heldMenuRef.current != null) {
+ releaseMenuPressPaint(heldMenuRef.current);
+ }
+ heldMenuRef.current = held;
+ if (held != null) {
+ holdMenuPressPaint(held);
+ }
+ }
if (onHighlight != null) {
onHighlight(row);
return;
@@ -449,13 +548,13 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
// Declared before `step` so the mutual recursion through refs type-checks.
const stepRef = useRef<
- (event: MenuPressEvent<HTMLElement>, native?: PointerEvent) => void
+ (event: MenuPressInput<HTMLElement>, native?: PointerEvent) => void
>(() => {});
const applyEffect = useCallback(
(
- effect: MenuPressEffect<HTMLElement>,
- gesture: MenuPressGesture<HTMLElement>,
+ effect: MenuPressOutcome<HTMLElement>,
+ gesture: MenuPressState<HTMLElement>,
native: PointerEvent | undefined,
) => {
const doc = getDocument();
@@ -511,8 +610,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
);
const step = useCallback(
- (event: MenuPressEvent<HTMLElement>, native?: PointerEvent) => {
- const result = menuPressStep(gestureRef.current, event);
+ (event: MenuPressInput<HTMLElement>, native?: PointerEvent) => {
+ const result = menuPressTransition(gestureRef.current, event);
gestureRef.current = result.gesture;
applyEffect(result.effect, result.gesture, native);
},
@@ -619,6 +718,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
row: point.row,
isInMenu: point.isInMenu,
time: Date.now(),
+ ...handoffPosition(
+ event,
+ optionsRef.current.touchModel === 'uikit',
+ ),
},
event,
);
@@ -636,6 +739,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
isInMenu: point.isInMenu,
isOnTrigger: point.isOnTrigger,
time: Date.now(),
+ ...handoffPosition(
+ event,
+ optionsRef.current.touchModel === 'uikit',
+ ),
},
event,
);
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index aaa6aafd51..c5a9677b58 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -314,3 +314,14 @@ scroll view coasts with 0.25 × the pan's velocity plus 0.75 × its value one
event earlier (four HID releases; `velocity.scrollReleaseWeight`, which a
pan's `scrollVelocity()` reads). On UIKit, Reduce Motion with Prefer Cross-Fade changes
nothing on a picker; the Wheel follows design:reduced-motion instead.
+
+## Menus (UIMenu)
+
+Probe: the UIKit lab host app with a UIButton whose `UIMenu` is its primary
+action (`showsMenuAsPrimaryAction`), three to twelve items, on a plain view
+and inside a UIScrollView; the gesture-state, presentation-modifier,
+display-link and feedback hooks; real HID touches.
+
+| ID | Scene | Gesture | Extract | Method |
+| ----- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------ |
+| M-MN2 | button on a plain view | hold until the menu is open, then lift still; move 8 pt down, 8 pt right, 12 pt down, (7, 7), (8, 8) and lift; move 6 pt before the open and 6 pt after | row picked or not; handoff and list-selection recognizer states; highlighted row per frame: threshold, metric, where it is counted from | C |
diff --git a/packages/core/src/motion/uikit/gestures.ts b/packages/core/src/motion/uikit/gestures.ts
index eb250257d0..e1c6f3aca7 100644
--- a/packages/core/src/motion/uikit/gestures.ts
+++ b/packages/core/src/motion/uikit/gestures.ts
@@ -251,6 +251,27 @@ export const UIKIT_PRESS = {
momentumMemory: {value: 3000, unit: 'ms'},
} as const satisfies Record<string, GestureConstant>;
+/**
+ * UIMenu presented by a button whose menu is its primary action: how far the
+ * finger that opened it travels before it picks. DropdownMenu's press model
+ * reads a copy in `hooks/menuPressValues.ts`.
+ */
+export const UIKIT_MENU_PRESS = {
+ /**
+ * After the menu opens under a still-held finger, the finger travels this
+ * far before it starts picking. The distance is a straight line from the
+ * first sample the menu receives after it opened. Until then nothing is
+ * lit, and lifting acts on nothing.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, gesture-state hook, steps 150 ms apart, Oct 23 2026
+ * (M-MN2): with the menu open under a held finger and a 1 pt first step,
+ * moves of (0, 9) and (7, 7) picked nothing; (0, 10), (0, 11), (10, 0),
+ * (9, 9) and (10, 10) picked; a 9 pt step followed by 3 pt more picked
+ * nothing
+ */
+ handoff: {value: 10, unit: 'px'},
+} as const satisfies Record<string, GestureConstant>;
+
export const UIKIT_VELOCITY = {
/**
* UIPanGestureRecognizer.velocity(in:) is this times the newest event's
@@ -318,6 +339,7 @@ export const UIKIT_GESTURES = {
screenEdgePan: UIKIT_SCREEN_EDGE_PAN,
control: UIKIT_CONTROL,
press: UIKIT_PRESS,
+ menuPress: UIKIT_MENU_PRESS,
velocity: UIKIT_VELOCITY,
} as const;
diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts
index f9bbff0054..0ea81c759f 100644
--- a/packages/core/src/motion/uikit/index.ts
+++ b/packages/core/src/motion/uikit/index.ts
@@ -27,6 +27,7 @@ export {
UIKIT_CONTROL,
UIKIT_GESTURES,
UIKIT_LONG_PRESS,
+ UIKIT_MENU_PRESS,
UIKIT_PAN,
UIKIT_PINCH,
UIKIT_PRESS,
diff --git a/packages/core/src/privateAttributes/menuPressLit.stylex.ts b/packages/core/src/privateAttributes/menuPressLit.stylex.ts
new file mode 100644
index 0000000000..7a502dee1b
--- /dev/null
+++ b/packages/core/src/privateAttributes/menuPressLit.stylex.ts
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file privateAttributes/menuPressLit.stylex.ts
+ * @input The row that a held finger or pen lights in a menu
+ * @output markMenuPressLit and clearMenuPressLit, which mark that row,
+ * isMenuPressLit, which reads the mark, menuPressLitRowStyle, which
+ * paints the marked row, holdMenuPressPaint and releaseMenuPressPaint,
+ * which keep the other rows off their pressed paint, and
+ * isMenuPressPaintHeld, which reads that hold
+ * @position Owner module of the private menu-press-lit attribute: the only
+ * file that writes its name. The menu press model (hooks/useMenuPress.ts)
+ * marks the row; DropdownMenu's rows compose the styles. No package entry
+ * exports it.
+ *
+ * SYNC: Each row that composes menuPressLitRowStyle reads
+ * `--_menu-row-focus-paint` in its `:focus` background, and a row with an
+ * `:active` background reads `--_menu-row-active-paint` there:
+ * - /packages/core/src/DropdownMenu/DropdownMenuItem.tsx
+ * - /packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
+ * - /packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
+ * - /packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {colorVars} from '../theme/tokens.stylex';
+
+const MENU_PRESS_LIT = 'data-astryx-menu-press-lit';
+const ACTIVE_PAINT = '--_menu-row-active-paint';
+
+/** Marks `row` as the row that a held finger or pen lights. */
+export function markMenuPressLit(row: Element): void {
+ row.setAttribute(MENU_PRESS_LIT, '');
+}
+
+/** Removes the mark from `row`. */
+export function clearMenuPressLit(row: Element): void {
+ row.removeAttribute(MENU_PRESS_LIT);
+}
+
+/** Whether a held finger or pen lights `row`. */
+export function isMenuPressLit(row: Element): boolean {
+ return row.hasAttribute(MENU_PRESS_LIT);
+}
+
+/**
+ * Keeps `menu`'s rows off their `:active` paint while a held finger or pen
+ * presses in it. The row the press began on stays `:active` as the press
+ * moves on. The lit row keeps the pressed overlay through its own mark.
+ */
+export function holdMenuPressPaint(menu: HTMLElement): void {
+ menu.style.setProperty(ACTIVE_PAINT, 'transparent');
+}
+
+/** Gives `menu`'s rows their `:active` paint back. */
+export function releaseMenuPressPaint(menu: HTMLElement): void {
+ menu.style.removeProperty(ACTIVE_PAINT);
+}
+
+/** Whether a held finger or pen keeps `menu`'s rows off their `:active` paint. */
+export function isMenuPressPaintHeld(menu: HTMLElement): boolean {
+ return menu.style.getPropertyValue(ACTIVE_PAINT) !== '';
+}
+
+/**
+ * A value for each attribute state. The index signature gives StyleX the value
+ * type, which it cannot read from a literal attribute key.
+ */
+type ByAttribute<Value> = Readonly<{
+ default: null;
+ [attribute: string]: Value | null;
+}>;
+
+const litRowPaint: Readonly<{
+ '--_menu-row-focus-paint': ByAttribute<string>;
+ '--_menu-row-active-paint': ByAttribute<string>;
+}> = {
+ '--_menu-row-focus-paint': {
+ default: null,
+ '[data-astryx-menu-press-lit]': colorVars['--color-overlay-pressed'],
+ },
+ '--_menu-row-active-paint': {
+ default: null,
+ '[data-astryx-menu-press-lit]': colorVars['--color-overlay-pressed'],
+ },
+};
+
+const styles = stylex.create({
+ row: {...litRowPaint},
+});
+
+/**
+ * Compose on a menu row whose `:focus` background is
+ * `var(--_menu-row-focus-paint, <hover overlay>)`, and whose `:active`
+ * background, if any, is `var(--_menu-row-active-paint, <pressed overlay>)`.
+ * The row paints the hover overlay on focus, and the pressed overlay while a
+ * held finger or pen lights it.
+ * Under a finger, the hover overlay is too faint to follow. The variable has
+ * no default: a layered stylesheet emits a default unlayered, and it would
+ * beat the attribute arm. The value resolves on the row, so a theme set on any
+ * ancestor applies. The style sets only a custom property, which shares no
+ * key with StyleX's CSS property type, so TypeScript needs the wider type.
+ */
+export const menuPressLitRowStyle = styles.row as StyleXStyles;
diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjs
index 0765ababac..f559cf7246 100644
--- a/scripts/build-css.test.mjs
+++ b/scripts/build-css.test.mjs
@@ -102,6 +102,11 @@ function specificity(selector) {
function stateRule(css, {property, token, state, media}) {
const lines = css.split('\n');
+ // The token as the fallback of another variable is one component's own
+ // paint, not the shared overlay this guard orders.
+ const asFallback = new RegExp(
+ `var\\(--[\\w-]+,\\s*var\\(--color-overlay-${token}\\)`,
+ );
return lines.find(line => {
const inHoverMedia = line.includes('@media (hover: hover)');
return (
@@ -109,7 +114,8 @@ function stateRule(css, {property, token, state, media}) {
line.includes(`:${state}:where(`) &&
!line.includes('::') &&
line.includes(`${property}:`) &&
- line.includes(`var(--color-overlay-${token})`)
+ line.includes(`var(--color-overlay-${token})`) &&
+ !asFallback.test(line)
);
});
}