From 2bcc49a4622f3a024a2975c8bc487c473a2eb553 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 02:26:34 -0800 Subject: [PATCH 001/151] feat(ContextMenu): open from a held finger on iOS 26's timeline A finger held on the trigger opens the menu on UIKit's timeline: the hold commits at 400 ms and the menu shows at 735 ms. One outside-press watch closes the menu for every pointer, and a touch closes it as it begins to pan. It carries this pull request's own diff from 6d7fceb72a, replayed on main after #9814's squash, and folds these 12 commits (the history of 6d7fceb72a has each one): - chore(motion): ContextMenu's touch timeline and press curve, measured on iOS 26.2 - test(ContextMenu): a held finger opens the menu on iOS 26's timeline, and a touch outside closes it as it pans - feat(ContextMenu): open from a held finger on iOS 26's timeline, with no page lock - docs(ContextMenu): FR11 cites AST-094 FR45 for the hold's measured moments - test(ContextMenu): the long-press a11y contract follows the touch model - docs(ContextMenu): the touch changeset and docs name their condition, not every touch device - test(Layer): the outside-press watch closes a layer at the press for a mouse or a pen - feat(Layer): the outside-press watch closes a layer at the press for a mouse or a pen - refactor(ContextMenu): one outside-press watch closes the menu for every pointer, and its mousedown Effect goes - docs(ContextMenu): split long file-header sentences - test(Indicator): the ContextMenu box-hold case pins the popover menu - test(ContextMenu): the long-press spec note keeps to 20 words --- .changeset/contextmenu-touch-timeline.md | 7 + .changeset/outside-press-pan-watch.md | 2 +- .../storybook/stories/ContextMenu.stories.tsx | 69 ++ .../ContextMenu/ContextMenu.spec.md | 95 +-- .../core/src/ContextMenu/ContextMenu.doc.mjs | 9 +- .../core/src/ContextMenu/ContextMenu.test.tsx | 796 ++++++++++++++++-- packages/core/src/ContextMenu/ContextMenu.tsx | 237 ++++-- .../core/src/ContextMenu/ContextMenuTouch.ts | 17 + .../src/ContextMenu/ContextMenuTouchLayer.tsx | 99 +++ ...ContextMenuLongPress.a11y.chromium.spec.ts | 130 ++- ...tMenuLongPress.interaction.browser.spec.ts | 182 ++++ .../src/ContextMenu/contextMenuPress.test.ts | 214 +++++ .../core/src/ContextMenu/contextMenuPress.ts | 198 +++++ packages/core/src/Indicator/boxHold.test.tsx | 5 +- packages/core/src/Layer/outsidePress.test.ts | 112 ++- packages/core/src/Layer/outsidePress.ts | 49 +- packages/core/src/motion/README.md | 1 + packages/core/src/motion/uikit/contextMenu.ts | 94 +++ 18 files changed, 2054 insertions(+), 262 deletions(-) create mode 100644 .changeset/contextmenu-touch-timeline.md create mode 100644 packages/core/src/ContextMenu/ContextMenuTouch.ts create mode 100644 packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx create mode 100644 packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts create mode 100644 packages/core/src/ContextMenu/contextMenuPress.test.ts create mode 100644 packages/core/src/ContextMenu/contextMenuPress.ts create mode 100644 packages/core/src/motion/uikit/contextMenu.ts diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md new file mode 100644 index 0000000000000..b8c1a1e95a6c7 --- /dev/null +++ b/.changeset/contextmenu-touch-timeline.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu takes the focus, and a row lights only under the finger, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. + +@vjeux diff --git a/.changeset/outside-press-pan-watch.md b/.changeset/outside-press-pan-watch.md index e71ae7e4c072a..3cb9f8e136f72 100644 --- a/.changeset/outside-press-pan-watch.md +++ b/.changeset/outside-press-pan-watch.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: the layer's outside-press watch can follow chosen pointer types, close as a press that starts outside begins to pan (on either axis, at core's pan threshold) or when the browser takes it, and judge a press inside a closed shadow root, which the document sees as its host. No component passes these options yet, so every watch keeps today's behavior. Not exported from the package entry point. +[chore] Internal: the layer's outside-press watch can follow chosen pointer types, close as a press that starts outside begins to pan (on either axis, at core's pan threshold) or when the browser takes it, and judge a press inside a closed shadow root, which the document sees as its host. ContextMenu's touch model uses them; every other watch keeps today's behavior. Not exported from the package entry point. @vjeux diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 891b4ca1c4aa1..7d8dff9642034 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -647,3 +647,72 @@ export const BottomSheetSubmenu: Story = { } }, }; + +const touchStyles = stylex.create({ + card: { + width: '200px', + height: '120px', + display: 'grid', + placeItems: 'center', + borderRadius: '12px', + backgroundColor: '#e5e7eb', + color: '#374151', + userSelect: 'none', + }, +}); + +export const TouchLongPress: Story = { + name: 'Touch / long press', + parameters: { + docs: { + description: { + story: + 'Where the primary pointer is coarse (a touch screen), hold a finger on the card. As on iOS, a haptic plays at 400 ms where the device can play one, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. While the menu is up, the page still scrolls: a touch outside the menu closes it as it begins to pan.', + }, + }, + }, + render: () => ( + {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + {label: 'Save to Files', icon: ArrowDownTrayIcon, onClick: () => {}}, + {type: 'divider'}, + { + label: 'Delete', + icon: TrashIcon, + variant: 'destructive', + onClick: () => {}, + }, + ]}> +
Hold for actions
+
+ ), +}; + +export const TouchLongPressPopover: Story = { + name: 'Touch / long press, presentation="popover"', + parameters: { + docs: { + description: { + story: + 'With `presentation="popover"`, ContextMenu keeps today’s menu on every device: a finger held for 500 ms opens it at the finger, with no growth and no iOS timeline. A finger on a device whose primary pointer is fine (a mouse or a trackpad) gets the same long press.', + }, + }, + }, + render: () => ( + {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + {label: 'Save to Files', icon: ArrowDownTrayIcon, onClick: () => {}}, + ]}> +
Hold for actions
+
+ ), +}; diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 9fa75032743cb..dac8d53543eaf 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -36,15 +36,15 @@ system_specs: [spec:AST-094, spec:AST-107] ## Contract at a glance -| Area | Contract | -| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Public contract | None changes. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | -| Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | -| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger, and a scroll that starts outside leaves it open; mouse and keyboard opens keep today's look. | -| Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | -| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow, pan dismissal, and trigger lift (FR5) are listed under Current-state impact. | -| Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | -| Governing rules | `spec:AST-107` FR8; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `family:overlay-dismissal`; `architecture:component-theming-surface`; `architecture:layer-runtime`. | +| Area | Contract | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Public contract | None changes. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | +| Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | +| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger; mouse and keyboard opens keep today's look. | +| Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | +| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow and trigger lift (FR5) are listed under Current-state impact. | +| Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | +| Governing rules | `spec:AST-107` FR8; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `family:overlay-dismissal`; `architecture:component-theming-surface`; `architecture:layer-runtime`. | This table is a review projection; the body below is authoritative. @@ -100,19 +100,20 @@ Consumer props, content modes, and presentation policy remain documented in ## Behavioral and layout contract -| ID | Invariant | Basis | -| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| FR1 | Every render contains a caller-provided Trigger area; with `isDisabled` no invocation opens a menu and the native context menu is left alone. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | -| FR2 | The `context-menu` target stays on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | `architecture:component-theming-surface`; current source | -| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | -| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | -| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, a scroll that starts outside leaves it open, the opening finger is not handed to the menu so it cannot slide to a row, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | -| FR6 | With `triggerAs="span"` the Trigger area is an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | DEC-1 | -| FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | -| FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. Implementation gap: the arrow keys and typeahead skip disabled rows today (Current-state impact). | Current source and tests | -| FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | -| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | -| FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | +| ID | Invariant | Basis | +| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| FR1 | Every render contains a caller-provided Trigger area; with `isDisabled` no invocation opens a menu and the native context menu is left alone. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | +| FR2 | The `context-menu` target stays on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | `architecture:component-theming-surface`; current source | +| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | +| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | +| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, the opening finger is not handed to the menu so it cannot slide to a row, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | +| FR6 | With `triggerAs="span"` the Trigger area is an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | DEC-1 | +| FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | +| FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. Implementation gap: the arrow keys and typeahead skip disabled rows today (Current-state impact). | Current source and tests | +| FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | +| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | +| FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | +| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | ### Allowed variation @@ -244,24 +245,25 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens on touch long-press", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | -| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | -| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | -| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and scroll outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, or a tap or mouse press outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift; the scroll-outside and pen cases assert the current gaps. | `audit:ContextMenu/behavior` | -| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | -| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | -| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | -| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | -| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | -| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | -| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | -| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | -| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "composes consumer touch handlers with long-press detection") | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | -| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | -| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | -| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | +| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | +| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | +| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | +| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | +| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | +| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | +| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | +| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | +| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | +| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | +| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | +| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | +| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | +| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | +| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does"; `contextMenuPress.test.ts` | A held finger: the commit and the menu's display | A commit or a display off UIKit's moments fails. | `audit:ContextMenu/behavior` | +| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | +| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | ## Current-state impact @@ -271,13 +273,12 @@ anchor is positioning infrastructure rather than consumer anatomy. - **No headless factory (FR10).** No headless context menu ships, so ContextMenu owns its invocation, open state, and outside-press listener itself, against `spec:AST-107` FR8. -- **Touch grow, pan dismissal, handoff, and lift (FR5).** A touch-opened - menu keeps the layer's own entrance and exit instead of growing from the - finger, a scroll that starts outside leaves it open, the held finger that - opened it cannot slide to a row, and a block trigger is not lifted over a - tinted page; a pen press outside closes it at the press. All are against - `spec:AST-094` FR31, FR32, and FR33. A menu opened by mouse or keyboard - already keeps its released appearance and motion. +- **Touch grow, handoff, and lift (FR5).** A touch-opened menu keeps the + layer's own entrance and exit instead of growing from the finger, the held + finger that opened it cannot slide to a row, and a block trigger is not + lifted over a tinted page; a pen press outside closes it at the press. All + are against `spec:AST-094` FR31, FR32, and FR33. A menu opened by mouse or + keyboard already keeps its released appearance and motion. ## Decision log diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs index f8ee2c5659074..4a5b1745c7bbe 100644 --- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs +++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -132,8 +132,7 @@ export const docs = { name: 'presentation', type: "'popover' | 'bottom-sheet' | 'adaptive'", description: - 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the 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'", + 'Presentation policy. Omitted, the menu opens at the pointer position, and under a finger a held finger opens it on iOS timing (the touch model). `popover` opens at the pointer position on every device, and a held finger opens it at 500 ms (the long press), as before; so does a finger where the primary pointer is fine. `bottom-sheet` always uses an action sheet, and `adaptive` uses the 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.', }, { name: 'isDisabled', @@ -160,7 +159,7 @@ export const docs = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons. Under a finger, where the primary pointer is coarse, a held finger opens it with iOS timing: the menu opens at 735 ms, or as soon as the finger lifts after 400 ms.', bestPractices: [ { guidance: true, @@ -224,7 +223,7 @@ export const docs = { export const docsZh = { usage: { description: - '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。', + '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在主指针为粗指针(触摸屏)时,按住手指即可打开,时序与 iOS 相同:735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。', bestPractices: [ {guidance: true, description: '保持菜单项简洁和面向操作。'}, {guidance: true, description: '有很多项时使用分组和分隔线。'}, @@ -260,7 +259,7 @@ export const docsDense = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (a coarse primary pointer): a held finger opens it at 735 ms, or on a lift after 400 ms.', bestPractices: [ {guidance: true, description: 'Keep items concise and action-oriented.'}, { diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index d68f7a78dcc1d..3b3957152001d 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -10,7 +10,15 @@ import {useRef, useState} from 'react'; import {createPortal} from 'react-dom'; -import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest'; +import { + describe, + it, + expect, + vi, + afterEach, + beforeAll, + beforeEach, +} from 'vitest'; import { render, screen, @@ -37,6 +45,9 @@ import {Divider} from '../Divider'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet'; import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation'; +import {COMPACT_QUERY, TOUCH_QUERY} from '../utils/touchPresentation'; +import {HAPTIC_VIBRATION_PATTERNS} from '../motion/uikit'; +import {contextMenu} from '../motion/uikit/contextMenu'; // The touch sheet is loaded lazily; resolve its modules once up front, so // ContextMenu's own lazy sheet renders within the cases' waitFor. @@ -180,6 +191,17 @@ describe('ContextMenu', () => { ).toBeInTheDocument(); }); + it('suppresses native text selection on the long-press trigger', () => { + const source = readFileSync( + 'packages/core/src/ContextMenu/ContextMenu.tsx', + 'utf8', + ); + + expect(source).toMatch( + /trigger:[\s\S]*?WebkitTouchCallout: 'none',[\s\S]*?WebkitUserSelect: 'none',[\s\S]*?userSelect: 'none'/, + ); + }); + it('does not put aria-haspopup on the role-less trigger wrapper (menus-15)', () => { render( @@ -374,7 +396,11 @@ describe('ContextMenu', () => { vi.stubGlobal( 'matchMedia', vi.fn().mockImplementation((query: string) => ({ - matches: query === COMPACT_TOUCH_PRESENTATION_QUERY, + // A compact touch screen: a coarse primary pointer, a narrow viewport. + matches: + query === COMPACT_TOUCH_PRESENTATION_QUERY || + query === TOUCH_QUERY || + query === COMPACT_QUERY, media: query, onchange: null, addEventListener: vi.fn(), @@ -414,6 +440,8 @@ describe('ContextMenu', () => { it.each(['open', 'closed', 'nested'] as const)( 'judges presses once inside a %s shadow root', mode => { + // Under the touch model, so a touch on the host closes the menu. + stubPointer(true); const host = document.createElement('div'); document.body.append(host); let root = host.attachShadow({mode: mode === 'open' ? 'open' : 'closed'}); @@ -431,16 +459,33 @@ describe('ContextMenu', () => { , {container}, ); - fireEvent.contextMenu(container.querySelector('div div')!); + const trigger = container.querySelector('div div')!; + fireEvent.contextMenu(trigger); // At the document a press on the menu is retargeted to a shadow host. const item = container.querySelector('[role="menuitem"]')!; fireEvent.mouseDown(item, {composed: true}); expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); - // A press on the host itself is outside the menu. + // A touch on the menu is inside too, through its lift. + const onItem = {pointerType: 'touch', pointerId: 1, composed: true}; + fireEvent.pointerDown(item, onItem); + fireEvent.pointerUp(item, onItem); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + // A mouse press on the host itself is outside the menu. Its + // pointerdown comes first, as a browser sends it. + fireEvent.pointerDown(host, {pointerType: 'mouse', pointerId: 3}); fireEvent.mouseDown(host); expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled(); + // A touch on the host closes the menu at its lift. + vi.mocked(HTMLElement.prototype.hidePopover).mockClear(); + fireEvent.contextMenu(trigger); + const onHost = {pointerType: 'touch', pointerId: 2}; + fireEvent.pointerDown(host, onHost); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + fireEvent.pointerUp(host, onHost); + expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled(); } finally { host.remove(); + vi.unstubAllGlobals(); } }, ); @@ -665,114 +710,598 @@ describe('ContextMenu', () => { expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(2); }); }); +}); - it('opens on touch long-press', () => { - vi.useFakeTimers(); - try { - render( - -
Long-press me
-
, - ); - const trigger = screen.getByTestId('ctx'); - fireEvent.touchStart(trigger, { - touches: [{clientX: 20, clientY: 20}], - }); - // Not open until the long-press threshold elapses. - expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); - act(() => { - vi.advanceTimersByTime(500); +/** + * A finger on the real gesture host: touch events with explicit contacts, + * stamped on the (faked) `performance.now()` clock the host reads. + */ +interface Contact { + id: number; + x: number; + y: number; +} + +function dispatchTouch( + type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel', + target: EventTarget, + changed: Contact[], + all: Contact[], +): Event { + const event = new Event(type, {bubbles: true, cancelable: true}); + const toTouch = (contact: Contact) => ({ + identifier: contact.id, + clientX: contact.x, + clientY: contact.y, + target, + }); + Object.defineProperty(event, 'changedTouches', {value: changed.map(toTouch)}); + Object.defineProperty(event, 'touches', {value: all.map(toTouch)}); + Object.defineProperty(event, 'timeStamp', {value: performance.now()}); + target.dispatchEvent(event); + return event; +} + +function finger(target: EventTarget, id = 1, x = 20, y = 20) { + const contact = {id, x, y}; + return { + down: () => dispatchTouch('touchstart', target, [contact], [contact]), + moveTo: (nx: number, ny: number) => { + contact.x = nx; + contact.y = ny; + return dispatchTouch('touchmove', target, [contact], [contact]); + }, + up: () => dispatchTouch('touchend', target, [contact], []), + }; +} + +const advance = (ms: number) => + act(() => { + vi.advanceTimersByTime(ms); + }); + +/** The primary pointer answers `matches` to `(pointer: coarse)`. */ +function stubPointer(isCoarse: boolean) { + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: isCoarse && query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); +} + +/** + * A finger on iOS in jsdom: a coarse pointer, on an engine that supports + * `-webkit-touch-callout` (WebKit on iOS). Undone by vi.unstubAllGlobals(). + */ +function stubIosTouch() { + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); + vi.stubGlobal('CSS', { + ...(globalThis as {CSS?: object}).CSS, + supports: (condition: string) => + condition.includes('-webkit-touch-callout'), + }); +} + +/** A finger on Android: a coarse pointer, no WebKit touch callout. */ +function stubAndroidTouch() { + stubPointer(true); +} + +// The gesture host lives as long as the document and remembers the latest +// event time. Each install of fake timers restarts `performance.now()` near 0. +// So every case moves the faked clock past the ones before it. +let clockEpoch = 0; + +// One touch model on every touch device (#8316): iOS and Android alike. +describe.each([ + ['iOS', stubIosTouch], + ['Android', stubAndroidTouch], +] as const)( + 'ContextMenu under a finger on %s: UIKit’s long-press timeline', + (_platform, stubTouch) => { + beforeEach(() => { + stubTouch(); + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + 'Date', + ], }); - expect(HTMLElement.prototype.showPopover).toHaveBeenCalled(); - } finally { + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + }); + afterEach(() => { vi.useRealTimers(); - } - }); + vi.unstubAllGlobals(); + }); - it('composes consumer touch handlers with long-press detection', () => { - vi.useFakeTimers(); - try { - const onTouchStart = vi.fn(); + function renderMenu( + props: { + isDisabled?: boolean; + presentation?: 'popover' | 'bottom-sheet'; + triggerAs?: 'div' | 'span'; + onTouchStart?: (event: React.TouchEvent) => void; + onTouchEnd?: (event: React.TouchEvent) => void; + } = {}, + ) { render( - +
Long-press me
, ); + return screen.getByTestId('ctx'); + } - fireEvent.touchStart(screen.getByTestId('ctx'), { - touches: [{clientX: 20, clientY: 20}], - }); - expect(onTouchStart).toHaveBeenCalledOnce(); + it('opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.menuDisplayMs - 1); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + it('lights no row when a touch opens it: focus goes to the menu itself, not its first item', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.menuDisplayMs); + // The focus moves on the next frame. + advance(20); + expect(screen.getByRole('menu', {hidden: true})).toHaveFocus(); + expect( + screen.getByRole('menuitem', {name: 'Item 1', hidden: true}), + ).not.toHaveFocus(); + press.up(); + }); + + it('opens at the lift for a finger lifted after the commit (400 ms), as UIKit does', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(529); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + // A first open mounts the menu's layer, which shows it as it attaches. act(() => { - vi.advanceTimersByTime(500); + press.up(); }); - expect(HTMLElement.prototype.showPopover).toHaveBeenCalledOnce(); - } finally { - vi.useRealTimers(); - } - }); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + }); - it('clears a pending long-press when a consumer prevents default on touch end', () => { - vi.useFakeTimers(); - try { - render( + it('opens nothing for a drag past the tolerance after the commit, before the menu', () => { + const trigger = renderMenu(); + const press = finger(trigger, 1, 20, 20); + press.down(); + advance(500); + press.moveTo(20, 50); + advance(500); + press.up(); + advance(100); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + }); + + it('keeps the menu open as the finger lifts: the lift sends no click or compatibility mouse events', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.menuDisplayMs); + const lift = press.up(); + // A cancelled touchend is the one signal that stops the browser's click + // and its compatibility mousedown, which would read as a press outside. + expect(lift.defaultPrevented).toBe(true); + expect(screen.getByRole('menu', {hidden: true})).toBeInTheDocument(); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + }); + + it('still opens at 735 ms beside a consumer onTouchStart, which runs (#7167)', () => { + const onTouchStart = vi.fn(); + const trigger = renderMenu({onTouchStart}); + const press = finger(trigger); + press.down(); + expect(onTouchStart).toHaveBeenCalledTimes(1); + advance(contextMenu.press.menuDisplayMs - 1); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('opens nothing for an early lift whose consumer onTouchEnd prevents default (#7167)', () => { + const onTouchEnd = vi.fn((event: React.TouchEvent) => { + event.preventDefault(); + }); + const trigger = renderMenu({onTouchEnd}); + const press = finger(trigger); + press.down(); + advance(200); + press.up(); + expect(onTouchEnd).toHaveBeenCalledTimes(1); + advance(1000); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + }); + + it('moves the recognizer to the new trigger when triggerAs swaps it: a hold on the new node opens the menu', () => { + const {rerender} = render( + +
Long-press me
+
, + ); + rerender( event.preventDefault()}> -
Long-press me
+ triggerAs="span"> + Long-press me
, ); + const press = finger(screen.getByTestId('ctx')); + press.down(); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); - const trigger = screen.getByTestId('ctx'); - fireEvent.touchStart(trigger, { - touches: [{clientX: 20, clientY: 20}], + it('opens nothing for a press lifted before the commit, and leaves its click alone', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(250); + const lift = press.up(); + expect(lift.defaultPrevented).toBe(false); + advance(1000); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + }); + + it('cancels when the finger drifts past the tolerance on one axis (11.5 px)', () => { + const trigger = renderMenu(); + const press = finger(trigger, 1, 20, 20); + press.down(); + advance(50); + press.moveTo(20, 31.6); + advance(1000); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + press.up(); + }); + + it('still opens after a drift inside the tolerance', () => { + const trigger = renderMenu(); + const press = finger(trigger, 1, 20, 20); + press.down(); + advance(50); + press.moveTo(31, 31); // 15.6 px away, 11 px on each axis + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('cancels when a second finger lands before the commit', () => { + const trigger = renderMenu(); + const first = {id: 1, x: 20, y: 20}; + const second = {id: 2, x: 60, y: 20}; + dispatchTouch('touchstart', trigger, [first], [first]); + advance(100); + dispatchTouch('touchstart', trigger, [second], [first, second]); + advance(1000); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + dispatchTouch('touchend', trigger, [first, second], []); + }); + + it('lets the long press decide while a finger is down: the browser’s own long-press menu opens nothing', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(380); + // Android Chrome fires contextmenu for a held finger on its own clock. + const native = new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + clientX: 20, + clientY: 20, }); - fireEvent.touchEnd(trigger); + trigger.dispatchEvent(native); + expect(native.defaultPrevented).toBe(true); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(contextMenu.press.menuDisplayMs - 380); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('plays the click haptic at the commit where the platform vibrates, and none for an early lift', () => { + const vibrate = vi.fn(() => true); + Object.defineProperty(navigator, 'vibrate', { + value: vibrate, + configurable: true, + }); + try { + const trigger = renderMenu(); + const early = finger(trigger); + early.down(); + advance(250); + early.up(); + advance(500); + expect(vibrate).not.toHaveBeenCalled(); + + const held = finger(trigger); + held.down(); + advance(contextMenu.press.commitMs - 1); + expect(vibrate).not.toHaveBeenCalled(); + advance(1); + // At the commit, before the menu shows. + expect(vibrate).toHaveBeenCalledTimes(1); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + expect(vibrate).toHaveBeenCalledWith([ + ...HAPTIC_VIBRATION_PATTERNS[contextMenu.commitHaptic].value, + ]); + held.up(); + } finally { + // jsdom has no vibration API of its own. + delete (navigator as {vibrate?: unknown}).vibrate; + } + }); + it('leaves the page free to scroll while a menu a finger opened is up; a touch outside closes it as it begins to pan', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.commitMs); + // Lifted after the commit: the menu opens at the lift. act(() => { - vi.advanceTimersByTime(500); + press.up(); + }); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + expect(document.body.style.position).toBe(''); + const outside = {pointerType: 'touch', pointerId: 9, clientX: 200}; + act(() => { + fireEvent.pointerDown(document.body, {...outside, clientY: 200}); + fireEvent.pointerMove(document.body, {...outside, clientY: 195}); + }); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + act(() => { + fireEvent.pointerMove(document.body, {...outside, clientY: 180}); }); + expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled(); + }); + + it('leaves the page alone for a menu a right-click opened', () => { + const trigger = renderMenu(); + fireEvent.contextMenu(trigger, {clientX: 20, clientY: 20}); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + expect(document.body.style.position).toBe(''); + }); + + it('passes touch events through to the consumer’s own handlers', () => { + const onTouchStart = vi.fn(); + const onTouchEnd = vi.fn(); + const trigger = renderMenu({onTouchStart, onTouchEnd}); + const press = finger(trigger); + press.down(); + press.up(); + expect(onTouchStart).toHaveBeenCalledTimes(1); + expect(onTouchEnd).toHaveBeenCalledTimes(1); + }); + + it('keeps today’s menu with presentation="popover": a held finger opens it at 500 ms through today’s long press, with no growth and no scroll lock', () => { + const trigger = renderMenu({presentation: 'popover'}); + const shows = () => + vi.mocked(HTMLElement.prototype.showPopover).mock.calls.length; + expect(trigger).not.toHaveAttribute('data-astryx-pressable'); + const press = finger(trigger); + press.down(); + advance(499); + expect(shows()).toBe(0); + advance(1); + expect(shows()).toBe(1); + // Today’s menu: the first row takes the focus, nothing grows, the page + // is not locked. + expect(trigger.style.getPropertyValue('scale')).toBe(''); + expect(document.body.style.overflow).not.toBe('hidden'); + press.up(); + // The browser’s own long-press menu (Android Chrome) still opens it. + fireEvent.contextMenu(trigger, {clientX: 20, clientY: 20, detail: 1}); + expect(shows()).toBeGreaterThanOrEqual(1); + }); + + it('with presentation="popover", a drift past 10 px or a lift before 500 ms opens nothing (today’s long press)', () => { + const trigger = renderMenu({presentation: 'popover'}); + const shows = () => + vi.mocked(HTMLElement.prototype.showPopover).mock.calls.length; + let press = finger(trigger); + press.down(); + advance(300); + press.up(); + advance(400); + expect(shows()).toBe(0); + press = finger(trigger); + press.down(); + press.moveTo(31, 20); + advance(600); + expect(shows()).toBe(0); + press.up(); + }); + + it('opens nothing on touch when disabled', () => { + const trigger = renderMenu({isDisabled: true}); + const press = finger(trigger); + press.down(); + advance(1000); expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); - } finally { - vi.useRealTimers(); - } + press.up(); + }); + }, +); + +describe('ContextMenu under a fine pointer: the touch model costs nothing', () => { + beforeEach(() => { + stubPointer(false); + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + 'Date', + ], + }); + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + }); + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); }); - it('suppresses native text selection on the long-press trigger', () => { - const source = readFileSync( - 'packages/core/src/ContextMenu/ContextMenu.tsx', - 'utf8', + it('opens today’s menu for a finger held 500 ms (today’s long press), with no touch model: no growth, no scroll lock, the first row focused', () => { + // A fine pointer in this context, before any check. + expect(window.matchMedia('(pointer: coarse)').matches).toBe(false); + const onTouchStart = vi.fn(); + render( + +
Right-click me
+
, ); + const trigger = screen.getByTestId('ctx'); + expect(trigger).not.toHaveAttribute('data-astryx-pressable'); + const press = finger(trigger); + press.down(); + expect(onTouchStart).toHaveBeenCalledTimes(1); + advance(499); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + expect(trigger.style.getPropertyValue('scale')).toBe(''); + expect(document.body.style.overflow).not.toBe('hidden'); + advance(20); + expect( + screen.getByRole('menuitem', {name: 'Item 1', hidden: true}), + ).toHaveFocus(); + press.up(); + }); - expect(source).toMatch( - /trigger:[\s\S]*?WebkitTouchCallout: 'none',[\s\S]*?WebkitUserSelect: 'none',[\s\S]*?userSelect: 'none'/, + it('does not hand the finger that opened the menu on to it: a slide onto a row and a lift pick nothing', () => { + const onClick = vi.fn(); + render( + +
Right-click me
+
, ); + const trigger = screen.getByTestId('ctx'); + const press = finger(trigger); + press.down(); + advance(500); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + const row = screen.getByRole('menuitem', {name: 'Item 1', hidden: true}); + const box = row.getBoundingClientRect(); + press.moveTo(box.left + 4, box.top + 4); + press.up(); + advance(50); + expect(onClick).not.toHaveBeenCalled(); + }); + + it('opens the cursor menu on a right-click, as before', () => { + render( + +
Right-click me
+
, + ); + const trigger = screen.getByTestId('ctx'); + fireEvent.contextMenu(trigger, {clientX: 20, clientY: 20, detail: 1}); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + advance(20); + expect( + screen.getByRole('menuitem', {name: 'Item 1', hidden: true}), + ).toHaveFocus(); }); +}); - it('cancels the long-press when the finger moves past the threshold', () => { - vi.useFakeTimers(); - try { - render( +describe('ContextMenu: the primary pointer alone picks a finger’s rules (spec:AST-094 FR13, FR33)', () => { + beforeEach(() => { + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + 'Date', + ], + }); + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + }); + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('opens for the same held finger at 735 ms where the primary pointer is coarse, and at 500 ms where it is fine', () => { + const shows = () => + vi.mocked(HTMLElement.prototype.showPopover).mock.calls.length; + const renderTrigger = () => { + const view = render( -
Long-press me
+
Hold me
, ); - const trigger = screen.getByTestId('ctx'); - fireEvent.touchStart(trigger, {touches: [{clientX: 20, clientY: 20}]}); - // Move past MOVE_CANCEL_PX (10px) — treated as a scroll, not a press. - fireEvent.touchMove(trigger, {touches: [{clientX: 20, clientY: 40}]}); - act(() => { - vi.advanceTimersByTime(500); - }); - expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); - } finally { - vi.useRealTimers(); - } + return {trigger: screen.getByTestId('ctx'), unmount: view.unmount}; + }; + // Coarse: the touch model's timeline, no menu at 500 ms. + stubPointer(true); + const coarse = renderTrigger(); + let press = finger(coarse.trigger); + press.down(); + advance(600); + expect(shows()).toBe(0); + advance(contextMenu.press.menuDisplayMs - 600); + expect(shows()).toBe(1); + press.up(); + coarse.unmount(); + vi.mocked(HTMLElement.prototype.showPopover).mockClear(); + // Fine: today's long press, the same finger opens at 500 ms. + stubPointer(false); + const fine = renderTrigger(); + press = finger(fine.trigger); + press.down(); + advance(499); + expect(shows()).toBe(0); + advance(1); + expect(shows()).toBe(1); + press.up(); }); }); @@ -1632,6 +2161,16 @@ describe('ContextMenu inline trigger (triggerAs)', () => { describe('ContextMenu outside dismissal', () => { const finger = (pointerId: number) => ({pointerType: 'touch', pointerId}); + // Under the touch model, a coarse primary pointer. Undone at the end. + function underTouchModel(run: () => void) { + stubPointer(true); + try { + run(); + } finally { + vi.unstubAllGlobals(); + } + } + // Holds a finger on the trigger until the long-press opens the menu. Only // the long-press delay is faked. function longPress(trigger: HTMLElement, pointerId: number) { @@ -1724,7 +2263,25 @@ describe('ContextMenu outside dismissal', () => { expect(onOpenChange).not.toHaveBeenCalledWith(false); }); - it('a tap outside closes the menu through its compatibility mousedown; a scroll that starts outside leaves it open', () => { + it('under the touch model, a tap outside closes the menu at its lift, and a scroll that starts outside closes it as the browser takes the finger', () => { + underTouchModel(() => { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + const {trigger, outside} = renderMenu(onOpenChange); + fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); + // The browser takes this finger for a scroll: no compatibility events. + fireEvent.pointerDown(outside, finger(3)); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + fireEvent.pointerCancel(outside, finger(3)); + expect(onOpenChange).toHaveBeenLastCalledWith(false); + fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); + fireEvent.pointerDown(outside, finger(4)); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + lift(outside, 4); + expect(onOpenChange).toHaveBeenLastCalledWith(false); + }); + }); + + it('outside the touch model, a tap outside closes the menu through its compatibility mousedown, and a scroll that starts outside leaves it open', () => { const onOpenChange = vi.fn<(isOpen: boolean) => void>(); const {trigger, outside} = renderMenu(onOpenChange); fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); @@ -1737,6 +2294,37 @@ describe('ContextMenu outside dismissal', () => { expect(onOpenChange).toHaveBeenLastCalledWith(false); }); + it('with presentation="popover", a finger keeps the released outside dismissal: a scroll or a drag outside leaves the menu open', () => { + underTouchModel(() => { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + render( + <> + +
Long-press me
+
+ + , + ); + const outside = screen.getByRole('button', {name: 'Outside'}); + fireEvent.contextMenu(screen.getByTestId('ctx'), { + clientX: 50, + clientY: 15, + detail: 1, + }); + fireEvent.pointerDown(outside, {...finger(3), clientX: 0, clientY: 0}); + fireEvent.pointerCancel(outside, finger(3)); + fireEvent.pointerDown(outside, {...finger(4), clientX: 0, clientY: 0}); + fireEvent.pointerMove(outside, {...finger(4), clientX: 0, clientY: 40}); + fireEvent.pointerUp(outside, finger(4)); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + }); + }); + it('a mouse press or a pen press outside closes the menu at the press', () => { for (const pointerType of ['mouse', 'pen']) { const onOpenChange = vi.fn<(isOpen: boolean) => void>(); @@ -1749,7 +2337,7 @@ describe('ContextMenu outside dismissal', () => { } }); - it('presses that send no mousedown leave the menu open, as before: a cancelled pointerdown, a finger drag, a second finger', () => { + it('a mouse press that sends no mousedown leaves the menu open, as before', () => { const onOpenChange = vi.fn<(isOpen: boolean) => void>(); const {trigger, outside} = renderMenu(onOpenChange); fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); @@ -1757,18 +2345,48 @@ describe('ContextMenu outside dismissal', () => { // resize handle): the browser sends no mousedown. fireEvent.pointerDown(outside, {pointerType: 'mouse', pointerId: 1}); fireEvent.pointerUp(outside, {pointerType: 'mouse', pointerId: 1}); - // A finger drag on a surface that does not pan (a Slider), lifted. - fireEvent.pointerDown(outside, finger(5)); - fireEvent.pointerMove(outside, finger(5)); - fireEvent.pointerUp(outside, finger(5)); - // A second finger's tap. - fireEvent.pointerDown(outside, finger(6)); - fireEvent.pointerDown(outside, finger(7)); - fireEvent.pointerUp(outside, finger(7)); - fireEvent.pointerCancel(outside, finger(6)); expect(onOpenChange).toHaveBeenLastCalledWith(true); expect(onOpenChange).not.toHaveBeenCalledWith(false); }); + + it('under the touch model, a finger outside closes the menu as it pans past the pan threshold, or at its lift; a second finger waits for the first one', () => { + underTouchModel(() => { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + const {trigger, outside} = renderMenu(onOpenChange); + const open = () => + fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); + // A drag on a surface that does not pan (a Slider): it closes the menu + // as it travels past the pan threshold, before the lift. + open(); + fireEvent.pointerDown(outside, {...finger(5), clientX: 0, clientY: 0}); + fireEvent.pointerMove(outside, {...finger(5), clientX: 8, clientY: 0}); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + fireEvent.pointerMove(outside, {...finger(5), clientX: 30, clientY: 0}); + expect(onOpenChange).toHaveBeenLastCalledWith(false); + fireEvent.pointerUp(outside, finger(5)); + // A second finger's tap does not end the first finger's touch. + open(); + fireEvent.pointerDown(outside, finger(6)); + fireEvent.pointerDown(outside, finger(7)); + fireEvent.pointerUp(outside, finger(7)); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + fireEvent.pointerUp(outside, finger(6)); + expect(onOpenChange).toHaveBeenLastCalledWith(false); + }); + }); + + it('under the touch model, a touch on the menu itself leaves it open', () => { + underTouchModel(() => { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + const {trigger} = renderMenu(onOpenChange); + fireEvent.contextMenu(trigger, {clientX: 50, clientY: 15, detail: 1}); + const menu = screen.getByRole('menu', {hidden: true}); + fireEvent.pointerDown(menu, {...finger(8), clientX: 0, clientY: 0}); + fireEvent.pointerMove(menu, {...finger(8), clientX: 0, clientY: 40}); + fireEvent.pointerUp(menu, finger(8)); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + }); + }); }); describe('ContextMenu: Tab from a flyout leaves the whole menu (APG menu button)', () => { diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index b3b1536ec9e11..d59a02ab30a90 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -4,7 +4,8 @@ /** * @file ContextMenu.tsx * @input Uses React, StyleX, useLayer, shared layer dismissal, BottomSheet, - * useListFocus, and the shared menu-presentation resolver + * useListFocus, the presentation resolver (usePresentation), useLongPress, + * and the touch layer (ContextMenuTouchLayer) * @output Exports ContextMenu with cursor-popover and touch-sheet presentations * @position Core implementation; consumed by index.ts * @@ -35,6 +36,8 @@ * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs * - /packages/core/src/ContextMenu/ContextMenu.test.tsx + * - /packages/core/src/ContextMenu/ContextMenuTouch.ts (the touch layer's one import site) + * - /packages/core/src/ContextMenu/contextMenuPress.ts (touch timeline) * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx * - /packages/cli/assets/templates/blocks/components/ContextMenu/ (showcase blocks) @@ -42,7 +45,6 @@ import React, { useCallback, - useEffect, useId, lazy, useMemo, @@ -59,7 +61,7 @@ import {useLayerInternal} from '../Layer/useLayer'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; import {currentGesture} from '../Layer/gestureCounter'; -import {noteOutsideDismissal} from '../Layer/outsidePress'; +import {useOutsidePress} from '../Layer/outsidePress'; import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList'; import {menuBottomSheetStyles} from '../DropdownMenu/menuBottomSheet.stylex'; import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems'; @@ -77,9 +79,15 @@ import { import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow'; import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn'; import {useInternalListFocus} from '../hooks/useListFocus'; +import {useLongPress} from '../hooks/useLongPress'; import {useMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; -import {useLongPress} from '../hooks/useLongPress'; +import {shadowHostOf} from '../utils/flatTree'; +import {usePresentation} from '../utils/presentation'; +import { + ContextMenuTouchLayer, + type ContextMenuTouchHandle, +} from './ContextMenuTouchLayer'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import { @@ -102,10 +110,7 @@ import type { } from '../DropdownMenu/DropdownMenu'; import {useMergedRefs} from '../hooks/useMergedRefs'; -import { - useAdaptivePresentation, - type AdaptivePresentation, -} from '../hooks/useAdaptivePresentation'; +import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation'; import { registerEnglishFallback, useComponentTranslator, @@ -120,11 +125,12 @@ const LazyMenuBottomSheet = lazy(async () => })), ); const styles = stylex.create({ - // Trigger wrapper: suppress the iOS long-press callout/selection so the - // long-press opens our context menu instead of the native text/callout UI. - // `position: relative` establishes the containing block for the absolutely - // positioned cursor anchor below, so the anchor point tracks the trigger - // (and scrolls with it) instead of the page. + // Trigger wrapper. `position: relative` makes the containing block for the + // absolutely positioned cursor anchor below. So the anchor point follows + // the trigger, and scrolls with it, instead of the page. The iOS callout and + // text selection stay off. A long press or a right-click then opens this + // menu instead of selecting the trigger's text. The + // gesture host adds its own lock for a held press. trigger: { position: 'relative', WebkitTouchCallout: 'none', @@ -167,6 +173,11 @@ const styles = stylex.create({ transitionTimingFunction: easeVars['--ease-standard'], userSelect: 'none', WebkitTouchCallout: 'none', + // A touch open focuses the menu itself, so no row is lit until the finger + // moves onto one, as with DropdownMenu's held finger. The menu is an + // internal focus target, not a control, so it shows no browser ring. + // Keyboard focus moves to an item instead. + outline: 'none', }, // Scroll ownership by the browser's own signal; see DropdownMenu. touchPinchZoom: { @@ -284,11 +295,13 @@ interface ContextMenuBaseProps extends BaseProps { onOpenChange?: (isOpen: boolean) => void; /** * Presentation policy for the menu. - * - `popover`: open beside the pointer position. + * - omitted: the menu at the pointer. Under a finger, a held finger opens it + * on iOS's timeline (the touch model). + * - `popover`: the menu at the pointer on every device, as before. A held + * finger opens it at 500 ms through today's long press. * - `bottom-sheet`: open as an action sheet. * - `adaptive`: use a BottomSheet on compact coarse-pointer viewports and * the cursor-positioned popover elsewhere. - * @default 'popover' */ presentation?: AdaptivePresentation; 'data-testid'?: string; @@ -342,7 +355,7 @@ export function ContextMenu({ label: labelFromProps, isDisabled = false, onOpenChange, - presentation = 'popover', + presentation, triggerAs = 'div', ref, className, @@ -360,8 +373,12 @@ export function ContextMenu({ const t = useComponentTranslator(); const label = labelFromProps ?? t('@astryx.contextMenu.label'); const backLabel = t('@astryx.dropdownMenu.back'); - const resolvedPresentation = useAdaptivePresentation(presentation); - const usesBottomSheet = resolvedPresentation === 'bottom-sheet'; + // The surface, and whether the touch model applies: under a finger, unless + // the caller pins `presentation="popover"`. + const {surface, touchModes} = usePresentation(presentation, { + whenOmitted: 'touch', + }); + const usesBottomSheet = surface === 'bottom-sheet'; // Separate content props (union discriminant) from DOM pass-through attrs. // The union means exactly one of items/menuContent exists in rest; destructure // both so triggerProps contains only DOM-safe attributes. @@ -395,15 +412,20 @@ export function ContextMenu({ const [isOpen, setIsOpen] = useState(false); // An open from the trigger moves focus into the menu once it shows: a frame - // after the show, which for a first open comes as its layer attaches. - const focusOnShowRef = useRef(false); + // after the show, which for a first open comes as its layer attaches. A + // touch open focuses the menu itself; other opens focus its first row. + const focusOnShowRef = useRef<'first' | 'menu' | null>(null); const focusFirstRef = useRef<() => void>(() => {}); + const focusMenuRef = useRef<() => void>(() => {}); const [submenuPath, setSubmenuPath] = useState([]); const currentSubmenu = submenuPath.at(-1); const currentItems = currentSubmenu?.items ?? items; const currentTitle = currentSubmenu?.label ?? label; const sheetLabel = typeof currentTitle === 'string' ? currentTitle : label; + // The mounted touch layer, which says whether it times a finger. + const touchHandleRef = useRef(null); + const updateOpenState = useCallback( (nextIsOpen: boolean) => { if (!nextIsOpen) { @@ -415,12 +437,17 @@ export function ContextMenu({ [onOpenChange], ); + const outsidePress = useOutsidePress(); + // Starts the outside-press watch as the menu shows. It is set below, where + // the menu's list and its close exist. + const watchOutsideRef = useRef<() => void>(() => {}); const layer = useLayerInternal({ mode: 'context', // Mounted at the first open and kept (see the file header). lazyMount: true, keepsMountAfterShow: true, onHide: useCallback(() => { + outsidePress.stop(); setIsOpen(false); onOpenChange?.(false); // Restore focus to the element that was focused before opening. @@ -429,13 +456,19 @@ export function ContextMenu({ if (toRestore && document.contains(toRestore)) { toRestore.focus(); } - }, [onOpenChange]), + }, [onOpenChange, outsidePress]), onShow: useCallback(() => { setIsOpen(true); onOpenChange?.(true); - if (focusOnShowRef.current) { - focusOnShowRef.current = false; - requestAnimationFrame(() => focusFirstRef.current()); + watchOutsideRef.current(); + const focusTarget = focusOnShowRef.current; + if (focusTarget != null) { + focusOnShowRef.current = null; + requestAnimationFrame(() => + focusTarget === 'menu' + ? focusMenuRef.current() + : focusFirstRef.current(), + ); } }, [onOpenChange]), lightDismiss: false, @@ -489,6 +522,7 @@ export function ContextMenu({ focusFollowsLastInput: true, }); focusFirstRef.current = focusFirst; + focusMenuRef.current = () => listRef.current?.focus({preventScroll: true}); // Join the shared stack so an Escape press dismisses exactly one top-most // surface. BottomSheet owns its own dismissal path. @@ -511,44 +545,36 @@ export function ContextMenu({ ), }); - // Dismiss on any click outside the menu. We use popover="manual" (not - // "auto") because the native light-dismiss treats the mouseup from the - // opening right-click as a dismiss event. Handling it ourselves via - // mousedown avoids that race. A touch's compatibility mousedown for the - // press that opened the menu (sent mid-hold by iOS, or as a long press - // lifts by Chromium) belongs to that press's gesture, so it is not read as - // a press outside; any later press is a new gesture and closes as before. - useEffect(() => { - if (!isOpen || usesBottomSheet) { + // The menu is a manual popover: native light dismiss would read the mouseup + // of the opening right-click as a press outside. So one watch closes it. A + // mouse or a pen closes it at the press. Under the touch model, a touch + // closes it as it begins to pan, or at its lift, and the page stays free to + // scroll. Otherwise a touch closes it at its compatibility mousedown. The + // press that opened the menu keeps it open. + watchOutsideRef.current = () => { + const trigger = triggerRef.current; + if (trigger == null) { return; } - // Inside a shadow root, even a closed or nested one, the document sees a - // press on the menu as a press on an outer shadow host, so the menu's own - // tree judges its presses first and the document skips those. - const tree = listRef.current?.getRootNode(); - const shadow = tree instanceof ShadowRoot ? tree : null; - const judged = new WeakSet(); - const handleClickOutside = (e: Event) => { - const menu = listRef.current; - if (judged.has(e)) { - return; - } - judged.add(e); - if (currentGesture() === openingGestureRef.current) { - return; - } - if (menu && !menu.contains(e.target as Node)) { - noteOutsideDismissal(menu.ownerDocument); - closeMenu(); - } - }; - document.addEventListener('mousedown', handleClickOutside); - shadow?.addEventListener('mousedown', handleClickOutside); - return () => { - document.removeEventListener('mousedown', handleClickOutside); - shadow?.removeEventListener('mousedown', handleClickOutside); - }; - }, [isOpen, closeMenu, listRef, usesBottomSheet]); + // The menu mounts after its first show, so each press reads it then. It + // renders in the trigger's own root, which may be another window's. + const root = trigger.getRootNode(); + outsidePress.start( + trigger, + path => listRef.current != null && path.includes(listRef.current), + () => { + if (currentGesture() !== openingGestureRef.current) { + closeMenu(); + } + }, + { + pointerTypes: touchModes ? ['touch'] : [], + closesOnPan: touchModes, + pressTypes: touchModes ? ['mouse', 'pen'] : ['mouse', 'pen', 'touch'], + root: shadowHostOf(root) != null ? root : null, + }, + ); + }; const listKeyDown = useCallback( (e: React.KeyboardEvent) => { @@ -603,7 +629,15 @@ export function ContextMenu({ // what makes the menu context-relative: it scrolls with the content and the // browser auto-flips it against the viewport edges via CSS anchor positioning. const openAtLocalPoint = useCallback( - (localX: number, localY: number, focusEl: HTMLElement | null) => { + ( + localX: number, + localY: number, + focusEl: HTMLElement | null, + // A touch open focuses the menu itself: UIKit lights no row until the + // finger moves onto one. Pointer and keyboard opens focus the first + // item (APG menu pattern); arrow keys reach the items from the menu. + focusTarget: 'first' | 'menu' = 'first', + ) => { const rect = triggerRef.current?.getBoundingClientRect(); const x = rect ? keepAnchorInside(localX, rect.width) : localX; const y = rect ? keepAnchorInside(localY, rect.height) : localY; @@ -625,7 +659,7 @@ export function ContextMenu({ // A first open mounts the layer, and the show runs from the popover // element's callback ref as it attaches, in the same commit, before // the browser paints; a later one shows at once. - focusOnShowRef.current = true; + focusOnShowRef.current = focusTarget; layer.show(); } }, @@ -639,6 +673,22 @@ export function ContextMenu({ [], ); + // A client point in the trigger's own coordinates, where the cursor anchor + // lives. It stays inside the trigger's box. + const toTriggerLocal = useCallback( + (point: {x: number; y: number}): {x: number; y: number} => { + const rect = triggerRef.current?.getBoundingClientRect(); + if (rect == null) { + return point; + } + return { + x: Math.min(Math.max(point.x - rect.left, 0), rect.width), + y: Math.min(Math.max(point.y - rect.top, 0), rect.height), + }; + }, + [], + ); + const handleContextMenu = useCallback( (e: React.MouseEvent) => { if (isDisabled) { @@ -670,19 +720,33 @@ export function ContextMenu({ [isDisabled, openAtLocalPoint, getAnchorBaseRect], ); - // Touch long-press invocation (menus-8). iOS Safari never synthesizes a - // `contextmenu` event on long-press, so a context menu is otherwise - // unreachable on touch. Open the menu at the touch point once the press is - // held long enough (see useLongPress for timer/move-cancel/cleanup logic). - // The hook also returns the imperative start/moveTo/cancel API the menu press - // model drives; only its four touch handlers belong on the trigger element. + // Touch invocation. Under the touch model, the touch layer runs UIKit's long + // press and asks for the menu here, at the client point where the finger + // landed. + const openFromFinger = useCallback( + (point: {x: number; y: number}) => { + const local = toTriggerLocal(point); + // The finger is still down: its lift belongs to the press that opened + // the menu, so it does not close it. + openingGestureRef.current = currentGesture(); + openAtLocalPoint(local.x, local.y, triggerRef.current, 'menu'); + }, + [openAtLocalPoint, toTriggerLocal], + ); + + // Today's long press for a finger outside the touch model: under a fine + // primary pointer, or with `presentation="popover"`, the way back. Safari on + // iOS never sends a `contextmenu` event for a long press. So the menu opens + // at the touch point once the finger is held for 500 ms. The useLongPress + // hook owns the timer, the move cancel and the cleanup. Under the touch + // model, the touch layer's recognizer owns the finger instead. const { onTouchStart: handleLongPressTouchStart, onTouchMove: handleLongPressTouchMove, onTouchEnd: handleLongPressTouchEnd, onTouchCancel: handleLongPressTouchCancel, } = useLongPress({ - disabled: isDisabled, + disabled: isDisabled || touchModes, onLongPress: useCallback( (point: {x: number; y: number}) => { const rect = getAnchorBaseRect(); @@ -698,17 +762,6 @@ export function ContextMenu({ [openAtLocalPoint, getAnchorBaseRect], ), }); - - // ContextMenu owns invocation and long-press cleanup. Consumer handlers are - // notified too, but preventing their default does not cancel component-owned - // behavior that the public API does not promise as cancelable. - const handleTriggerContextMenu = useCallback( - (event: React.MouseEvent) => { - handleContextMenu(event); - onContextMenuProp?.(event); - }, - [handleContextMenu, onContextMenuProp], - ); const handleTriggerTouchStart = useCallback( (event: React.TouchEvent) => { handleLongPressTouchStart(event); @@ -738,6 +791,23 @@ export function ContextMenu({ [handleLongPressTouchCancel, onTouchCancelProp], ); + // ContextMenu owns invocation. Consumer handlers are notified too, but + // preventing their default does not cancel component-owned behavior that + // the public API does not promise as cancelable. + const handleTriggerContextMenu = useCallback( + (event: React.MouseEvent) => { + if (touchHandleRef.current?.isTracking() === true) { + // The browser's own long-press menu (Android Chrome) for a finger the + // recognizer is timing: the recognizer decides, not this event. + event.preventDefault(); + } else { + handleContextMenu(event); + } + onContextMenuProp?.(event); + }, + [handleContextMenu, onContextMenuProp], + ); + const popoverXstyle = menuWidth ? styles.popoverCustomWidth(menuWidth) : styles.popover; @@ -903,6 +973,13 @@ export function ContextMenu({ })} /> + {touchModes && !isDisabled ? ( + + ) : null} {usesBottomSheet ? ( diff --git a/packages/core/src/ContextMenu/ContextMenuTouch.ts b/packages/core/src/ContextMenu/ContextMenuTouch.ts new file mode 100644 index 0000000000000..f8f22f0b96c95 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuTouch.ts @@ -0,0 +1,17 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ContextMenuTouch.ts + * @input ContextMenu's touch modules + * @output ContextMenu's touch layer, its one import site: the press + * recognizer (contextMenuPress.ts) + * @position ContextMenuTouchLayer.tsx, which ContextMenu renders under the + * touch model, imports its touch behaviour from here only; the mouse and + * keyboard paths stay in ContextMenu.tsx + * + * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx + */ + +export {ContextMenuPressRecognizer} from './contextMenuPress'; diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx new file mode 100644 index 0000000000000..9650067be3297 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -0,0 +1,99 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ContextMenuTouchLayer.tsx + * @input ContextMenu's touch layer (ContextMenuTouch.ts), the gesture + * foundation and the UIKit context-menu constants + * @output ContextMenuTouchLayer: renders nothing; runs the trigger's press + * recognizer while ContextMenu is under the touch model + * @position Rendered by ContextMenu while the touch model applies + * + * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx + */ + +import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; +import {playHaptic} from '../gestures/haptics'; +import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; +import {contextMenu} from '../motion/uikit/contextMenu'; +import {ContextMenuPressRecognizer} from './ContextMenuTouch'; + +/** What ContextMenu reaches of a mounted touch layer. */ +export interface ContextMenuTouchHandle { + /** Whether the recognizer is timing a finger on the trigger. */ + isTracking(): boolean; +} + +export interface ContextMenuTouchLayerProps { + triggerRef: RefObject; + /** Receives the layer's handle as it mounts, and null as it unmounts. */ + ref?: Ref; + /** Open the menu at a client point (where the finger landed). */ + onOpen: (point: {x: number; y: number}) => void; +} + +/** + * UIContextMenuInteraction's long press. iOS Safari never fires `contextmenu` + * for a held finger. So the trigger runs its own recognizer on UIKit's + * timeline, `contextMenu.press`. At the commit, the haptic plays and the + * recognizer claims the finger. The page stops scrolling under it, and its + * lift sends no click and no compatibility mouse events. The menu opens where + * the finger landed: at `menuDisplayMs` if it is still down, or at the lift. + * A lift before the commit, a second finger or a scroll gets no menu. So does + * a drift past the tolerance before the menu shows. + */ +export function ContextMenuTouchLayer({ + triggerRef, + ref, + onOpen, +}: ContextMenuTouchLayerProps): null { + const onOpenRef = useRef(onOpen); + onOpenRef.current = onOpen; + const hasPressOpenedRef = useRef(false); + + // The gesture hook follows the element behind the ref, so a `triggerAs` + // swap moves the recognizer to the new node. + const recognizer = useGestureRecognizer( + triggerRef, + () => new ContextMenuPressRecognizer(), + press => { + const open = () => { + hasPressOpenedRef.current = true; + onOpenRef.current(press.press ?? press.location()); + }; + switch (press.state) { + case 'began': + hasPressOpenedRef.current = false; + // The click haptic, where a vibration motor is the only haptic. + // iOS Safari can play none here: no tap lands at the commit. + playHaptic(contextMenu.commitHaptic); + break; + case 'changed': + if (press.isMenuDue && !hasPressOpenedRef.current) { + open(); + } + break; + case 'ended': + if (!hasPressOpenedRef.current) { + open(); + } + break; + case 'possible': + case 'failed': + case 'cancelled': + break; + } + }, + ); + + useImperativeHandle( + ref, + () => ({ + isTracking: () => recognizer.numberOfTouches > 0, + }), + [recognizer], + ); + + return null; +} diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts index d914ca03605f0..e3ceb579c81a6 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts @@ -2,10 +2,12 @@ /** * @file ContextMenuLongPress.a11y.chromium.spec.ts - * @input The `Core/ContextMenu` Default story in a built Storybook and CDP - * touch input. + * @input The `Core/ContextMenu` Default and popover-presentation touch stories + * in a built Storybook, and CDP touch input. * @output Real-engine proof that the long press that opens a context menu * does not close it as the finger lifts, and that a tap outside still does. + * Under the touch model the lift sends no click. Under today's long press + * (`presentation="popover"`) its click arrives and acts on nothing. * @position Run with `pnpm test:a11y-contract`; jsdom cannot produce the * compatibility mouse events a real browser sends after a touch. */ @@ -35,6 +37,8 @@ test.afterAll(async () => { }); const STORY = 'core-contextmenu--default'; +// A finger keeps today's long press under `presentation="popover"`. +const POPOVER_STORY = 'core-contextmenu--touch-long-press-popover'; async function touchCdp(page: Page): Promise { const cdp = await page.context().newCDPSession(page); @@ -45,61 +49,88 @@ async function touchCdp(page: Page): Promise { return cdp; } -async function triggerCenter(page: Page): Promise<{x: number; y: number}> { - const box = await page.getByText('Right-click this area').boundingBox(); +async function triggerCenter( + page: Page, + label = 'Right-click this area', +): Promise<{x: number; y: number}> { + const box = await page.getByText(label).boundingBox(); if (box == null) { throw new Error('the trigger area has no rendered bounds'); } return {x: box.x + box.width / 2, y: box.y + box.height / 2}; } -/** - * Resolves once the browser has delivered the `click` that follows a touch - * (the last of its compatibility mouse events) and two frames have run, so - * anything that event closes has closed. - */ -async function armCompatClick(page: Page): Promise { +interface InputEntry { + type: 'click' | 'touchstart'; + /** For a `touchstart`: whether a menu was open as it arrived. */ + isMenuOpen?: boolean; +} + +/** Records every `click` and `touchstart` the page gets from now on, in order. */ +async function recordInput(page: Page): Promise { await page.evaluate(() => { - const w = window as unknown as {__compatClick?: Promise}; - w.__compatClick = new Promise(resolve => { - document.addEventListener( - 'click', - () => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())), - {once: true, capture: true}, - ); - }); + const entries: {type: string; isMenuOpen?: boolean}[] = []; + (window as unknown as {__input?: typeof entries}).__input = entries; + document.addEventListener( + 'click', + () => { + entries.push({type: 'click'}); + }, + {capture: true}, + ); + document.addEventListener( + 'touchstart', + () => { + entries.push({ + type: 'touchstart', + // A closed menu can stay mounted, hidden. + isMenuOpen: + document.querySelector('[role="menu"]')?.checkVisibility() ?? false, + }); + }, + {capture: true}, + ); }); } -async function compatClickDelivered(page: Page): Promise { - await page.evaluate( - async () => - (window as unknown as {__compatClick?: Promise}).__compatClick, +async function recordedInput(page: Page): Promise { + return page.evaluate( + () => (window as unknown as {__input?: InputEntry[]}).__input ?? [], ); } -test('the long press that opens the menu leaves it open as the finger lifts', async ({ - page, -}) => { - await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`); +const nextFrame = async (page: Page) => + page.evaluate( + async () => + new Promise(resolve => requestAnimationFrame(() => resolve())), + ); + +/** + * Holds a finger on the trigger until the menu opens, lifts it, waits one + * frame, then taps outside. Returns the input recorded from the lift on: the + * outside tap's `touchstart` is the later event that bounds the lift's click. + */ +async function holdLiftThenTapOutside( + page: Page, + story: string, + label?: string, +): Promise { + await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`); + // Touch emulation makes the primary pointer coarse. const cdp = await touchCdp(page); - const center = await triggerCenter(page); + const center = await triggerCenter(page, label); await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{x: center.x, y: center.y, id: 1}], }); const menu = page.getByRole('menu'); await expect(menu).toBeVisible({timeout: 2000}); - await armCompatClick(page); + await recordInput(page); await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [], }); - await compatClickDelivered(page); - await expect(menu).toBeVisible(); - - // A tap outside still closes it. + await nextFrame(page); await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{x: 5, y: 5, id: 2}], @@ -108,7 +139,40 @@ test('the long press that opens the menu leaves it open as the finger lifts', as type: 'touchEnd', touchPoints: [], }); + // A tap outside still closes it. await expect(menu).toBeHidden(); + return recordedInput(page); +} + +/** The clicks before the outside tap, and whether the menu was open at it. */ +function beforeOutsideTap(entries: InputEntry[]) { + const tap = entries.findIndex(entry => entry.type === 'touchstart'); + expect(tap).toBeGreaterThanOrEqual(0); + return { + clicks: entries.slice(0, tap).filter(entry => entry.type === 'click') + .length, + isMenuOpen: entries[tap].isMenuOpen, + }; +} + +test('under the touch model, the long press that opens the menu leaves it open as the finger lifts, and the lift sends no click', async ({ + page, +}) => { + const entries = await holdLiftThenTapOutside(page, STORY); + expect(beforeOutsideTap(entries)).toEqual({clicks: 0, isMenuOpen: true}); +}); + +// The positive control: the same steps see the click that follows today's +// long press, so the check above can fail. +test('with presentation="popover", the click that follows the long press arrives before the outside tap and leaves the menu open', async ({ + page, +}) => { + const entries = await holdLiftThenTapOutside( + page, + POPOVER_STORY, + 'Hold for actions', + ); + expect(beforeOutsideTap(entries)).toEqual({clicks: 1, isMenuOpen: true}); }); test('a mouse press outside closes a right-click menu', async ({page}) => { diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts new file mode 100644 index 0000000000000..a8aa2d26a29a3 --- /dev/null +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -0,0 +1,182 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuLongPress.interaction.browser.spec.ts + * @input The built "Touch / long press" ContextMenu story, real touch input, + * the interaction harness, the context-menu constants and UIKit's frames + * @output Interaction and animation proofs for a context menu that a held + * finger opens on UIKit's timeline. They cover the menu's moments, the + * press feedback against UIKit's frames and a blocked main thread. They + * also cover the page under the finger, a pan outside and a storyboard of + * the press + * @position Interaction specs of packages/core/src/ContextMenu; Chromium's + * finger stands for Android's engine, and WebKit's for iOS + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + installInputLog, + openStory, + readInputLog, + tap, + touchDriver, + withStorybook, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; +import {contextMenu} from '../../motion/uikit/contextMenu'; + +const storybook = withStorybook(test); +const {menuDisplayMs} = contextMenu.press; +// Core's press machine believes a press 150 ms after it lands +// (`utils/pressGesture.ts`). That module loads a StyleX stylesheet, which +// this Node-side spec cannot, so the onset is restated here. + +interface TouchStory { + driver: TouchDriver; + trigger: Locator; + center: {x: number; y: number}; +} + +/** The touch story under the engine's own finger (a coarse pointer). */ +async function openTouchStory( + page: Page, + story = 'core-contextmenu--touch-long-press', +): Promise { + await installInputLog(page); + // Note when the menu is asked to show, on the page clock (no per-frame + // work: rendering proofs share this page). + await page.addInitScript(() => { + const w = window as unknown as {__menuShownAt?: number | null}; + w.__menuShownAt = null; + const show = HTMLElement.prototype.showPopover; + HTMLElement.prototype.showPopover = function ( + this: HTMLElement, + ...args: Parameters + ) { + // Only a popover that holds the menu (Storybook shows its own). + if ( + this.matches('[role="menu"]') || + this.querySelector('[role="menu"]') != null + ) { + w.__menuShownAt ??= performance.now(); + } + return show.apply(this, args); + }; + }); + await openStory(page, storybook(), story); + const driver = await touchDriver(page); + const trigger = page.getByTestId('touch-context-menu'); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); + } + return { + driver, + trigger, + center: {x: box.x + box.width / 2, y: box.y + box.height / 2}, + }; +} + +const menuShownAt = async (page: Page) => + page.evaluate( + () => + (window as unknown as {__menuShownAt?: number | null}).__menuShownAt ?? + null, + ); + +/** The page-clock timestamp of the last `type` event. */ +async function lastInput( + page: Page, + type: 'touchstart' | 'touchend', +): Promise { + const log = await readInputLog(page); + const record = log.filter(entry => entry.type === type).at(-1); + if (record == null) { + throw new Error(`no ${type} reached the page`); + } + return record.timeStamp; +} + +const touchStartedAt = async (page: Page) => lastInput(page, 'touchstart'); + +/** A finger held still for `ms`, then lifted. */ +const hold = (at: {x: number; y: number}, ms: number) => tap(at, {holdMs: ms}); + +test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + await driver.play(hold(center, menuDisplayMs + 200)); + const start = await touchStartedAt(page); + const shown = await menuShownAt(page); + expect(shown, 'the menu never showed').not.toBeNull(); + const after = (shown as number) - start; + // The timer runs at its deadline, give or take a task. + expect(after).toBeGreaterThanOrEqual(menuDisplayMs); + expect(after).toBeLessThan(menuDisplayMs + 20); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + +/** The story with somewhere to scroll below it, and its trigger's center. */ +async function openScrollableStory(page: Page) { + const story = await openTouchStory(page); + await page.evaluate(() => { + document.body.style.paddingBottom = '3000px'; + }); + const box = await story.trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); + } + const center = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + // Where the trigger's container sits: the trigger itself is scaled by the + // press feedback. + const top = async () => + story.trigger.evaluate( + el => (el.parentElement ?? el).getBoundingClientRect().y, + ); + return {...story, center, top}; +} + +test('a new finger that pans outside the open menu closes it, and the page scrolls', async ({ + page, +}) => { + const {driver, center, top} = await openScrollableStory(page); + await driver.play(hold(center, menuDisplayMs + 50)); + const menu = page.getByRole('menu', {name: 'Photo actions'}); + await expect(menu).toBeVisible(); + const before = await top(); + // The menu opens at the finger. So the new finger lands beside the menu's + // box, at the first point below or above it with room for the pan. + const box = await menu.boundingBox(); + const viewport = page.viewportSize(); + if (box == null || viewport == null) { + throw new Error('the menu or the viewport has no box'); + } + const outside = [ + {x: center.x, y: Math.round(box.y + box.height + 40)}, + {x: center.x, y: Math.round(box.y - 40)}, + ].find(point => point.y - 130 > 0 && point.y + 10 < viewport.height); + if (outside == null) { + throw new Error('no point beside the menu has room for the pan'); + } + expect( + await page.evaluate( + ({x, y}) => document.elementFromPoint(x, y)?.closest('[role="menu"]'), + outside, + ), + ).toBeNull(); + await driver.play( + drag(outside, {x: outside.x, y: outside.y - 120}, {durationMs: 300}), + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); + // WebKit scrolls nothing from an injected touch (README: engine limits). + if (driver.drivesNativeGestures) { + expect(await top()).toBeLessThan(before); + } +}); diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts new file mode 100644 index 0000000000000..fdc7db94eb237 --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -0,0 +1,214 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file contextMenuPress.test.ts + * @input vitest, the gesture arena driven by synthetic touches at explicit + * timestamps (the gesture tests' harness), ContextMenuPressRecognizer + * @output The context menu's touch timeline as a state machine. The press + * commits at UIKit's moment and not a millisecond before, at that moment + * even when the timer runs late. It fails on travel past the long-press + * tolerance, a lift, a second finger or the browser taking the touch. The + * commit claims the finger and drops its click. A press that fails leaves + * the click alone + * @position Unit tests of packages/core/src/ContextMenu/contextMenuPress.ts + */ + +import {describe, expect, it} from 'vitest'; +import {createHarness} from '../gestures/__tests__/harness'; +import {contextMenu} from '../motion/uikit/contextMenu'; +import {ContextMenuPressRecognizer} from './contextMenuPress'; + +const COMMIT = contextMenu.press.commitMs; +const DISPLAY = contextMenu.press.menuDisplayMs; + +function setup( + options: ConstructorParameters[0] = {}, +) { + const harness = createHarness(); + const press = new ContextMenuPressRecognizer({name: 'press', ...options}); + const states: string[] = []; + press.addTransitionListener((recognizer, _from, to) => { + states.push(`${to}@${recognizer.clockTime}`); + }); + return {harness, press, states}; +} + +describe('ContextMenuPressRecognizer', () => { + it('commits at UIKit’s moment (iOS 26.2: 400 ms, first 60 Hz tick 417 ms), not a millisecond before', () => { + const {harness, press, states} = setup(); + harness.finger(1).down(100, 200, 1000, {recognizers: [press]}); + harness.advance(1000 + COMMIT - 1); + expect(press.state).toBe('possible'); + harness.advance(1000 + COMMIT); + expect(press.state).toBe('began'); + expect(states).toEqual([`began@${1000 + COMMIT}`]); + expect(COMMIT).toBe(400); + }); + + it('commits at the deadline even when the main thread runs the timer late', () => { + const {harness, press, states} = setup(); + harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + // Nothing ran until 900 ms (a blocked main thread): the press still + // began at 400, and the menu was due at 735. + harness.advance(900); + expect(states).toEqual([`began@${COMMIT}`, `changed@${DISPLAY}`]); + expect(press.beganAt).toBe(COMMIT); + }); + + it('claims the finger at the commit and drops the lift’s click', () => { + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + expect(harness.claims).toEqual([]); + harness.advance(COMMIT); + expect(harness.claims).toEqual([1]); + expect(finger.up(COMMIT + 300)).toBe('suppress'); + expect(press.state).toBe('possible'); + expect(press.press).toBeNull(); + }); + + it('makes the menu due at 735 ms while the finger stays (changed, isMenuDue)', () => { + const {harness, press, states} = setup(); + harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(DISPLAY - 1); + expect(press.isMenuDue).toBe(false); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([`began@${COMMIT}`, `changed@${DISPLAY}`]); + expect(DISPLAY).toBe(735); + }); + + it('ends at a lift after the commit, before the menu is due (UIKit shows the menu at the lift)', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + expect(finger.up(529)).toBe('suppress'); + harness.advance(DISPLAY + 100); + expect(states).toEqual([`began@${COMMIT}`, 'ended@529', 'possible@529']); + }); + + it('is cancelled by a drift past the tolerance after the commit, before the menu', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(0, 5, 480); // within: still committed + finger.move(0, 30, 500); // a 30 px drag at 0.5 s + expect(states).toEqual([`began@${COMMIT}`, 'changed@480', 'cancelled@500']); + harness.advance(DISPLAY + 100); + expect(press.isMenuDue).toBe(false); + }); + + it('lets the finger move freely once the menu is due', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(DISPLAY); + finger.move(0, 80, DISPLAY + 50); + finger.up(DISPLAY + 100); + expect(states).toEqual([ + `began@${COMMIT}`, + `changed@${DISPLAY}`, + `changed@${DISPLAY + 50}`, + `ended@${DISPLAY + 100}`, + `possible@${DISPLAY + 100}`, + ]); + }); + + it.each([ + [7, 7], + [8, 8], + [10, 0], + [11, 11], + [0, -11.5], + ])('still commits after a drift of (%d, %d) pt, as UIKit does', (dx, dy) => { + const {harness, press} = setup(); + harness + .finger(1) + .down(100, 100, 0, {recognizers: [press]}) + .move(100 + dx, 100 + dy, 100); + harness.advance(COMMIT); + expect(press.state).toBe('began'); + }); + + it.each([ + [12, 0], + [0, 12], + [-11.6, 0], + [0, -11.6], + ])( + 'fails on a drift of (%d, %d) pt, past the tolerance on one axis', + (dx, dy) => { + const {harness, press, states} = setup(); + harness + .finger(1) + .down(100, 100, 0, {recognizers: [press]}) + .move(100 + dx, 100 + dy, 250); + expect(press.state).toBe('failed'); + harness.advance(COMMIT); + expect(states).toEqual(['failed@250']); + }, + ); + + it('fails when the finger lifts before the commit, and lets that tap’s click through', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + expect(finger.up(250)).toBe('allow'); + harness.advance(COMMIT); + expect(states).toEqual(['failed@250', 'possible@250']); + }); + + it('fails on a second finger before the commit', () => { + const {harness, press} = setup(); + harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.finger(2).down(50, 0, 120, {recognizers: [press]}); + expect(press.state).toBe('failed'); + }); + + it('ignores a second finger after the commit', () => { + const {harness, press} = setup(); + harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + harness.finger(2).down(50, 0, COMMIT + 20, {recognizers: [press]}); + expect(press.state).toBe('began'); + }); + + it('fails when the browser takes the finger to scroll', () => { + const {harness, press, states} = setup(); + harness + .finger(1) + .down(0, 0, 0, {recognizers: [press]}) + .takenByBrowser(90); + // The browser owns the finger now: the recognizer lets go of it at once. + expect(states).toEqual(['failed@90', 'possible@90']); + }); + + it('keeps the press while it fails, so the feedback knows which one ended', () => { + const {harness, press} = setup(); + let pressAtFailure: unknown = 'unset'; + press.addTransitionListener((recognizer, _from, to) => { + if (to === 'failed') { + pressAtFailure = recognizer.press; + } + }); + harness + .finger(1) + .down(10, 20, 5, {recognizers: [press]}) + .up(200); + expect(pressAtFailure).toEqual({time: 5, x: 10, y: 20}); + expect(press.press).toBeNull(); + }); + + it('takes a finger or a pen, not a mouse (a mouse opens the menu with its secondary button)', () => { + const mouse = setup(); + mouse.harness + .finger(1) + .down(0, 0, 0, {recognizers: [mouse.press], pointerType: 'mouse'}); + mouse.harness.advance(COMMIT); + expect(mouse.press.state).toBe('possible'); + + const pen = setup(); + pen.harness + .finger(1) + .down(0, 0, 0, {recognizers: [pen.press], pointerType: 'pen'}); + pen.harness.advance(COMMIT); + expect(pen.press.state).toBe('began'); + }); +}); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts new file mode 100644 index 0000000000000..dfc25022eeb40 --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -0,0 +1,198 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file contextMenuPress.ts + * @input Touches from the gesture arena and the context-menu constants + * @output ContextMenuPressRecognizer: the long press that opens a context menu + * on UIContextMenuInteraction's timeline under a finger, and the press it + * reports + * @position ContextMenu's touch invocation, on the gesture foundation; + * ContextMenu.tsx attaches it to the trigger + * + * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx + * and /packages/core/src/ContextMenu/contextMenuPress.test.ts + */ + +import {isActive} from '../gestures/GestureRecognizer'; +import { + LongPressGestureRecognizer, + type LongPressGestureRecognizerOptions, +} from '../gestures/LongPressGestureRecognizer'; +import type {GestureEventContext, GestureTouch} from '../gestures/types'; +import {contextMenu} from '../motion/uikit/contextMenu'; + +const {commitMs, menuDisplayMs, allowableMovement} = contextMenu.press; + +/** + * The foundation's own press timer, which this recognizer never lets fire: + * the hold below commits instead. It is longer than any hold, and under the + * window timer's 2^31 - 1 ms limit. + */ +const NEVER_MS = 2 ** 30; + +/** A finger that may become a context menu: when and where it landed. */ +export interface ContextMenuPress { + /** On the event clock (`performance.now()`, an event's `timeStamp`), ms. */ + readonly time: number; + /** Client CSS px. */ + readonly x: number; + readonly y: number; +} + +export type ContextMenuPressRecognizerOptions = Omit< + LongPressGestureRecognizerOptions, + | 'allowableMovement' + | 'minimumPressDuration' + | 'numberOfTapsRequired' + | 'numberOfTouchesRequired' +>; + +/** + * A context menu is not UIKit's plain long press (500 ms, 10 pt of travel). + * Its timeline is `contextMenu.press`, and these are the recognizer's states: + * - `possible`: the finger landed. A lift, a second finger, or a browser + * scroll fails it. A drift past `allowableMovement` on either + * axis fails it too. + * - `began` at `commitMs`: the click haptic. The recognizer claims the touch. + * The page stops scrolling under it, and the lift sends no click and no + * compatibility mouse events. The menu does not show yet. A drift past + * `allowableMovement` still ends it with no menu (`cancelled`). A lift shows + * the menu at once (`ended` without `isMenuDue`). + * - `changed` with `isMenuDue` at `menuDisplayMs`: the finger is still down, + * and the menu shows. From then on, the finger moves freely. + * + * The hold runs on the arena's clock and timers, so the commit lands at its + * deadline even when the main thread is busy. The foundation's long press + * gives the claim and failure rules and the trigger's style. It never begins + * on its own timer, only at the hold's commit. A press that fails or is + * cancelled reports it through `addTransitionListener`, while `press` still + * names it. + */ +export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { + /** The finger in play, from its landing until the gesture resets. */ + press: ContextMenuPress | null = null; + /** + * The finger stayed until `menuDisplayMs`: the menu is due, and the finger + * moves freely from here. + */ + isMenuDue = false; + /** The finger the hold follows. */ + private pressTouchId: number | null = null; + /** Where the finger landed, while its hold runs. The drift counts from here. */ + private holdFrom: {x: number; y: number} | null = null; + /** When the finger landed, on the arena's clock. The deadlines count from it. */ + private holdStart = 0; + + constructor(options: ContextMenuPressRecognizerOptions = {}) { + super({ + ...options, + // A finger or a pen; a mouse opens the menu with its secondary button. + allowedPointerTypes: options.allowedPointerTypes ?? ['touch', 'pen'], + minimumPressDuration: NEVER_MS, + // The hold's own tolerance is the drift rule (touchesMoved below). + allowableMovement: Infinity, + }); + } + + /** + * The event clock at this moment: the timestamp of the input (or the + * deadline of the timer) being processed. Read it from a listener to + * place what the transition starts at the time it happened. + */ + get clockTime(): number { + return this.now(); + } + + protected override touchesBegan( + touches: ReadonlyArray, + event: GestureEventContext, + ): void { + super.touchesBegan(touches, event); + if ( + this.press == null && + this.state === 'possible' && + this.numberOfTouches === this.numberOfTouchesRequired + ) { + const [touch] = touches; + this.press = {time: event.time, x: touch.x, y: touch.y}; + this.pressTouchId = touch.id; + // The hold's deadlines count from the touch itself. This replaces the + // foundation's own press timer, which never fires. + this.holdFrom = {x: touch.x, y: touch.y}; + this.holdStart = event.time; + this.setTimer(event.time + commitMs, () => this.commit()); + } + } + + protected override touchesMoved(touches: ReadonlyArray): void { + const touch = touches.find(each => each.id === this.pressTouchId); + const hasDrifted = touch != null && !this.followHold(touch); + if (hasDrifted && this.state === 'possible') { + this.setState('failed'); + return; + } + if (hasDrifted && isActive(this.state) && !this.isMenuDue) { + this.setState('cancelled'); + return; + } + super.touchesMoved(touches); + } + + /** + * Follows the finger during its hold. A drift past `allowableMovement` on + * either axis ends the hold. Returns whether the hold still runs. + */ + private followHold(touch: GestureTouch): boolean { + const from = this.holdFrom; + if (from == null) { + return false; + } + if ( + Math.abs(touch.x - from.x) > allowableMovement || + Math.abs(touch.y - from.y) > allowableMovement + ) { + this.endHold(); + return false; + } + return true; + } + + private endHold(): void { + this.clearTimer(); + this.holdFrom = null; + } + + /** The hold's commit claims the finger, then waits for the menu's moment. */ + private commit(): void { + if (this.holdFrom == null) { + return; + } + if ( + this.state === 'possible' && + this.numberOfTouches === this.numberOfTouchesRequired + ) { + this.beganAt = this.now(); + this.setState('began'); + } + // A transition listener can end the hold. + if (this.holdFrom != null) { + this.setTimer(this.holdStart + menuDisplayMs, () => this.showMenu()); + } + } + + /** The finger is still down at the menu's moment: the menu is due. */ + private showMenu(): void { + if (this.holdFrom != null && isActive(this.state)) { + this.isMenuDue = true; + this.setState('changed'); + } + } + + protected override reset(): void { + super.reset(); + this.endHold(); + this.pressTouchId = null; + this.press = null; + this.isMenuDue = false; + } +} diff --git a/packages/core/src/Indicator/boxHold.test.tsx b/packages/core/src/Indicator/boxHold.test.tsx index 05bd93d001570..538b601bd7c8a 100644 --- a/packages/core/src/Indicator/boxHold.test.tsx +++ b/packages/core/src/Indicator/boxHold.test.tsx @@ -203,7 +203,10 @@ describe('a finger held on a control’s box', () => { const onChange = vi.fn(); const onOpenChange = vi.fn(); render( - + diff --git a/packages/core/src/Layer/outsidePress.test.ts b/packages/core/src/Layer/outsidePress.test.ts index ca08558aa9853..95beabf96d5a9 100644 --- a/packages/core/src/Layer/outsidePress.test.ts +++ b/packages/core/src/Layer/outsidePress.test.ts @@ -4,8 +4,9 @@ * @file outsidePress.test.ts * @input isFocusInsideOwnedLayer, isPressInsideOwnedLayer and * watchOutsidePress - * @output The shared focus-leave test, and the outside-press watch that - * closes as a finger outside begins to pan, at a cancel or at a lift + * @output The shared focus-leave test, and the outside-press watch. The + * watch closes as a finger outside begins to pan, at a cancel or at a lift. + * For a mouse or a pen it closes at the press */ import {fireEvent} from '@testing-library/react'; @@ -336,3 +337,110 @@ describe('watchOutsidePress, closing on a pan', () => { stop(); }); }); + +describe('watchOutsidePress, closing at the press', () => { + afterEach(() => { + document.body.replaceChildren(); + }); + + const press = (pointerType: string, pointerId = 1) => ({ + pointerType, + pointerId, + composed: true, + }); + + function setup(root?: Node, pressTypes = ['mouse', 'pen']) { + const owner = document.createElement('div'); + const layer = document.createElement('div'); + const item = document.createElement('button'); + layer.append(item); + const outside = document.createElement('button'); + document.body.append(owner, outside); + (root ?? document.body).appendChild(layer); + const onOutside = vi.fn(); + const stop = watchOutsidePress( + owner, + path => path.includes(layer), + onOutside, + {closesOnPan: true, pointerTypes: ['touch'], pressTypes, root}, + ); + return {item, outside, onOutside, stop}; + } + + it('closes at the mousedown of a mouse or a pen press outside, and not again at its lift', () => { + const {outside, onOutside, stop} = setup(); + fireEvent.pointerDown(outside, press('mouse')); + fireEvent.mouseDown(outside); + expect(onOutside).toHaveBeenCalledOnce(); + fireEvent.pointerUp(outside, press('mouse')); + fireEvent.mouseUp(outside); + expect(onOutside).toHaveBeenCalledOnce(); + fireEvent.pointerDown(outside, press('pen', 2)); + fireEvent.mouseDown(outside); + expect(onOutside).toHaveBeenCalledTimes(2); + stop(); + }); + + it('keeps the layer open for a mouse press inside it, in a closed shadow root too', () => { + const host = document.createElement('div'); + document.body.append(host); + const shadow = host.attachShadow({mode: 'closed'}); + const {item, onOutside, stop} = setup(shadow); + fireEvent.pointerDown(item, press('mouse')); + fireEvent.mouseDown(item, {composed: true}); + expect(onOutside).not.toHaveBeenCalled(); + fireEvent.pointerDown(host, press('mouse')); + fireEvent.mouseDown(host, {composed: true}); + expect(onOutside).toHaveBeenCalledOnce(); + stop(); + }); + + it('judges a mousedown that no pointerdown came before as a mouse press', () => { + const {outside, onOutside, stop} = setup(); + fireEvent.mouseDown(outside); + expect(onOutside).toHaveBeenCalledOnce(); + stop(); + }); + + it('leaves a press whose handler stops its mousedown before the document unjudged', () => { + const {outside, onOutside, stop} = setup(); + outside.addEventListener('mousedown', event => event.stopPropagation()); + fireEvent.pointerDown(outside, press('mouse')); + fireEvent.mouseDown(outside); + expect(onOutside).not.toHaveBeenCalled(); + stop(); + }); + + it('leaves a touch to its own judgment, and its compatibility mousedown alone', () => { + const {outside, onOutside, stop} = setup(); + fireEvent.pointerDown(outside, press('touch')); + fireEvent.pointerUp(outside, press('touch')); + expect(onOutside).toHaveBeenCalledOnce(); + fireEvent.mouseDown(outside); + expect(onOutside).toHaveBeenCalledOnce(); + stop(); + }); + + it('judges a touch at its compatibility mousedown when touch is a press type', () => { + const {outside, onOutside, stop} = setup(undefined, [ + 'mouse', + 'pen', + 'touch', + ]); + fireEvent.pointerDown(outside, press('touch')); + fireEvent.pointerUp(outside, press('touch')); + expect(onOutside).not.toHaveBeenCalled(); + fireEvent.mouseDown(outside); + expect(onOutside).toHaveBeenCalledOnce(); + stop(); + }); + + it('counts a layer it closes at the press as an outside dismissal', () => { + const {outside, stop} = setup(); + const before = outsideDismissalCount(document); + fireEvent.pointerDown(outside, press('mouse')); + fireEvent.mouseDown(outside); + expect(outsideDismissalCount(document)).toBe(before + 1); + stop(); + }); +}); diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.ts index 4c34767d91411..55229c34cdd20 100644 --- a/packages/core/src/Layer/outsidePress.ts +++ b/packages/core/src/Layer/outsidePress.ts @@ -5,7 +5,8 @@ /** * @file outsidePress.ts * @input Pointer presses on a document and on the shadow roots around a - * given root; with closesOnPan, pan moves from core's input stream + * given root. With closesOnPan, pan moves from core's input stream. With + * pressTypes, the presses' bubbling mousedown * @output watchOutsidePress, and useOutsidePress, one watch per component. * noteOutsideDismissal and outsideDismissalCount keep a per-document count * of layers that an outside press or focus move closed. The inside tests @@ -35,6 +36,14 @@ export interface OutsidePressOptions { * document judges presses too, and an inner root's judgment stands. */ readonly root?: Node | null; + /** + * The pointer types judged at the press rather than at the lift. A press + * outside by one of them closes the layer at its bubbling `mousedown`, as a + * manual popover's own dismissal does. A press's type is that of the last + * `pointerdown` before its `mousedown`. With none, or one that names no + * type, it is a mouse. The watch does not follow these types at the lift. + */ + readonly pressTypes?: ReadonlyArray; } // A modal host's backdrop press reads this. A press that closed a layer above @@ -60,21 +69,29 @@ export function outsideDismissalCount(doc: Document): number { * @param isInside - Whether a press with this composed path is inside. * @param onOutside - Called once for each press that starts and ends outside, * as native light dismiss does. With `closesOnPan`, also when that press - * pans or is cancelled. + * pans or is cancelled. For a press type, at the press. * @returns Stops watching. */ export function watchOutsidePress( owner: Element, isInside: (path: ReadonlyArray) => boolean, onOutside: () => void, - {pointerTypes, closesOnPan = false, root = null}: OutsidePressOptions = {}, + { + pointerTypes, + closesOnPan = false, + root = null, + pressTypes = [], + }: OutsidePressOptions = {}, ): () => void { const doc = owner.ownerDocument; const shadows = root == null ? [] : shadowRootsOutward(root); let startedOutside = false; let panStart: {id: number; x: number; y: number} | null = null; + // The type of the pointer whose press the next mousedown belongs to. + let pressType: string | null = null; const follows = (event: PointerEvent) => - pointerTypes == null || pointerTypes.includes(event.pointerType); + !pressTypes.includes(event.pointerType) && + (pointerTypes == null || pointerTypes.includes(event.pointerType)); const close = () => { startedOutside = false; panStart = null; @@ -86,6 +103,7 @@ export function watchOutsidePress( // An inner root's listener runs after the outer ones', so its judgment // stands. const handleDown = (event: PointerEvent) => { + pressType = event.pointerType; if (!follows(event)) { return; } @@ -164,10 +182,30 @@ export function watchOutsidePress( } }; + // A press type's press is judged at its bubbling mousedown, so a handler + // that stops it keeps the layer open. An inner root sees it first, with the + // real target, and the outer ones skip it. + let judgedPress: Event | null = null; + const handlePress = (event: Event) => { + if (event === judgedPress) { + return; + } + judgedPress = event; + const type = pressType || 'mouse'; + pressType = null; + if (pressTypes.includes(type) && !isInside(event.composedPath())) { + close(); + } + }; + const judges: EventTarget[] = [ doc, ...shadows.map(({root: shadow}) => shadow), ]; + const pressJudges = pressTypes.length > 0 ? judges : []; + for (const target of pressJudges) { + target.addEventListener('mousedown', handlePress); + } for (const target of judges) { target.addEventListener('pointerdown', handleDown as EventListener, true); } @@ -190,6 +228,9 @@ export function watchOutsidePress( true, ); } + for (const target of pressJudges) { + target.removeEventListener('mousedown', handlePress); + } stopMoves?.(); doc.removeEventListener('pointerup', handleUp, true); for (const {shadow, host, handleRootUp, handleHostUp} of liftJudges) { diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 5d7cec1464883..c739deaa6c701 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -18,6 +18,7 @@ roles through `resolveMotion`. | `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. | | `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, `delaysContentTouches`, scroll to top. | | `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. | +| `uikit/contextMenu.ts` | UIContextMenuInteraction: touch timeline (feedback, commit, menu), drift tolerance, commit haptic. | | `uikit/paging.ts` | A paging UIScrollView: the integrator that settles a release on its page, the page rule, the catch, `setContentOffset(animated:)`. | | `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | diff --git a/packages/core/src/motion/uikit/contextMenu.ts b/packages/core/src/motion/uikit/contextMenu.ts new file mode 100644 index 0000000000000..a6c168b433270 --- /dev/null +++ b/packages/core/src/motion/uikit/contextMenu.ts @@ -0,0 +1,94 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file contextMenu.ts + * @input Measurements of UIContextMenuInteraction on iOS 26.2 + * @output `contextMenu`: UIContextMenuInteraction's touch timeline, drift + * tolerance and commit haptic + * @position The context-menu domain of the UIKit constants table. Only + * ContextMenu's own modules import it. The table's barrel does not + * re-export it. + * + * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md and + * /packages/core/src/ContextMenu/contextMenuPress.ts + */ + +/** + * UIContextMenuInteraction's touch timeline on iOS 26.2. A context menu is not + * a plain long press. A finger that rests on the view starts a press feedback + * after 150 ms. A copy of the view grows uniformly, and its size follows a + * linear ramp through a spring. At 400 ms the press commits. The click haptic + * plays, and the touch can no longer become a tap. The menu displays at 735 ms + * if the finger is still down, or at the lift after the commit. A finger that + * lifts before the commit gets no menu, and the copy springs back. A finger + * that drifts too far before the menu displays gets the same. + * + * UIKit runs this on display-link ticks. So a 60 Hz screen shows each moment + * on the first frame after it: the feedback at 151 ms, the commit at 417 ms. + * The times here are the moments themselves, from the `touchstart` timestamp. + * UIKit counts from the main thread's receipt of the touch, about a frame + * after the hardware timestamp that a browser stamps. A browser's compositor + * shows a value about a frame after its time, so the two offsets cancel. + * Scales are fractions of the view's own size. The lift and dismissal springs + * are `springs.contextMenuLift` and `springs.contextMenuDismiss`. + * + * Every leaf has one or more `@source`. A GUESS value also has the `@measure` + * task that confirms or replaces it. uikit.test.ts enforces both. + */ +export const contextMenu = { + press: { + /** + * When the long press commits. The click haptic plays, and from then on + * the touch belongs to the menu, not to a tap. The menu itself waits for + * `menuDisplayMs` or the lift. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, recognizer state log, Oct 23 2026: the + * clickPresentationExclusion and clickPresentationFailure recognizers + * ended on the first 60 Hz tick after 400 ms (at 416.7 ms; the tick + * before, at 399.5 ms, had not), the haptic played at 420 ms, and the + * platter's size ramp changes slope at 400 ms + * @measure M-CM6 + */ + commitMs: 400, + /** + * How far the finger may drift on either axis, from where it landed, + * until the menu displays; past it the press ends with no menu. Not the + * long press's `UIKIT_GESTURES.longPress.allowableMovement` (a distance): + * a diagonal drift of 15.6 pt still opens the menu. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, drifts at 100, 250 and 500 ms, Oct 23 2026: (7, 7), + * (8, 8), (10, 0) and (11, 11) pt open the menu; (12, 0) and (0, 12) + * cancel it, before and after the onset alike, and a 30 pt drag after + * the commit cancels it too + * @source GUESS — the value, midway in the measured bracket (11, 12) + * @measure M-CM3 + */ + allowableMovement: 11.5, + /** + * When the menu displays for a finger that is still down: the delegate's + * willDisplay, with the backdrop and the menu. Until then, only the press + * copy shows, and it grows on the second ramp. A finger lifted after the + * commit gets the menu at the lift. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, delegate log and per-frame view tree, Oct 23 2026: + * 735–738 ms after the touch over five warm presses at random display + * phase (734 ms on the first press of a session); a press lifted at + * 0.5 s displayed at the lift (529 ms) + */ + menuDisplayMs: 735, + }, + /** + * The click haptic at the commit, as a vibration where that is the only + * haptic (Android browsers). UIKit plays a private pattern + * (`_UIClickPresentationFeedbackGenerator`) at the commit; iOS Safari can + * play nothing at that moment, because no tap lands then. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIFeedbackGenerator hook, Oct 23 2026: the click + * presentation feedback plays 3 ms after the commit, nothing plays for a + * press lifted before it (the moment) + * @source GUESS — a medium impact stands in for the private pattern (the + * kind) + * @measure M-CM5 + */ + commitHaptic: 'impactMedium', +} as const; From 812d3a40fd4e0753ac3be53669aebf8bd8ecab21 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 05:13:36 -0800 Subject: [PATCH 002/151] test(ContextMenu): the hold's menu commits in its deciding task (red) The hold's timer only sets ContextMenu's state, so React mounts and shows the menu in its next scheduled task. A WebKit CI run showed it at 758 ms, past the 735 ms proof's 20 ms. The proof now also wants the menu to show inside the timer task that decides it, and that task at the deadline counted from the touch. The page's stamps record the first show only. --- ...tMenuLongPress.interaction.browser.spec.ts | 53 ++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index a8aa2d26a29a3..973617c03cceb 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -52,8 +52,37 @@ async function openTouchStory( // Note when the menu is asked to show, on the page clock (no per-frame // work: rendering proofs share this page). await page.addInitScript(() => { - const w = window as unknown as {__menuShownAt?: number | null}; + const w = window as unknown as { + __menuShownAt?: number | null; + __menuShownTimerAt?: number | null; + }; w.__menuShownAt = null; + w.__menuShownTimerAt = null; + // When the timer task that runs now started. The hold's moments come from + // the gesture arena's timers. The menu commits in the task that decides + // it, so its show runs inside that timer task. + let timerAt: number | null = null; + const setTimer = window.setTimeout; + window.setTimeout = (( + handler: TimerHandler, + timeout?: number, + ...args: unknown[] + ) => + setTimer( + (...callArgs: unknown[]) => { + const outer = timerAt; + timerAt = performance.now(); + try { + if (typeof handler === 'function') { + handler(...callArgs); + } + } finally { + timerAt = outer; + } + }, + timeout, + ...args, + )) as typeof window.setTimeout; const show = HTMLElement.prototype.showPopover; HTMLElement.prototype.showPopover = function ( this: HTMLElement, @@ -64,7 +93,11 @@ async function openTouchStory( this.matches('[role="menu"]') || this.querySelector('[role="menu"]') != null ) { - w.__menuShownAt ??= performance.now(); + // Only the first show counts, so a later one cannot stand in for it. + if (w.__menuShownAt == null) { + w.__menuShownAt = performance.now(); + w.__menuShownTimerAt = timerAt; + } } return show.apply(this, args); }; @@ -83,6 +116,14 @@ async function openTouchStory( }; } +/** When the timer task that showed the menu started, or null outside one. */ +const menuShownTimerAt = async (page: Page) => + page.evaluate( + () => + (window as unknown as {__menuShownTimerAt?: number | null}) + .__menuShownTimerAt ?? null, + ); + const menuShownAt = async (page: Page) => page.evaluate( () => @@ -115,7 +156,15 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async await driver.play(hold(center, menuDisplayMs + 200)); const start = await touchStartedAt(page); const shown = await menuShownAt(page); + const decided = await menuShownTimerAt(page); expect(shown, 'the menu never showed').not.toBeNull(); + // The menu commits in the timer task that decides it. That task runs at + // the deadline, which counts from the touch's own timestamp. + expect( + decided, + 'the menu showed after the task that decided it', + ).not.toBeNull(); + expect((decided as number) - start).toBeGreaterThanOrEqual(menuDisplayMs - 1); const after = (shown as number) - start; // The timer runs at its deadline, give or take a task. expect(after).toBeGreaterThanOrEqual(menuDisplayMs); From 0776b4071b32c57040daa18b08f0097bf7789a17 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 05:13:37 -0800 Subject: [PATCH 003/151] fix(ContextMenu): the hold commits its menu in the task that decides it The hold's timer opened the menu with a plain state update, which waits for React's next scheduled task: the menu showed 9 ms after the deadline in Chromium and 17 ms in the WebKit CI container. UIKit shows the menu at its moment. The open now commits with flushSync, in the timer task, as a lift's open commits in the lift's dispatch. --- packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 9650067be3297..834178947c100 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -14,6 +14,7 @@ */ import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; +import {flushSync} from 'react-dom'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {contextMenu} from '../motion/uikit/contextMenu'; @@ -60,7 +61,10 @@ export function ContextMenuTouchLayer({ press => { const open = () => { hasPressOpenedRef.current = true; - onOpenRef.current(press.press ?? press.location()); + // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the menu shows in the task that decides it, as UIKit shows it at its moment, not a scheduled task later + flushSync(() => { + onOpenRef.current(press.press ?? press.location()); + }); }; switch (press.state) { case 'began': From e8f5ca1898daf706c39b645a0895759ee8fadb8b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 05:14:22 -0800 Subject: [PATCH 004/151] test(ContextMenu): the menu mounts, closed, at the hold's commit (red) The menu's first show mounts its layer, a render of 6 ms in Chromium and 17 to 21 ms in the WebKit CI container inside the task that shows the menu at 735 ms. UIKit prepares a context menu as the interaction begins and only presents it at its moment. The proofs want the menu mounted, closed and out of the accessibility tree, at the commit; the same element shown at 735 ms or at the lift; and nothing left mounted by a move past the tolerance or a cancel. --- .../core/src/ContextMenu/ContextMenu.test.tsx | 69 +++++++++++++++++++ ...tMenuLongPress.interaction.browser.spec.ts | 19 +++++ 2 files changed, 88 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index 3b3957152001d..2a2284db9cd6f 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -869,6 +869,75 @@ describe.each([ press.up(); }); + it('mounts the menu, closed, at the commit, and shows that element at 735 ms', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.commitMs - 1); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + advance(1); + const menu = screen.getByRole('menu', {hidden: true}); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(contextMenu.press.menuDisplayMs - contextMenu.press.commitMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + expect(screen.getByRole('menu', {hidden: true})).toBe(menu); + press.up(); + }); + + it('shows the menu mounted at the commit at the lift that comes before 735 ms', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(529); + const menu = screen.getByRole('menu', {hidden: true}); + act(() => { + press.up(); + }); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + expect(screen.getByRole('menu', {hidden: true})).toBe(menu); + }); + + it('mounts no menu for a press lifted before the commit', () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(250); + press.up(); + advance(1000); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it.each([ + [ + 'a move past the tolerance', + (trigger: HTMLElement) => { + const moved = {id: 1, x: 20, y: 50}; + dispatchTouch('touchmove', trigger, [moved], [moved]); + }, + ], + [ + 'a touch the browser cancels', + (trigger: HTMLElement) => { + dispatchTouch('touchcancel', trigger, [{id: 1, x: 20, y: 20}], []); + }, + ], + ])( + 'unmounts the menu mounted at the commit after %s, before 735 ms', + (_, end) => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(contextMenu.press.commitMs + 50); + expect(screen.getByRole('menu', {hidden: true})).toBeInTheDocument(); + act(() => { + end(trigger); + }); + advance(contextMenu.press.menuDisplayMs); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + }, + ); + it('lights no row when a touch opens it: focus goes to the menu itself, not its first item', () => { const trigger = renderMenu(); const press = finger(trigger); diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 973617c03cceb..efba3d49c46db 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -172,6 +172,25 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); +test('the menu mounts at the commit, closed and out of the accessibility tree, and shows at 735 ms', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + const playing = driver.play(hold(center, menuDisplayMs + 200)); + const prepared = page + .locator('[popover]') + .filter({has: page.locator('[role="menu"]')}); + // Mounted at the commit (400 ms), well before the menu's moment (735 ms). + await expect(prepared).toHaveCount(1, {timeout: 700}); + expect(await menuShownAt(page), 'the menu showed before 735 ms').toBeNull(); + expect(await prepared.evaluate(el => el.matches(':popover-open'))).toBe( + false, + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toHaveCount(0); + await playing; + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + /** The story with somewhere to scroll below it, and its trigger's center. */ async function openScrollableStory(page: Page) { const story = await openTouchStory(page); From 0fbd309fdf2f8f974c10697f040b46784461fc27 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 05:14:49 -0800 Subject: [PATCH 005/151] fix(ContextMenu): the hold mounts the menu at its commit, closed A lazy context layer gains prepare(), which mounts its content without showing it, and releasePrepared(), which unmounts that content unless the layer has shown since. Both are internal to core's layer hook. At the hold's commit, ContextMenu prepares its layer, so the show at 735 ms or at the lift only reveals it. A press that ends with no menu releases it. component:ContextMenu PR1 names the commit-time mount. --- .../ContextMenu/ContextMenu.spec.md | 4 +- packages/core/src/ContextMenu/ContextMenu.tsx | 14 ++++- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 28 ++++++++- packages/core/src/Layer/useLayer.test.tsx | 60 +++++++++++++++++++ packages/core/src/Layer/useLayer.tsx | 60 ++++++++++++++++++- 5 files changed, 161 insertions(+), 5 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index dac8d53543eaf..29691feaa9afc 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -152,7 +152,9 @@ Consumer props, content modes, and presentation policy remain documented in mounted. A menu never opened mounts no pointer menu surface, only its layer's inert marker: the surface mounts at the first open and stays mounted after it, so a page with many context menus (a table with one per cell) carries no - closed menu surfaces. + closed menu surfaces. A finger's hold mounts the surface, closed, at its + commit, so the menu at 735 ms only shows it; a hold that ends with no menu + unmounts it again. ## Accessibility contract diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index d59a02ab30a90..dafc716443ee3 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -28,7 +28,9 @@ * context menu that was never opened adds no popover element to the page (a * table with a menu on every cell would otherwise carry one per cell). Once * mounted it stays, so every later open and close, its exit animation - * included, runs as before. + * included, runs as before. A finger's hold mounts it, closed, at the + * commit, so the show at 735 ms only reveals it. A hold that ends with no + * menu unmounts it again. * The trigger wrapper is a `div` by default; `triggerAs` makes it an inline * `span`, so a reference inside prose can own a context menu without * breaking the text flow. @@ -666,6 +668,14 @@ export function ContextMenu({ [layer, updateOpenState, usesBottomSheet], ); + // The hold's commit: the menu shows at its moment or at the lift, so its + // layer mounts now, closed, and the show only reveals it. + const prepareMenu = useCallback(() => { + if (!usesBottomSheet) { + layer.prepare(); + } + }, [layer, usesBottomSheet]); + // The box the cursor anchor's offsets are measured from: the trigger, which // is its containing block. const getAnchorBaseRect = useCallback( @@ -978,6 +988,8 @@ export function ContextMenu({ ref={touchHandleRef} triggerRef={triggerRef} onOpen={openFromFinger} + onCommit={prepareMenu} + onCancel={layer.releasePrepared} /> ) : null} diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 834178947c100..a42432403acf2 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -32,6 +32,13 @@ export interface ContextMenuTouchLayerProps { ref?: Ref; /** Open the menu at a client point (where the finger landed). */ onOpen: (point: {x: number; y: number}) => void; + /** + * The hold committed: the menu shows at its moment or at the lift, so its + * content can mount now, hidden. + */ + onCommit?: () => void; + /** The press ended with no menu: what mounted at the commit can go. */ + onCancel?: () => void; } /** @@ -48,16 +55,32 @@ export function ContextMenuTouchLayer({ triggerRef, ref, onOpen, + onCommit, + onCancel, }: ContextMenuTouchLayerProps): null { const onOpenRef = useRef(onOpen); onOpenRef.current = onOpen; + const onCommitRef = useRef(onCommit); + onCommitRef.current = onCommit; + const onCancelRef = useRef(onCancel); + onCancelRef.current = onCancel; const hasPressOpenedRef = useRef(false); // The gesture hook follows the element behind the ref, so a `triggerAs` // swap moves the recognizer to the new node. const recognizer = useGestureRecognizer( triggerRef, - () => new ContextMenuPressRecognizer(), + () => { + const recognizer = new ContextMenuPressRecognizer(); + // Its target-action listeners never hear `failed`, so a press that ends + // with no menu releases what the commit mounted from here. + recognizer.addTransitionListener((_press, _from, to) => { + if (to === 'failed' || to === 'cancelled') { + onCancelRef.current?.(); + } + }); + return recognizer; + }, press => { const open = () => { hasPressOpenedRef.current = true; @@ -72,6 +95,9 @@ export function ContextMenuTouchLayer({ // The click haptic, where a vibration motor is the only haptic. // iOS Safari can play none here: no tap lands at the commit. playHaptic(contextMenu.commitHaptic); + // The menu shows at its moment or at the lift. Mounted now, its + // content costs that show nothing. + onCommitRef.current?.(); break; case 'changed': if (press.isMenuDue && !hasPressOpenedRef.current) { diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx index f6c280516458a..37e0238403433 100644 --- a/packages/core/src/Layer/useLayer.test.tsx +++ b/packages/core/src/Layer/useLayer.test.tsx @@ -208,6 +208,12 @@ function KeptLazyContextHarness({ + + {unsafe ? (

{renderedLayer}

@@ -1024,6 +1030,60 @@ describe('useLayer', () => { expect(layer).toHaveAttribute('data-open', 'true'); }); + it('prepare() mounts it closed, and the next show opens that element at once', async () => { + const showSpy = mockPopover(); + const {container, getByRole} = render(); + + fireEvent.click(getByRole('button', {name: 'Prepare'})); + await waitFor(() => { + expect(container.querySelector('[popover]')).not.toBeNull(); + }); + const layer = container.querySelector('[popover]'); + expect(layer).not.toHaveAttribute('data-open'); + expect(showSpy).not.toHaveBeenCalled(); + + fireEvent.click(getByRole('button', {name: 'Trigger'})); + // Mounted: shown within the call, not after a commit. + expect(showSpy).toHaveBeenCalledOnce(); + expect(container.querySelector('[popover]')).toBe(layer); + expect(layer).toHaveAttribute('data-open', 'true'); + }); + + it('releasePrepared() unmounts a prepared layer that never showed', async () => { + const showSpy = mockPopover(); + const {container, getByRole} = render(); + + fireEvent.click(getByRole('button', {name: 'Prepare'})); + await waitFor(() => { + expect(container.querySelector('[popover]')).not.toBeNull(); + }); + fireEvent.click(getByRole('button', {name: 'Release'})); + + await waitFor(() => { + expect(container.querySelector('[popover]')).toBeNull(); + }); + expect(container.querySelector('template')).not.toBeNull(); + expect(showSpy).not.toHaveBeenCalled(); + }); + + it('releasePrepared() keeps a prepared layer that has shown since', async () => { + mockPopover(); + const {container, getByRole} = render(); + + fireEvent.click(getByRole('button', {name: 'Prepare'})); + await waitFor(() => { + expect(container.querySelector('[popover]')).not.toBeNull(); + }); + const layer = container.querySelector('[popover]'); + fireEvent.click(getByRole('button', {name: 'Trigger'})); + fireEvent.click(getByRole('button', {name: 'Close'})); + fireEvent.click(getByRole('button', {name: 'Release'})); + + await act(async () => {}); + expect(container.querySelector('[popover]')).toBe(layer); + expect(layer?.isConnected).toBe(true); + }); + it('without the option, a lazy layer still unmounts on hide', async () => { mockPopover(); const {container, getByRole} = render( diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index 75b8e877b7cf6..1bfc7ca3d80f4 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -456,6 +456,23 @@ interface InternalLayerFields { wasJustDismissed: () => boolean; } +/** Context-mode members a core component may use through `useLayerInternal`. */ +interface InternalContextLayerFields { + /** + * With `lazyMount`, mounts the layer's content without showing it. The + * popover stays closed, so it shows no pixel and is out of the accessibility + * tree until `show()`, which then only shows it. A caller that knows a show + * is coming spares that show the first mount's render. Does nothing for a + * layer that is mounted already. + */ + prepare: () => void; + /** + * Unmounts what `prepare()` mounted, unless the layer has shown since. A + * layer that has shown keeps its mount as its options say. + */ + releasePrepared: () => void; +} + /** * Context-mode options a core component may pass through `useLayerInternal`; * not part of the public `useLayer` options. @@ -485,7 +502,9 @@ interface InternalContextLayerOptions extends ContextLayerOptions { onCloseStart?: () => void; } -type InternalContextLayerReturn = ContextLayerReturn & InternalLayerFields; +type InternalContextLayerReturn = ContextLayerReturn & + InternalLayerFields & + InternalContextLayerFields; type InternalFixedLayerReturn = FixedLayerReturn & InternalLayerFields; function toCssLength(value: number | string): string { @@ -1427,6 +1446,30 @@ function useLayerImplementation( [mountStore], ); + // The mount came from `prepare()`, and the layer has not shown since. + const isMountPreparedRef = useRef(false); + + const prepare = useCallback(() => { + if (mode !== 'context' || !lazyMount || contextMountRef.current != null) { + return; + } + isMountPreparedRef.current = true; + requestContextMount(); + }, [mode, lazyMount, requestContextMount]); + + const releasePrepared = useCallback(() => { + if ( + !isMountPreparedRef.current || + pendingShowRef.current || + isOpenRef.current + ) { + return; + } + isMountPreparedRef.current = false; + contextMountRef.current = null; + mountStore.set(null); + }, [mountStore]); + const clearContextMount = useCallback(() => { if (mode !== 'context' || !lazyMount || keepsMountAfterShow) { return; @@ -1441,6 +1484,7 @@ function useLayerImplementation( if (wasJustDismissed()) { return; } + isMountPreparedRef.current = false; // A context popover left over until React commits a previous hide must not // be reopened. The synchronous mount ref is the source of truth. const candidate = popoverRef.current; @@ -2111,6 +2155,8 @@ function useLayerImplementation( hide, isOpen, wasJustDismissed, + prepare, + releasePrepared, id, render: renderContext, }), @@ -2121,6 +2167,8 @@ function useLayerImplementation( hide, isOpen, wasJustDismissed, + prepare, + releasePrepared, id, renderContext, ], @@ -2148,7 +2196,15 @@ export function useLayer( ): ContextLayerReturn | FixedLayerReturn { const internalLayer = useLayerImplementation(options); return useMemo(() => { - const {wasJustDismissed: _, ...layer} = internalLayer; + const { + wasJustDismissed: _, + prepare: _prepare, + releasePrepared: _releasePrepared, + ...layer + } = internalLayer as ( + InternalContextLayerReturn | InternalFixedLayerReturn + ) & + Partial; return layer; }, [internalLayer]); } From 32e75c73cc6aa98b8b4db2a2187ac6bd56b5d708 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 05:20:00 -0800 Subject: [PATCH 006/151] test(ContextMenu): a mouse press closes the menu in its own document On main, ContextMenu's mouse and pen dismissal listens on the page's document. A menu rendered into a same-origin iframe or a Document Picture-in-Picture window then closes on a press in the page and stays open on one in its own window. The shared outside-press watch listens in the trigger's own document, as `family:overlay-dismissal` FR8 has every member work in the document it renders in. With main's ContextMenu.tsx, this case fails. --- .../core/src/ContextMenu/ContextMenu.test.tsx | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index 2a2284db9cd6f..17213536c4441 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -27,6 +27,7 @@ import { waitFor, cleanup, createEvent, + within, } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import {readFileSync} from 'node:fs'; @@ -2456,6 +2457,67 @@ describe('ContextMenu outside dismissal', () => { expect(onOpenChange).not.toHaveBeenCalledWith(false); }); }); + + describe('in a second document', () => { + // An app can render a ContextMenu into a same-origin iframe or a Document + // Picture-in-Picture window through a portal. Every press for it then + // happens in that document. + let frame: HTMLIFrameElement; + let secondDocument: Document; + + beforeEach(() => { + frame = document.createElement('iframe'); + document.body.appendChild(frame); + secondDocument = frame.contentDocument!; + // The Popover API stand-in above, on the second window's own prototype. + const {prototype} = secondDocument.defaultView!.HTMLElement; + prototype.showPopover = HTMLElement.prototype.showPopover; + prototype.hidePopover = HTMLElement.prototype.hidePopover; + prototype.matches = HTMLElement.prototype.matches; + }); + + afterEach(() => { + // Unmount before the frame goes, or React removes nodes from a + // document that no longer exists. + cleanup(); + frame.remove(); + }); + + it('a mouse press outside the menu closes it in the document it renders in; a press in the page does not', () => { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + render( + createPortal( + <> + +
Right-click me
+
+ + , + secondDocument.body, + ), + ); + const view = within(secondDocument.body); + fireEvent.contextMenu(view.getByTestId('ctx'), { + clientX: 50, + clientY: 15, + detail: 1, + }); + expect(onOpenChange).toHaveBeenLastCalledWith(true); + fireEvent.pointerDown(document.body, { + pointerType: 'mouse', + pointerId: 1, + }); + fireEvent.mouseDown(document.body); + expect(onOpenChange).not.toHaveBeenCalledWith(false); + const outside = view.getByRole('button', {name: 'Outside'}); + fireEvent.pointerDown(outside, {pointerType: 'mouse', pointerId: 1}); + fireEvent.mouseDown(outside); + expect(onOpenChange).toHaveBeenLastCalledWith(false); + }); + }); }); describe('ContextMenu: Tab from a flyout leaves the whole menu (APG menu button)', () => { From df6fd04576e9fd141d4eb913f90bc4707249715d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:15:20 -0800 Subject: [PATCH 007/151] docs(ContextMenu): PR1 names the outside-press watch and the touch query PR1 listed one mousedown listener and the adaptive query. While the menu is open, the outside-press watch adds pointer listeners to the trigger's document and shadow roots, plus a mousedown listener where a mouse or a pen closes it at the press. With presentation omitted, ContextMenu subscribes to the coarse-pointer query while mounted. --- .../components/ContextMenu/ContextMenu.spec.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 29691feaa9afc..e1a79e4a0779e 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -144,12 +144,13 @@ Consumer props, content modes, and presentation policy remain documented in ### Performance and resources -- **PR1 — Bounded resources.** While open, ContextMenu adds a document (and - shadow-root) mousedown listener for outside dismissal and removes it on - close, and the - pointer menu observes its size and content to decide whether it scrolls. With - `presentation="adaptive"` it subscribes to the compact-touch query while - mounted. A menu never opened mounts no pointer menu surface, only its layer's +- **PR1 — Bounded resources.** While open, ContextMenu's outside-press watch + adds pointer listeners to the trigger's document (and shadow roots), plus a + mousedown listener where a mouse or a pen closes it at the press, and + removes them on close. The pointer menu observes its size and content to + decide whether it scrolls. With `presentation` omitted it subscribes to the + coarse-pointer query while mounted, and with `presentation="adaptive"` to + the compact-touch query. A menu never opened mounts no pointer menu surface, only its layer's inert marker: the surface mounts at the first open and stays mounted after it, so a page with many context menus (a table with one per cell) carries no closed menu surfaces. A finger's hold mounts the surface, closed, at its From 1cedda2d73d250a12bb71b35141eba86d5111143 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 008/151] feat(ContextMenu): a held finger grows the trigger on the lift spring Under a finger, a block trigger grows from the onset, 150 ms after the finger lands, toward 1.0735 times its size on springs.contextMenuLift, and returns on springs.contextMenuDismiss. It carries this pull request's own diff from 63c7a6c009, replayed on main after #9814's squash, and folds these 27 commits (the history of 63c7a6c009 has each one): - test(ContextMenu): a held finger grows the trigger on the theme's motion tokens, and the timeline's other proofs - feat(ContextMenu): a held finger grows the trigger on the theme's motion tokens - test(ContextMenu): a trigger gets its size back when its press feedback goes while the menu it opened is up - fix(ContextMenu): the press feedback attaches through useAttachment, and a departing feedback gives the trigger its size back - refactor(ContextMenu): the touch layer's recognizer carries its transition listener, and the press recognizer drops onPressStart - docs(ContextMenu): FR11's growth cites AST-094 FR45 - test(ContextMenu): the trigger returns on the theme's exit duration and easing when the menu closes - fix(ContextMenu): the trigger returns on the theme's exit duration and easing when the menu closes - docs(ContextMenu): FR11 keeps the measured basis for the hold's moments, and the tests that verify them - docs(ContextMenu): the block-trigger guidance says the trigger grows while the menu is up - test(ContextMenu): the growth starts 150 ms after the finger lands, wherever the press machine marks the press - fix(ContextMenu): the growth starts 150 ms after the finger lands, wherever the press machine marks the press - test(ContextMenu): the trigger's growth plays springs.contextMenuLift, and its returns springs.contextMenuDismiss - fix(ContextMenu): the trigger's growth plays springs.contextMenuLift, and its returns springs.contextMenuDismiss - docs(ContextMenu): FR11 names the block trigger, and the tests, story and comments say the trigger springs back - refactor(ContextMenu): the press feedback stops returning the pressable marker, and two comments say what the code does - test(ContextMenu): a right-click in a scaled container gives the anchor no scale of its own - fix(ContextMenu): the anchor cancels only the press feedback's own growth - fix(ContextMenu): the press feedback imports only its two springs - test(ContextMenu): a drift the recognizer still follows grows at onset - fix(ContextMenu): keep the growth's onset while the recognizer follows - test(ContextMenu): a finger grows at its own onset, marked or not - fix(ContextMenu): a finger arms the growth from its own landing - docs(ContextMenu): the growth starts 150 ms after the finger lands - refactor(ContextMenu): the recognizer times a finger's onset - refactor(ContextMenu): drop a comment that restates followsFingerRef - refactor(ContextMenu): the onset ref comment keeps only its constraint --- .changeset/contextmenu-touch-timeline.md | 2 +- .../storybook/stories/ContextMenu.stories.tsx | 2 +- .../ContextMenu/ContextMenu.spec.md | 66 +- .../core/src/ContextMenu/ContextMenu.doc.mjs | 21 +- .../core/src/ContextMenu/ContextMenu.test.tsx | 234 +++--- packages/core/src/ContextMenu/ContextMenu.tsx | 81 ++- .../core/src/ContextMenu/ContextMenuTouch.ts | 4 +- .../ContextMenuTouchGrowth.test.tsx | 262 +++++++ .../src/ContextMenu/ContextMenuTouchLayer.tsx | 61 +- .../ContextMenuTouchLayerProps.test.tsx | 62 ++ ...tMenuLongPress.interaction.browser.spec.ts | 688 +++++++++++++++++- .../src/ContextMenu/contextMenuPress.test.ts | 13 +- .../core/src/ContextMenu/contextMenuPress.ts | 6 + .../contextMenuPressFeedback.test.tsx | 332 +++++++++ .../ContextMenu/contextMenuPressFeedback.ts | 317 ++++++++ packages/core/src/motion/README.md | 2 +- packages/core/src/motion/uikit/contextMenu.ts | 27 +- .../core/src/utils/pressableCoverage.test.ts | 16 +- 18 files changed, 2033 insertions(+), 163 deletions(-) create mode 100644 packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx create mode 100644 packages/core/src/ContextMenu/ContextMenuTouchLayerProps.test.tsx create mode 100644 packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx create mode 100644 packages/core/src/ContextMenu/contextMenuPressFeedback.ts diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index b8c1a1e95a6c7..df1a62392af22 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu takes the focus, and a row lights only under the finger, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. A block trigger whose menu opens at the finger starts to grow 150 ms after the finger lands, toward its held size on UIKit's lift spring, played on the compositor, and the hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the trigger springs back to its size. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. The trigger returns to its size when the menu closes. A touch open lights no row: the menu takes the focus, and a row lights only under the finger, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 7d8dff9642034..0c25ea1cea0b4 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -667,7 +667,7 @@ export const TouchLongPress: Story = { docs: { description: { story: - 'Where the primary pointer is coarse (a touch screen), hold a finger on the card. As on iOS, a haptic plays at 400 ms where the device can play one, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. While the menu is up, the page still scrolls: a touch outside the menu closes it as it begins to pan.', + 'Where the primary pointer is coarse (a touch screen), hold a finger on the card. As on iOS, it starts to grow after 150 ms, a haptic plays at 400 ms where the device can play one, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the card springs back to its size. While the menu is up, the page still scrolls: a touch outside the menu closes it as it begins to pan. The card returns to its size when the menu closes.', }, }, }, diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index e1a79e4a0779e..5b9cc4172ffde 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -100,20 +100,20 @@ Consumer props, content modes, and presentation policy remain documented in ## Behavioral and layout contract -| ID | Invariant | Basis | -| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| FR1 | Every render contains a caller-provided Trigger area; with `isDisabled` no invocation opens a menu and the native context menu is left alone. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | -| FR2 | The `context-menu` target stays on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | `architecture:component-theming-surface`; current source | -| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | -| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | -| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, the opening finger is not handed to the menu so it cannot slide to a row, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | -| FR6 | With `triggerAs="span"` the Trigger area is an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | DEC-1 | -| FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | -| FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. Implementation gap: the arrow keys and typeahead skip disabled rows today (Current-state impact). | Current source and tests | -| FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | -| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | -| FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | -| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | +| ID | Invariant | Basis | +| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| FR1 | Every render contains a caller-provided Trigger area; with `isDisabled` no invocation opens a menu and the native context menu is left alone. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | +| FR2 | The `context-menu` target stays on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | `architecture:component-theming-surface`; current source | +| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | +| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | +| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, the opening finger is not handed to the menu so it cannot slide to a row, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | +| FR6 | With `triggerAs="span"` the Trigger area is an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | DEC-1 | +| FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | +| FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. Implementation gap: the arrow keys and typeahead skip disabled rows today (Current-state impact). | Current source and tests | +| FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | +| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | +| FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | +| FR12 | Under a finger, a block trigger whose menu opens at the finger grows during a hold toward 1.0735 times its size on `springs.contextMenuLift`, from the onset, 150 ms after the finger lands, and it returns after a lift before the commit on `springs.contextMenuDismiss`, as FR5 names them. The hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured on iOS 26.2 (`motion/uikit/contextMenu.ts`): UIKit commits at 400 ms, shows the menu at 735 ms, and grows the view on a linear ramp chased by a spring. `spec:AST-094` FR4, FR45: the two moments are measured input, and the long-press presentation is a gesture component (FR5), so the growth and its return play their spring roles | ### Allowed variation @@ -248,25 +248,25 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | -| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | -| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | -| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | -| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | -| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | -| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | -| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | -| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | -| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | -| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | -| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | -| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | -| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | -| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does"; `contextMenuPress.test.ts` | A held finger: the commit and the menu's display | A commit or a display off UIKit's moments fails. | `audit:ContextMenu/behavior` | -| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | -| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | +| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | +| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | +| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | +| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | +| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | +| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | +| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | +| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | +| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | +| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | +| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | +| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | +| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | +| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | +| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does"; `contextMenuPress.test.ts`; `contextMenuPressFeedback.test.tsx` "grows toward the held scale on springs.contextMenuLift, from the onset" and "returns on springs.contextMenuDismiss, at the time the recognizer ended the press"; `ContextMenuTouchGrowth.test.tsx` onset cases; the touch story's browser curve and busy-thread cases in Chromium, and an iOS Safari recording for WebKit | A held finger: the commit, the display, the onset, the growth, the early-lift return, their springs | A commit or a display off UIKit's moments, a growth before the onset, or a growth or return off its spring role fails | `audit:ContextMenu/behavior` | +| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | +| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | ## Current-state impact diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs index 4a5b1745c7bbe..7390609678f8b 100644 --- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs +++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -159,7 +159,7 @@ export const docs = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons. Under a finger, where the primary pointer is coarse, a held finger opens it with iOS timing: the menu opens at 735 ms, or as soon as the finger lifts after 400 ms.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons. Under a finger, where the primary pointer is coarse, a held finger opens it with iOS timing: a block trigger whose menu opens at the finger starts to grow at 150 ms, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms.', bestPractices: [ { guidance: true, @@ -186,6 +186,11 @@ export const docs = { description: 'Keep a visible MoreMenu or equivalent trigger for important mobile actions; long-press must not be the only route.', }, + { + guidance: true, + description: + 'Leave a little room around a block trigger: a held finger grows it from its center, by about 7%, while the menu is up.', + }, { guidance: false, description: @@ -223,7 +228,7 @@ export const docs = { export const docsZh = { usage: { description: - '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在主指针为粗指针(触摸屏)时,按住手指即可打开,时序与 iOS 相同:735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。', + '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在主指针为粗指针(触摸屏)时,按住手指即可打开,时序与 iOS 相同:150 毫秒时块级触发区域(菜单在手指处打开时)开始放大,735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。', bestPractices: [ {guidance: true, description: '保持菜单项简洁和面向操作。'}, {guidance: true, description: '有很多项时使用分组和分隔线。'}, @@ -241,6 +246,11 @@ export const docsZh = { description: '重要的移动端操作还应提供可见的 MoreMenu 或同等入口,不要只依赖长按。', }, + { + guidance: true, + description: + '块级触发区域周围请留出少量空间:按住时它会从中心放大约 7%,直到菜单关闭。', + }, { guidance: false, description: '将上下文菜单作为访问重要操作的唯一方式。', @@ -259,7 +269,7 @@ export const docsDense = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (a coarse primary pointer): a held finger opens it at 735 ms, or on a lift after 400 ms.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (a coarse primary pointer): a held finger opens it at 735 ms, or on a lift after 400 ms; a block trigger whose menu opens at the finger grows from 150 ms.', bestPractices: [ {guidance: true, description: 'Keep items concise and action-oriented.'}, { @@ -280,6 +290,11 @@ export const docsDense = { guidance: true, description: 'Keep a visible mobile entry point for important actions.', }, + { + guidance: true, + description: + 'Leave room around a block trigger: a held finger grows it about 7%.', + }, { guidance: false, description: 'Use as the only way to access important actions.', diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index 17213536c4441..e65447bba669b 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -603,113 +603,113 @@ describe('ContextMenu', () => { fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0}); expect(HTMLElement.prototype.showPopover).toHaveBeenCalled(); }); +}); - describe('a menu that was never opened', () => { - it('adds no popover element and no menu until its first open, which mounts and shows it', () => { - render( - -
Right-click me
-
, - ); - expect(document.querySelector('[popover]')).toBeNull(); - expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); - openMenu(); - const popover = document.querySelector('[popover]'); - expect(popover).not.toBeNull(); - expect(popover?.hasAttribute('popover-open')).toBe(true); - expect( - screen.getByRole('menuitem', {name: 'Cut', hidden: true}), - ).toBeInTheDocument(); - }); +describe('a menu that was never opened', () => { + it('adds no popover element and no menu until its first open, which mounts and shows it', () => { + render( + +
Right-click me
+
, + ); + expect(document.querySelector('[popover]')).toBeNull(); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + openMenu(); + const popover = document.querySelector('[popover]'); + expect(popover).not.toBeNull(); + expect(popover?.hasAttribute('popover-open')).toBe(true); + expect( + screen.getByRole('menuitem', {name: 'Cut', hidden: true}), + ).toBeInTheDocument(); + }); - it('shows a first open as its layer attaches, and a later open within the event', () => { - render( - -
Right-click me
-
, + it('shows a first open as its layer attaches, and a later open within the event', () => { + render( + +
Right-click me
+
, + ); + const trigger = screen.getByText('Right-click me'); + const open = () => + trigger.dispatchEvent( + new MouseEvent('contextmenu', {bubbles: true, cancelable: true}), ); - const trigger = screen.getByText('Right-click me'); - const open = () => - trigger.dispatchEvent( - new MouseEvent('contextmenu', {bubbles: true, cancelable: true}), - ); - const showPopover = vi.mocked(HTMLElement.prototype.showPopover); - act(() => { - open(); - // No layer yet: the show waits for its popover element. - expect(showPopover).not.toHaveBeenCalled(); - }); - // The commit attached the layer, which showed it. - expect(showPopover).toHaveBeenCalledTimes(1); - fireEvent.keyDown(document, {key: 'Escape'}); - act(() => { - open(); - // Mounted: shown in the event itself. - expect(showPopover).toHaveBeenCalledTimes(2); - }); + const showPopover = vi.mocked(HTMLElement.prototype.showPopover); + act(() => { + open(); + // No layer yet: the show waits for its popover element. + expect(showPopover).not.toHaveBeenCalled(); }); - - it('a keyboard open moves focus to the first item once the menu shows, and Escape returns it', async () => { - render( - - - , - ); - const button = screen.getByRole('button', {name: 'Right-click me'}); - button.focus(); - // Shift+F10 / the Menu key: a contextmenu at (0, 0) with no click count. - fireEvent.contextMenu(button, {clientX: 0, clientY: 0, detail: 0}); - await waitFor(() => { - expect( - screen.getByRole('menuitem', {name: 'Cut', hidden: true}), - ).toHaveFocus(); - }); - fireEvent.keyDown(document, {key: 'Escape'}); - expect(button).toHaveFocus(); + // The commit attached the layer, which showed it. + expect(showPopover).toHaveBeenCalledTimes(1); + fireEvent.keyDown(document, {key: 'Escape'}); + act(() => { + open(); + // Mounted: shown in the event itself. + expect(showPopover).toHaveBeenCalledTimes(2); }); + }); - it('carries the same trigger and cursor anchor attributes as after it opened', () => { - render( - -
Right-click me
-
, - ); - const trigger = screen.getByTestId('ctx'); - const describe = () => ({ - trigger: [...trigger.attributes].map(a => `${a.name}=${a.value}`), - anchor: [...(trigger.lastElementChild?.attributes ?? [])].map( - a => a.name, - ), - anchorName: ( - (trigger.lastElementChild as HTMLElement | null)?.style as unknown as - Record | undefined - )?.anchorName, - }); - const before = describe(); - openMenu(); - fireEvent.keyDown(document, {key: 'Escape'}); - expect(describe()).toEqual(before); - expect(trigger.hasAttribute('aria-controls')).toBe(false); - expect(trigger.hasAttribute('aria-haspopup')).toBe(false); + it('a keyboard open moves focus to the first item once the menu shows, and Escape returns it', async () => { + render( + + + , + ); + const button = screen.getByRole('button', {name: 'Right-click me'}); + button.focus(); + // Shift+F10 / the Menu key: a contextmenu at (0, 0) with no click count. + fireEvent.contextMenu(button, {clientX: 0, clientY: 0, detail: 0}); + await waitFor(() => { + expect( + screen.getByRole('menuitem', {name: 'Cut', hidden: true}), + ).toHaveFocus(); }); + fireEvent.keyDown(document, {key: 'Escape'}); + expect(button).toHaveFocus(); + }); - it('keeps its layer mounted after the first close, and a second open shows the same menu', () => { - render( - -
Right-click me
-
, - ); - openMenu(); - const menu = screen.getByRole('menu', {hidden: true}); - fireEvent.keyDown(document, {key: 'Escape'}); - expect(menu.isConnected).toBe(true); - expect( - document.querySelector('[popover]')?.hasAttribute('popover-open'), - ).toBe(false); - openMenu(); - expect(screen.getByRole('menu', {hidden: true})).toBe(menu); - expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(2); + it('carries the same trigger and cursor anchor attributes as after it opened', () => { + render( + +
Right-click me
+
, + ); + const trigger = screen.getByTestId('ctx'); + const describe = () => ({ + trigger: [...trigger.attributes].map(a => `${a.name}=${a.value}`), + anchor: [...(trigger.lastElementChild?.attributes ?? [])].map( + a => a.name, + ), + anchorName: ( + (trigger.lastElementChild as HTMLElement | null)?.style as unknown as + Record | undefined + )?.anchorName, }); + const before = describe(); + openMenu(); + fireEvent.keyDown(document, {key: 'Escape'}); + expect(describe()).toEqual(before); + expect(trigger.hasAttribute('aria-controls')).toBe(false); + expect(trigger.hasAttribute('aria-haspopup')).toBe(false); + }); + + it('keeps its layer mounted after the first close, and a second open shows the same menu', () => { + render( + +
Right-click me
+
, + ); + openMenu(); + const menu = screen.getByRole('menu', {hidden: true}); + fireEvent.keyDown(document, {key: 'Escape'}); + expect(menu.isConnected).toBe(true); + expect( + document.querySelector('[popover]')?.hasAttribute('popover-open'), + ).toBe(false); + openMenu(); + expect(screen.getByRole('menu', {hidden: true})).toBe(menu); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(2); }); }); @@ -939,6 +939,11 @@ describe.each([ }, ); + it('leaves a disabled trigger out of the press machine (spec:AST-094 FR24)', () => { + const trigger = renderMenu({isDisabled: true}); + expect(trigger).not.toHaveAttribute('data-astryx-pressable'); + }); + it('lights no row when a touch opens it: focus goes to the menu itself, not its first item', () => { const trigger = renderMenu(); const press = finger(trigger); @@ -1178,6 +1183,11 @@ describe.each([ expect(onTouchEnd).toHaveBeenCalledTimes(1); }); + it('makes the trigger a pressable surface of core’s one press machine', () => { + const trigger = renderMenu(); + expect(trigger).toHaveAttribute('data-astryx-pressable'); + }); + it('keeps today’s menu with presentation="popover": a held finger opens it at 500 ms through today’s long press, with no growth and no scroll lock', () => { const trigger = renderMenu({presentation: 'popover'}); const shows = () => @@ -1713,6 +1723,34 @@ describe('ContextMenu compound mode', () => { expect(anchor.style.top).toBe('40px'); }); + it("places a right-click's anchor at the pointer offset inside a scaled container, with no scale of its own", () => { + render( + +
Right-click me
+
, + ); + const trigger = screen.getByTestId('ctx'); + // A 200x120 trigger inside an ancestor scaled to 0.5. + Object.defineProperty(trigger, 'offsetWidth', {value: 200}); + Object.defineProperty(trigger, 'offsetHeight', {value: 120}); + trigger.getBoundingClientRect = () => + ({ + left: 100, + top: 50, + right: 200, + bottom: 110, + width: 100, + height: 60, + }) as DOMRect; + fireEvent.contextMenu(trigger, {clientX: 150, clientY: 80, detail: 1}); + const anchor = getCursorAnchor(trigger); + expect(anchor.style.left).toBe('50px'); + expect(anchor.style.top).toBe('30px'); + // The ancestor's scale is not the press feedback's growth: nothing to cancel. + expect(anchor.style.scale).toBe(''); + expect(anchor.style.translate).toBe(''); + }); + it('anchors a keyboard-invoked menu to the trigger bottom-left', () => { render( diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index dafc716443ee3..83adbec81a3c2 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -40,6 +40,7 @@ * - /packages/core/src/ContextMenu/ContextMenu.test.tsx * - /packages/core/src/ContextMenu/ContextMenuTouch.ts (the touch layer's one import site) * - /packages/core/src/ContextMenu/contextMenuPress.ts (touch timeline) + * - /packages/core/src/ContextMenu/contextMenuPressFeedback.ts (press feedback) * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx * - /packages/cli/assets/templates/blocks/components/ContextMenu/ (showcase blocks) @@ -82,6 +83,7 @@ import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow'; import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn'; import {useInternalListFocus} from '../hooks/useListFocus'; import {useLongPress} from '../hooks/useLongPress'; +import {pressableProps} from '../utils/pressFeedback'; import {useMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; import {shadowHostOf} from '../utils/flatTree'; @@ -236,6 +238,20 @@ const styles = stylex.create({ }, }); +/** An element's own computed `scale` on each axis; 1 where it has none. */ +function ownScale(element: HTMLElement): {x: number; y: number} { + const value = + element.ownerDocument.defaultView?.getComputedStyle(element).scale ?? ''; + if (value === '' || value === 'none') { + return {x: 1, y: 1}; + } + const [x, y = x] = value.trim().split(/\s+/).map(Number.parseFloat); + return { + x: Number.isFinite(x) && x > 0 ? x : 1, + y: Number.isFinite(y) && y > 0 ? y : 1, + }; +} + /** * Keeps the 1px cursor anchor inside the trigger along one axis. A point in * the trigger's last pixel (Shift+F10 opens on its bottom edge) steps back by @@ -425,18 +441,25 @@ export function ContextMenu({ const currentTitle = currentSubmenu?.label ?? label; const sheetLabel = typeof currentTitle === 'string' ? currentTitle : label; - // The mounted touch layer, which says whether it times a finger. + // The mounted touch layer, for its press feedback and whether it times a + // finger. const touchHandleRef = useRef(null); + // The menu closed: a finger's menu is over, and the trigger returns with + // the close itself (run by every close handler below). + const endTouchOpen = useCallback(() => { + touchHandleRef.current?.release(); + }, []); const updateOpenState = useCallback( (nextIsOpen: boolean) => { if (!nextIsOpen) { setSubmenuPath([]); + endTouchOpen(); } setIsOpen(nextIsOpen); onOpenChange?.(nextIsOpen); }, - [onOpenChange], + [endTouchOpen, onOpenChange], ); const outsidePress = useOutsidePress(); @@ -450,6 +473,7 @@ export function ContextMenu({ keepsMountAfterShow: true, onHide: useCallback(() => { outsidePress.stop(); + endTouchOpen(); setIsOpen(false); onOpenChange?.(false); // Restore focus to the element that was focused before opening. @@ -458,7 +482,7 @@ export function ContextMenu({ if (toRestore && document.contains(toRestore)) { toRestore.focus(); } - }, [onOpenChange, outsidePress]), + }, [endTouchOpen, onOpenChange, outsidePress]), onShow: useCallback(() => { setIsOpen(true); onOpenChange?.(true); @@ -625,6 +649,16 @@ export function ContextMenu({ [listNavKeyDown, closeMenu, typeahead, ownsEvent], ); + // How much the press feedback has grown a block trigger from its center: + // the trigger's own `scale`, not an ancestor's transform. + const triggerScale = useCallback((): {x: number; y: number} => { + const trigger = triggerRef.current; + if (trigger == null || triggerAs === 'span') { + return {x: 1, y: 1}; + } + return ownScale(trigger); + }, [triggerAs]); + // Place the 1px cursor anchor at a point in the trigger's local // coordinate space and open the menu. Positioning the anchor inside the // trigger (rather than storing viewport coordinates on the menu itself) is @@ -641,13 +675,29 @@ export function ContextMenu({ focusTarget: 'first' | 'menu' = 'first', ) => { const rect = triggerRef.current?.getBoundingClientRect(); - const x = rect ? keepAnchorInside(localX, rect.width) : localX; - const y = rect ? keepAnchorInside(localY, rect.height) : localY; + const scale = rect ? triggerScale() : {x: 1, y: 1}; + const x = rect ? keepAnchorInside(localX, rect.width / scale.x) : localX; + const y = rect ? keepAnchorInside(localY, rect.height / scale.y) : localY; positionRef.current = {x, y}; const anchorEl = cursorAnchorRef.current; if (anchorEl) { anchorEl.style.left = `${x}px`; anchorEl.style.top = `${y}px`; + // A trigger the press feedback has grown (from its center) would + // carry the anchor with it, and engines differ on whether anchor + // positioning follows transforms. Cancel the scale at the anchor, so + // its box is the same either way: where the point is on screen. + if (rect != null && (scale.x !== 1 || scale.y !== 1)) { + const centerX = rect.width / scale.x / 2; + const centerY = rect.height / scale.y / 2; + anchorEl.style.transformOrigin = '0 0'; + anchorEl.style.scale = `${1 / scale.x} ${1 / scale.y}`; + anchorEl.style.translate = `${(x - centerX) * (1 / scale.x - 1)}px ${(y - centerY) * (1 / scale.y - 1)}px`; + } else { + anchorEl.style.removeProperty('transform-origin'); + anchorEl.style.removeProperty('scale'); + anchorEl.style.removeProperty('translate'); + } } // Remember the element focused before opening so we can restore it on // close (Escape or outside-click), instead of dropping focus to . @@ -665,7 +715,7 @@ export function ContextMenu({ layer.show(); } }, - [layer, updateOpenState, usesBottomSheet], + [layer, updateOpenState, usesBottomSheet, triggerScale], ); // The hold's commit: the menu shows at its moment or at the lift, so its @@ -684,19 +734,25 @@ export function ContextMenu({ ); // A client point in the trigger's own coordinates, where the cursor anchor - // lives. It stays inside the trigger's box. + // lives. It is the offset from the trigger's laid-out box, before the press + // feedback's scale, and it stays inside that box. const toTriggerLocal = useCallback( (point: {x: number; y: number}): {x: number; y: number} => { const rect = triggerRef.current?.getBoundingClientRect(); if (rect == null) { return point; } + const scale = triggerScale(); + const width = rect.width / scale.x; + const height = rect.height / scale.y; + const left = rect.left + (rect.width - width) / 2; + const top = rect.top + (rect.height - height) / 2; return { - x: Math.min(Math.max(point.x - rect.left, 0), rect.width), - y: Math.min(Math.max(point.y - rect.top, 0), rect.height), + x: Math.min(Math.max(point.x - left, 0), width), + y: Math.min(Math.max(point.y - top, 0), height), }; }, - [], + [triggerScale], ); const handleContextMenu = useCallback( @@ -957,6 +1013,10 @@ export function ContextMenu({ ({ + elements: [] as HTMLElement[], + play: vi.fn(), + animate: vi.fn(), +})); + +vi.mock('../motion/animator', async importOriginal => { + const original = await importOriginal(); + return { + ...original, + createMotionEngine: (element: HTMLElement) => { + animator.elements.push(element); + const pending = () => ({finished: new Promise(() => {})}); + return { + element, + play: (...args: unknown[]) => { + animator.play(element, ...args); + return pending(); + }, + animate: (...args: unknown[]) => { + animator.animate(element, ...args); + return pending(); + }, + stop: () => {}, + dispose: () => {}, + get: () => 1, + getVelocity: () => 0, + reducedMotion: () => 'off', + }; + }, + }; +}); + +interface Contact { + id: number; + x: number; + y: number; +} + +function dispatchTouch( + type: 'touchstart' | 'touchmove' | 'touchend', + target: EventTarget, + changed: Contact[], + all: Contact[], +) { + const event = new Event(type, {bubbles: true, cancelable: true}); + const toTouch = (contact: Contact) => ({ + identifier: contact.id, + clientX: contact.x, + clientY: contact.y, + target, + }); + Object.defineProperty(event, 'changedTouches', {value: changed.map(toTouch)}); + Object.defineProperty(event, 'touches', {value: all.map(toTouch)}); + Object.defineProperty(event, 'timeStamp', {value: performance.now()}); + target.dispatchEvent(event); +} + +const advance = (ms: number) => + act(() => { + vi.advanceTimersByTime(ms); + }); + +/** The press machine's "on", as core's press machine writes it. */ +async function pressMachineOn(trigger: HTMLElement) { + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await act(async () => {}); +} + +/** The press machine lets the press go. */ +async function pressMachineOff(trigger: HTMLElement) { + trigger.removeAttribute(PRESSED_ATTRIBUTE); + await act(async () => {}); +} + +// The gesture host remembers the latest event time, and each install of fake +// timers restarts `performance.now()` near 0. So every case moves the clock on. +let clockEpoch = 0; + +describe('ContextMenu’s growth under a finger', () => { + beforeEach(() => { + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + 'Date', + ], + }); + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + }); + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); + animator.elements.length = 0; + }); + + function renderMenu() { + render( + +
Hold me
+
, + ); + return screen.getByTestId('ctx'); + } + + const scaleBack = (trigger: HTMLElement) => + animator.animate.mock.calls.filter( + ([element, to]) => + element === trigger && (to as {scale?: number}).scale === 1, + ); + + it('springs a grown trigger back when the finger lifts before the commit', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(150); + await pressMachineOn(trigger); + expect(growths(trigger)).toHaveLength(1); + advance(100); + dispatchTouch('touchend', trigger, [contact], []); + expect(scaleBack(trigger)).toHaveLength(1); + }); + + const growths = (trigger: HTMLElement) => + animator.animate.mock.calls.filter( + ([element, to]) => + element === trigger && ((to as {scale?: number}).scale ?? 1) > 1, + ); + const startOf = (call: unknown[]) => (call[3] as {at: number}).at; + + it('starts the growth at the onset, 150 ms after the finger lands, when the press machine marks the press as the finger lands', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + // Outside a scroll view the press machine marks a press as it lands. + await pressMachineOn(trigger); + advance(149); + expect(growths(trigger)).toHaveLength(0); + advance(1); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + }); + + it('grows the trigger at the onset when the press machine marks the press before the recognizer has the finger', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + // In a browser the press machine's mark comes first: its listener runs + // before the recognizer's, and the mark is read between the two. + await pressMachineOn(trigger); + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(150); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + }); + + it('still grows at the onset after a drift past the press machine’s 10 px that the recognizer’s 11.5 px tolerance still follows', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + await pressMachineOn(trigger); + advance(60); + // An 11 px drift: the press machine lets the press go at 10 px. + const drifted = {...contact, x: 31}; + dispatchTouch('touchmove', trigger, [drifted], [drifted]); + await pressMachineOff(trigger); + advance(90); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + }); + + it('grows at the onset after a drift the press machine never marks, as inside a scroll view, that the recognizer still follows', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(60); + // An (8, 8) px drift, 11.3 px: past the machine's 10 px, so it never + // marks the press, and inside the recognizer's 11.5 px. + const drifted = {...contact, x: 28, y: 28}; + dispatchTouch('touchmove', trigger, [drifted], [drifted]); + advance(90); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + }); + + it('grows at the onset, 150 ms after the finger lands, even when the press machine marks the press later', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(150); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + // Inside a scroll view the machine's own timer marks it later. + advance(90); + await pressMachineOn(trigger); + expect(growths(trigger)).toHaveLength(1); + }); + + it('grows a pen’s press at the onset from the press machine’s mark, which finds the recognizer following the pen', async () => { + const trigger = renderMenu(); + const landedAt = performance.now(); + const down = new Event('pointerdown', {bubbles: true, cancelable: true}); + Object.assign(down, { + pointerId: 7, + pointerType: 'pen', + isPrimary: true, + button: 0, + buttons: 1, + clientX: 20, + clientY: 20, + }); + Object.defineProperty(down, 'timeStamp', {value: landedAt}); + // The press machine marks the pen's press from the same pointerdown. + trigger.dispatchEvent(down); + await act(async () => {}); + expect(trigger.getAttribute(PRESSED_ATTRIBUTE)).toBe('on'); + advance(149); + expect(growths(trigger)).toHaveLength(0); + advance(1); + expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + }); + + it('does not grow the trigger for a press its recognizer does not follow, such as a mouse', async () => { + const trigger = renderMenu(); + await pressMachineOn(trigger); + expect(growths(trigger)).toHaveLength(0); + }); +}); diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index a42432403acf2..136b9bc943635 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -7,7 +7,7 @@ * @input ContextMenu's touch layer (ContextMenuTouch.ts), the gesture * foundation and the UIKit context-menu constants * @output ContextMenuTouchLayer: renders nothing; runs the trigger's press - * recognizer while ContextMenu is under the touch model + * recognizer and press feedback while ContextMenu is under the touch model * @position Rendered by ContextMenu while the touch model applies * * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx @@ -15,19 +15,28 @@ import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; import {flushSync} from 'react-dom'; +import {isTerminal} from '../gestures/GestureRecognizer'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {contextMenu} from '../motion/uikit/contextMenu'; -import {ContextMenuPressRecognizer} from './ContextMenuTouch'; +import {isElement} from '../utils/nodeType'; +import { + ContextMenuPressRecognizer, + useContextMenuPressFeedback, +} from './ContextMenuTouch'; /** What ContextMenu reaches of a mounted touch layer. */ export interface ContextMenuTouchHandle { + /** The menu the press opened closed: the trigger returns. */ + release(): void; /** Whether the recognizer is timing a finger on the trigger. */ isTracking(): boolean; } export interface ContextMenuTouchLayerProps { triggerRef: RefObject; + /** False for an inline trigger, which does not grow. */ + isShown: boolean; /** Receives the layer's handle as it mounts, and null as it unmounts. */ ref?: Ref; /** Open the menu at a client point (where the finger landed). */ @@ -49,15 +58,34 @@ export interface ContextMenuTouchLayerProps { * lift sends no click and no compatibility mouse events. The menu opens where * the finger landed: at `menuDisplayMs` if it is still down, or at the lift. * A lift before the commit, a second finger or a scroll gets no menu. So does - * a drift past the tolerance before the menu shows. + * a drift past the tolerance before the menu shows. The press feedback grows + * the trigger from the onset, 150 ms after the finger lands, while the + * recognizer follows the finger. It springs back when the recognizer ends the + * press with no menu, and it holds while that menu is up. */ export function ContextMenuTouchLayer({ triggerRef, + isShown, ref, onOpen, onCommit, onCancel, }: ContextMenuTouchLayerProps): null { + // Whether the recognizer follows a finger or a pen now. It is set below, + // where the recognizer exists. + const isFollowedRef = useRef<() => boolean>(() => false); + // When the finger the recognizer follows landed, for the growth's onset. + const landedAtRef = useRef<() => number | null>(() => null); + const followsFingerRef = useRef<() => boolean>(() => false); + const feedback = useContextMenuPressFeedback( + triggerRef, + isShown, + isFollowedRef, + landedAtRef, + followsFingerRef, + ); + const feedbackRef = useRef(feedback); + feedbackRef.current = feedback; const onOpenRef = useRef(onOpen); onOpenRef.current = onOpen; const onCommitRef = useRef(onCommit); @@ -73,16 +101,31 @@ export function ContextMenuTouchLayer({ () => { const recognizer = new ContextMenuPressRecognizer(); // Its target-action listeners never hear `failed`, so a press that ends - // with no menu releases what the commit mounted from here. - recognizer.addTransitionListener((_press, _from, to) => { + // with no menu springs back from here. + recognizer.addTransitionListener((press, _from, to) => { if (to === 'failed' || to === 'cancelled') { + feedbackRef.current.end(press.clockTime); onCancelRef.current?.(); } }); + // A finger's growth counts from the landing the recognizer records as + // it takes the touch. A pen's press waits for the press machine's mark. + recognizer.onPressBegan = (touch, time) => { + if (touch.pointerType === 'touch') { + feedbackRef.current.begin( + time, + isElement(touch.target) ? touch.target : null, + ); + } + }; return recognizer; }, press => { const open = () => { + // The press feedback grew the trigger from its center, and the cursor + // anchor inside it moves with that scale. So stop the growth where it + // is. ContextMenu places the anchor under the finger. + feedbackRef.current.hold(); hasPressOpenedRef.current = true; // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the menu shows in the task that decides it, as UIKit shows it at its moment, not a scheduled task later flushSync(() => { @@ -117,9 +160,17 @@ export function ContextMenuTouchLayer({ }, ); + isFollowedRef.current = () => + recognizer.numberOfTouches > 0 && !isTerminal(recognizer.state); + landedAtRef.current = () => recognizer.press?.time ?? null; + followsFingerRef.current = () => + isFollowedRef.current() && + recognizer.trackedTouches[0]?.pointerType === 'touch'; + useImperativeHandle( ref, () => ({ + release: () => feedbackRef.current.release(), isTracking: () => recognizer.numberOfTouches > 0, }), [recognizer], diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayerProps.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayerProps.test.tsx new file mode 100644 index 0000000000000..fd65b7b69febd --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayerProps.test.tsx @@ -0,0 +1,62 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuTouchLayerProps.test.tsx + * @input ContextMenu under a coarse pointer, with its touch layer replaced + * @output Checks what ContextMenu asks of its touch layer: a block trigger + * grows, and a trigger whose menu is a bottom sheet does not + * @position Unit tests of packages/core/src/ContextMenu/ContextMenu.tsx + */ + +import {render, waitFor} from '@testing-library/react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {ContextMenu} from './ContextMenu'; +import {ContextMenuTouchLayer} from './ContextMenuTouchLayer'; + +vi.mock('./ContextMenuTouchLayer', () => ({ + ContextMenuTouchLayer: vi.fn(() => null), +})); + +function stubCoarsePointer() { + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); +} + +describe('ContextMenu and its touch layer', () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.mocked(ContextMenuTouchLayer).mockClear(); + }); + + async function shownProp(presentation?: 'bottom-sheet') { + stubCoarsePointer(); + render( + +
Hold me
+
, + ); + await waitFor(() => { + expect(ContextMenuTouchLayer).toHaveBeenCalled(); + }); + return vi.mocked(ContextMenuTouchLayer).mock.lastCall?.[0].isShown; + } + + it('grows a block trigger whose menu is anchored to it', async () => { + expect(await shownProp()).toBe(true); + }); + + it('does not grow a trigger whose menu is a bottom sheet', async () => { + expect(await shownProp('bottom-sheet')).toBe(false); + }); +}); diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index deddefbbed4bf..b83c187617373 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -20,24 +20,56 @@ import { type Page, } from '@astryxdesign/a11y-spec/playwright'; import { + blockMainThread, + busyWindowProof, + castStoryboard, + countBetween, drag, FRAME_STARVATION_MS, FrameStarvationError, + freezeTimers, + holdAnimations, installInputLog, + installLongTaskLog, + installTimerGate, + markElement, + merge, openStory, readInputLog, + releaseAnimations, + startScreencast, tap, + thawTimers, + timeline, touchDriver, + trackMarker, + traceRendering, + waitForAnimation, + withFinger, withStorybook, + writeEvidence, + animationStoryboard, type TouchDriver, } from '@astryxdesign/interaction-harness'; +import {solveSpring, toSpring} from '../../motion/spring'; import {contextMenu} from '../../motion/uikit/contextMenu'; +import {springs} from '../../motion/uikit/springs'; const storybook = withStorybook(test); -const {menuDisplayMs} = contextMenu.press; -// Core's press machine believes a press 150 ms after it lands -// (`utils/pressGesture.ts`). That module loads a StyleX stylesheet, which -// this Node-side spec cannot, so the onset is restated here. +const {commitMs, menuDisplayMs, heldScale} = contextMenu.press; +// The growth starts at the onset, 150 ms after the finger lands +// (`PRESS_ONSET_MS` in `utils/pressGesture.ts`). That module loads a StyleX +// stylesheet, which this Node-side spec cannot, so the onset is restated here. +const feedbackOnsetMs = 150; + +/** The growth's expected curve: `springs.contextMenuLift` from 1 to the held scale. */ +function playedCurve() { + const curve = solveSpring(toSpring(springs.contextMenuLift), { + from: 1, + to: heldScale, + }); + return {at: (t: number) => curve.value(Math.max(0, t))}; +} interface TouchStory { driver: TouchDriver; @@ -51,14 +83,17 @@ async function openTouchStory( story = 'core-contextmenu--touch-long-press', ): Promise { await installInputLog(page); + await installLongTaskLog(page); // Note when the menu is asked to show, on the page clock (no per-frame // work: rendering proofs share this page). await page.addInitScript(() => { const w = window as unknown as { __menuShownAt?: number | null; + __liftHandledAt?: number | null; __menuShownTimerAt?: number | null; }; w.__menuShownAt = null; + w.__liftHandledAt = null; w.__menuShownTimerAt = null; // When the timer task that runs now started. The hold's moments come from // the gesture arena's timers. The menu commits in the task that decides @@ -85,6 +120,15 @@ async function openTouchStory( timeout, ...args, )) as typeof window.setTimeout; + // When the page gets to the lift (the event's own timestamp is the + // hardware's, or the script's): the menu shows in the same task. + addEventListener( + 'touchend', + () => { + w.__liftHandledAt = performance.now(); + }, + {capture: true, passive: true}, + ); const show = HTMLElement.prototype.showPopover; HTMLElement.prototype.showPopover = function ( this: HTMLElement, @@ -148,6 +192,12 @@ async function lastInput( const touchStartedAt = async (page: Page) => lastInput(page, 'touchstart'); +const presentedScale = async (trigger: Locator) => + trigger.evaluate(element => { + const scale = getComputedStyle(element).scale; + return scale === 'none' ? 1 : Number.parseFloat(scale); + }); + /** A finger held still for `ms`, then lifted. */ const hold = (at: {x: number; y: number}, ms: number) => tap(at, {holdMs: ms}); @@ -262,6 +312,554 @@ test('the menu mounts at the commit, closed and out of the accessibility tree, a await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); +test('with presentation="popover" a finger keeps today’s long press: the menu at 500 ms, with no growth and no iOS timeline', async ({ + page, +}) => { + const {driver, trigger, center} = await openTouchStory( + page, + 'core-contextmenu--touch-long-press-popover', + ); + // A coarse primary pointer: only the caller's choice keeps today's menu. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); + expect(await trigger.getAttribute('data-astryx-pressable')).toBeNull(); + const playing = driver.play(hold(center, 1000)); + await page.waitForTimeout(350); + const scaleBeforeOpen = await presentedScale(trigger); + // Still held: the menu is up. At the lift, emulated Chromium sends + // compatibility mouse events that a device sends no click for. They dismiss + // today's menu. The touch model's recognizer claims the finger instead. + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible({ + timeout: 550, + }); + await playing; + const start = await touchStartedAt(page); + const shown = await menuShownAt(page); + expect(shown, 'the menu never showed').not.toBeNull(); + const after = (shown as number) - start; + // Today's 500 ms, give or take a task and the render that shows the menu; + // far from the touch model's 735 ms. + expect(after).toBeGreaterThanOrEqual(500); + expect(after).toBeLessThan(550); + expect(scaleBeforeOpen).toBe(1); +}); + +test('a finger where the primary pointer is fine keeps today’s long press: the menu at 500 ms, with no growth', async ({ + browser, + page, +}) => { + // A touch screen whose primary pointer is fine (a laptop with a trackpad). + const context = await browser.newContext({ + viewport: page.viewportSize() ?? {width: 402, height: 874}, + hasTouch: true, + isMobile: false, + }); + const fine = await context.newPage(); + try { + await installInputLog(fine); + await openStory(fine, storybook(), 'core-contextmenu--touch-long-press'); + const coarse = await fine.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip( + coarse, + 'this engine reports a coarse primary pointer whenever touch is emulated; the fine-primary finger is covered in jsdom', + ); + const trigger = fine.getByTestId('touch-context-menu'); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); + } + expect(await trigger.getAttribute('data-astryx-pressable')).toBeNull(); + const driver = await touchDriver(fine); + const center = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + const playing = driver.play(hold(center, 1000)); + await fine.waitForTimeout(350); + const scaleBeforeOpen = await presentedScale(trigger); + await expect(fine.getByRole('menu', {name: 'Photo actions'})).toBeVisible({ + timeout: 550, + }); + await playing; + expect(scaleBeforeOpen).toBe(1); + } finally { + await context.close(); + } +}); + +test('under Reduce Motion the card does not grow, and the menu still opens at 735 ms', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const {driver, trigger, center} = await openTouchStory(page); + const playing = driver.play(hold(center, menuDisplayMs + 200)); + // Sampled while the finger is down: before the commit, after it, and just + // before the menu. + const scales: number[] = []; + for (const wait of [300, 250, 100]) { + await page.waitForTimeout(wait); + scales.push(await presentedScale(trigger)); + } + await playing; + const start = await touchStartedAt(page); + const shown = await menuShownAt(page); + expect(scales).toEqual([1, 1, 1]); + expect(await trigger.evaluate(el => el.getAnimations().length)).toBe(0); + expect(shown, 'the menu never showed').not.toBeNull(); + const after = (shown as number) - start; + // The touch's stamp and the page clock are each coarsened (0.1 ms). + expect(after).toBeGreaterThanOrEqual(menuDisplayMs - 0.5); + expect(after).toBeLessThan(menuDisplayMs + 20); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + +test('the trigger’s selection and callout lock: its own style keeps it off at rest, and the gesture host refuses a selection for a held press', async ({ + page, +}) => { + const {driver, trigger, center} = await openTouchStory(page); + // WebKit spells it `-webkit-user-select` only. + const readLock = async () => + trigger.evaluate(el => { + const host = el as HTMLElement; + const computed = getComputedStyle(host); + return { + inline: + host.style.getPropertyValue('user-select') || + host.style.getPropertyValue('-webkit-user-select'), + computed: + computed.getPropertyValue('user-select') || + computed.getPropertyValue('-webkit-user-select'), + }; + }); + // Off iOS, the host's lock refuses a selection that starts on the element. + const refusesSelection = async () => + trigger.evaluate(el => { + const event = new Event('selectstart', {bubbles: true, cancelable: true}); + el.dispatchEvent(event); + return event.defaultPrevented; + }); + // At rest the trigger's own style keeps selection off (spec:AST-017 + // FR59), and nothing refuses a selection. + const rest = await readLock(); + expect(rest.computed).toBe('none'); + expect(await refusesSelection()).toBe(false); + // A held finger, short of the commit: the host's lock refuses a selection. + const playing = driver.play(hold(center, commitMs - 100)); + await page.waitForTimeout(commitMs / 2); + const heldRefuses = await refusesSelection(); + const held = await readLock(); + await playing; + await page.waitForTimeout(100); + // Lifted with no menu: back to the rest state. + const liftedRefuses = await refusesSelection(); + const lifted = await readLock(); + expect(heldRefuses).toBe(true); + expect(held.computed).toBe('none'); + expect(liftedRefuses).toBe(false); + expect(lifted).toEqual(rest); + expect( + await page.getByRole('menu', {name: 'Photo actions'}).isVisible(), + ).toBe(false); +}); + +test('a touch open lights no row: the menu itself takes the focus, and every row keeps its resting background', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + const playing = driver.play(hold(center, menuDisplayMs + 300)); + const menu = page.getByRole('menu', {name: 'Photo actions'}); + await expect(menu).toBeVisible(); + // The focus moves on the frame after the menu shows. + await page.evaluate( + async () => + new Promise(resolve => { + requestAnimationFrame(() => { + requestAnimationFrame(() => { + resolve(); + }); + }); + }), + ); + await expect(menu).toBeFocused(); + // An internal focus target: no browser ring on it. + expect(await menu.evaluate(el => getComputedStyle(el).outlineStyle)).toBe( + 'none', + ); + const backgrounds = await menu + .getByRole('menuitem') + .evaluateAll(rows => + rows.map(row => getComputedStyle(row).backgroundColor), + ); + expect(new Set(backgrounds).size).toBe(1); + await playing; +}); + +test('a finger lifted after the commit gets the menu at the lift, and sends no click', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + await driver.play(hold(center, 530)); + await page.waitForTimeout(300); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + const {lift, shown} = await page.evaluate(() => { + const w = window as unknown as { + __menuShownAt?: number | null; + __liftHandledAt?: number | null; + }; + return {lift: w.__liftHandledAt ?? null, shown: w.__menuShownAt ?? null}; + }); + expect(lift).not.toBeNull(); + expect(shown).not.toBeNull(); + // In the lift's own task: after it, and before the next frame could paint. + expect((shown as number) - (lift as number)).toBeGreaterThanOrEqual(0); + expect((shown as number) - (lift as number)).toBeLessThan(1000 / 60); + const log = await readInputLog(page); + const end = log.filter(record => record.type === 'touchend').at(-1); + expect(end?.defaultPrevented, JSON.stringify(log)).toBe(true); + expect(log.filter(record => record.type === 'click')).toEqual([]); +}); + +test('the lift after the menu shows keeps it open and sends no click', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + await driver.play(hold(center, menuDisplayMs + 150)); + await page.waitForTimeout(300); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + const log = await readInputLog(page); + expect(log.filter(record => record.type === 'click')).toEqual([]); +}); + +test('the menu’s anchor sits under the finger, on screen and as laid out, while the trigger is grown, and the menu stays put', async ({ + page, +}) => { + const {driver, trigger} = await openTouchStory(page); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); + } + const menu = page.getByRole('menu', {name: 'Photo actions'}); + // The cursor anchor (the trigger's last child), on screen and as laid out + // (engines differ on which one anchor positioning reads), and the menu. + const read = async () => + trigger.evaluate(el => { + const anchor = el.lastElementChild as HTMLElement | null; + const box = el.getBoundingClientRect(); + const host = el as HTMLElement; + const left = box.left + (box.width - host.offsetWidth) / 2; + const top = box.top + (box.height - host.offsetHeight) / 2; + const onScreen = anchor?.getBoundingClientRect(); + const list = document + .querySelector('[role="menu"]') + ?.getBoundingClientRect(); + return { + onScreen: onScreen == null ? null : {x: onScreen.x, y: onScreen.y}, + laidOut: + anchor == null + ? null + : { + x: left + host.clientLeft + anchor.offsetLeft, + y: top + host.clientTop + anchor.offsetTop, + }, + menu: list == null ? null : {x: list.x, y: list.y}, + }; + }); + // The middle of the card and near its far corner, where an anchor placed + // in the grown trigger's scaled coordinates would land furthest off. + for (const [fx, fy] of [ + [0.5, 0.5], + [0.9, 0.85], + ] as const) { + const p = { + x: Math.round(box.x + box.width * fx), + y: Math.round(box.y + box.height * fy), + }; + await driver.play(hold(p, menuDisplayMs + 100)); + await expect(menu).toBeVisible(); + const first = await read(); + await page.waitForTimeout(400); + const later = await read(); + await page.keyboard.press('Escape'); + await expect(menu).toBeHidden(); + // Let the trigger return to its size before the next press. + await page.waitForTimeout(1200); + const detail = JSON.stringify({p, first, later}); + expect(first.onScreen?.x, detail).toBeCloseTo(p.x, 0); + expect(first.onScreen?.y, detail).toBeCloseTo(p.y, 0); + expect(first.laidOut?.x, detail).toBeCloseTo(p.x, 0); + expect(first.laidOut?.y, detail).toBeCloseTo(p.y, 0); + expect(later.menu?.x, detail).toBeCloseTo(first.menu?.x ?? NaN, 0); + expect(later.menu?.y, detail).toBeCloseTo(first.menu?.y ?? NaN, 0); + } +}); + +test('a drag past the tolerance after the commit opens nothing', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + await driver.play( + drag( + center, + {x: center.x, y: center.y + 30}, + {durationMs: 50, holdMs: 500, restMs: 400}, + ), + ); + await page.waitForTimeout(200); + expect(await menuShownAt(page)).toBeNull(); +}); + +test('an early lift opens nothing, and the card springs back to its size', async ({ + page, +}) => { + const {driver, trigger, center} = await openTouchStory(page); + await driver.play(hold(center, 280)); + await page.waitForTimeout(commitMs + 200); + expect(await menuShownAt(page)).toBeNull(); + // The return spring settles within ~1.2 s; then the scale is gone. + await expect + .poll(async () => trigger.evaluate(el => (el as HTMLElement).style.scale), { + timeout: 3000, + }) + .toBe(''); + expect(await presentedScale(trigger)).toBe(1); +}); + +test('a second finger landing before the commit cancels: no menu, and the card springs back', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'two-finger input is Chromium-only in Playwright (WebKit drops the first finger)', + ); + const {driver, trigger, center} = await openTouchStory(page); + // The first finger holds; a second lands 200 ms in, before the commit. + await driver.play( + merge( + hold(center, menuDisplayMs + 300), + withFinger(hold({x: center.x + 50, y: center.y}, 400), 1, 200), + ), + ); + await page.waitForTimeout(300); + expect(await menuShownAt(page)).toBeNull(); + expect(await presentedScale(trigger)).toBeCloseTo(1, 3); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); +}); + +test('a drift within the tolerance still opens the menu; past it on one axis cancels', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + // (8, 8): 11.3 px away, within the tolerance on each axis (a long press's + // 10 px distance would cancel it). A drift past the browser's own pan slop + // goes to the page instead, as a scroll view's pan takes it on iOS. Lifted + // after the commit: the menu opens at the lift. + await driver.play( + drag( + center, + {x: center.x + 8, y: center.y + 8}, + {durationMs: 60, holdMs: 100, restMs: commitMs}, + ), + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + + const other = await openTouchStory(page); + await other.driver.play( + drag( + other.center, + {x: other.center.x, y: other.center.y + 12}, + {durationMs: 60, holdMs: 100, restMs: commitMs}, + ), + ); + await page.waitForTimeout(200); + expect(await menuShownAt(page)).toBeNull(); +}); + +test('the press feedback plays its computed curve on the compositor, frame by frame', async ({ + page, +}, testInfo) => { + const {driver, trigger, center} = await openTouchStory(page); + const played = playedCurve(); + const playing = driver.play(hold(center, commitMs + 300)); + await waitForAnimation(trigger, {minProgressMs: 16}); + await holdAnimations(page, trigger); + // Seek the held curve (its time 0 is the onset after the touch) to every + // 60 Hz frame and read the presented scale. + const samples = await trigger.evaluate((element, times) => { + const held = + (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? []; + return times.map(t => { + for (const animation of held) { + animation.currentTime = t; + } + const scale = getComputedStyle(element).scale; + return {t, value: scale === 'none' ? 1 : Number.parseFloat(scale)}; + }); + }, timeline(560)); + await releaseAnimations(page); + await playing; + const at = (ms: number) => { + const t = ms - feedbackOnsetMs; + if (t <= 0) { + return 1; + } + // Linear between the seeked frames. + const i = samples.findIndex(s => s.t >= t); + if (i <= 0) { + return samples[Math.max(0, i)].value; + } + const a = samples[i - 1]; + const b = samples[i]; + return a.value + ((b.value - a.value) * (t - a.t)) / (b.t - a.t); + }; + // The card is 200 px wide, so a scale error times 200 is in pixels. + const errors = Array.from({length: 33}, (_, i) => feedbackOnsetMs + i * 17) + .filter(ms => ms <= commitMs + 300) + .map(ms => { + const expected = played.at((ms - feedbackOnsetMs) / 1000); + return { + ms, + expected, + web: at(ms), + errorPx: Math.abs(at(ms) - expected) * 200, + }; + }); + const rms = Math.sqrt( + errors.reduce((sum, e) => sum + e.errorPx ** 2, 0) / errors.length, + ); + await writeEvidence( + 'curves/contextmenu-press-feedback', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {rmsPt: rms, errors, samples}, + null, + 1, + ), + }, + testInfo, + ); + testInfo.annotations.push({ + type: 'curve-parity', + description: `press feedback vs its computed curve (200 px card): rms ${rms.toFixed(3)} px over ${errors.length} frames`, + }); + expect(rms).toBeLessThan(0.1); + expect(Math.max(...errors.map(e => e.errorPx))).toBeLessThan(0.25); +}); + +test('the press feedback keeps advancing every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName === 'webkit', + "WebKit's Linux build runs the trigger's scale, as a transform too, on the main thread: beside a compositor control, its frames hold the trigger's width through the block (README: engine limits). The iOS simulator recording is the WebKit proof.", + ); + const {driver, trigger, center} = await openTouchStory(page); + // A wider card grows by about a CSS pixel a frame, which the screencast + // resolves; it stays inside the viewport at its largest. + await trigger.evaluate(el => { + const host = el as HTMLElement; + (host.firstElementChild as HTMLElement).style.width = '340px'; + }); + const played = playedCurve(); + await markElement(trigger, {mode: 'outline'}); + const cast = await startScreencast(page); + const playing = driver.play(hold(center, 1100)); + // The lift spring moves the card for about 200 ms, so the block covers + // its moving part. + const [feedback] = await waitForAnimation(trigger, {minProgressMs: 16}); + const block = await blockMainThread(page, 150); + await playing; + await page.waitForTimeout(100); + const castFrames = await cast.stop(); + const tracked = await trackMarker(page, castFrames); + const proof = busyWindowProof(tracked, block, {axis: 'width'}); + // What the curve grows by between the first and the last frame of the + // judged window, in the marker's pixels, against what those frames show. + const scaleAt = (epoch: number) => played.at((epoch - feedback.from) / 1000); + const judged = tracked.filter( + f => f.box != null && f.t >= block.from + 20 && f.t <= block.to - 20, + ); + const firstFrame = judged[0]; + const lastFrame = judged.at(-1); + if (firstFrame?.box == null || lastFrame?.box == null) { + throw new Error('the screencast shows no marker during the block'); + } + const restWidth = firstFrame.box.width / scaleAt(firstFrame.t); + const expectedGrowth = + restWidth * (scaleAt(lastFrame.t) - scaleAt(firstFrame.t)); + const shownGrowth = lastFrame.box.width - firstFrame.box.width; + // Widths arrive from the screencast in steps (2 px in Chromium here). One + // step is the instrument's resolution, and the only allowance below. + const widthStep = Math.min( + ...judged.slice(1).flatMap((f, i) => { + const change = Math.abs( + (f.box?.width ?? 0) - (judged[i].box?.width ?? 0), + ); + return change > 0 ? [change] : []; + }), + ); + await writeEvidence( + 'busy-main-thread/contextmenu-press-feedback', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + block, + feedback, + proof, + frames: tracked.map(f => ({ + t: +(f.t - block.from).toFixed(1), + w: f.box?.width ?? null, + })), + }, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, castFrames, { + name: 'contextmenu-press-feedback-busy-main-thread', + zero: block.from, + from: block.from - 40, + to: block.to + 40, + columns: 8, + cellScale: 0.35, + data: t => ({w: tracked.find(f => f.t === t)?.box?.width ?? -1}), + }); + await film.write(testInfo, {block, feedback, expectedGrowth}); + // Frames kept coming at display rate and the card kept growing, as much + // as the curve says, within the screencast's resolution. + expect(proof.medianFrameMs).toBeLessThan(20); + expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2); + expect(proof.monotonic).toBe(true); + expect(proof.longestStallMs).toBeLessThan(4 * (1000 / 60) + 4); + expect(Number.isFinite(widthStep)).toBe(true); + expect(shownGrowth).toBeGreaterThanOrEqual(expectedGrowth - widthStep); +}); + +test('the press feedback does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + const {driver, center} = await openTouchStory(page); + const timeOrigin = await page.evaluate(() => performance.timeOrigin); + const trace = await traceRendering(page, async () => { + // Lifted just before the commit: the feedback alone, then its return. + await driver.play(hold(center, commitMs - 20)); + }); + const start = timeOrigin + (await touchStartedAt(page)); + const during = countBetween( + trace, + start + feedbackOnsetMs + 50, + start + commitMs - 30, + ); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); + expect(trace.longTasks).toEqual([]); +}); + /** The story with somewhere to scroll below it, and its trigger's center. */ async function openScrollableStory(page: Page) { const story = await openTouchStory(page); @@ -282,6 +880,24 @@ async function openScrollableStory(page: Page) { return {...story, center, top}; } +test('the page does not scroll under the finger that held the menu open, and it does not lock the page', async ({ + page, +}) => { + const {driver, center, top} = await openScrollableStory(page); + const before = await top(); + // Held until the menu shows, then dragged up 200 px. + await driver.play( + drag( + center, + {x: center.x, y: center.y - 200}, + {durationMs: 300, holdMs: menuDisplayMs + 50, restMs: 100}, + ), + ); + expect(await top()).toBe(before); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + expect(await page.evaluate(() => document.body.style.position)).toBe(''); +}); + test('a new finger that pans outside the open menu closes it, and the page scrolls', async ({ page, }) => { @@ -319,3 +935,67 @@ test('a new finger that pans outside the open menu closes it, and the page scrol expect(await top()).toBeLessThan(before); } }); + +test('a drag that cancels the press after the commit does not scroll the page either', async ({ + page, +}) => { + const {driver, center, top} = await openScrollableStory(page); + const before = await top(); + await driver.play( + drag( + center, + {x: center.x, y: center.y - 200}, + {durationMs: 300, holdMs: commitMs + 100, restMs: 100}, + ), + ); + expect(await menuShownAt(page)).toBeNull(); + expect(await top()).toBe(before); +}); + +test( + 'storyboard: the press feedback up to the menu', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const {driver, trigger, center} = await openTouchStory(page); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); + } + // Gate the page's timers first: the commit and the menu wait while the + // held feedback is photographed, and the finger stays down meanwhile. + await installTimerGate(page); + const playing = driver.play(hold(center, 8000)); + await waitForAnimation(trigger, {minProgressMs: 16}); + await freezeTimers(page); + const {storyboard} = await animationStoryboard(page, { + name: 'contextmenu-press-feedback', + clip: { + x: box.x - 24, + y: box.y - 24, + width: box.width + 48, + height: box.height + 48, + }, + scope: trigger, + // t counts from the visible ramp's start, the onset after the touch. + times: timeline(menuDisplayMs - feedbackOnsetMs, 1000 / 30), + measure: async () => ({ + scale: (await presentedScale(trigger)).toFixed(4), + }), + columns: 6, + cellScale: 0.6, + }); + await releaseAnimations(page); + await thawTimers(page); + await playing; + await storyboard.write(testInfo); + const scales = storyboard.frames.map(f => Number(f.data.scale)); + // The lift spring rises to its peak, overshoots by under 3% of its + // travel, and settles at the held scale before the menu displays. + const peak = scales.indexOf(Math.max(...scales)); + expect( + scales.slice(0, peak + 1).every((s, i, a) => i === 0 || s >= a[i - 1]), + ).toBe(true); + expect(scales[peak]).toBeLessThan(heldScale + (heldScale - 1) * 0.03); + expect(scales.at(-1)).toBeCloseTo(heldScale, 2); + }, +); diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index fdc7db94eb237..e78f6f4fca17d 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -9,7 +9,7 @@ * even when the timer runs late. It fails on travel past the long-press * tolerance, a lift, a second finger or the browser taking the touch. The * commit claims the finger and drops its click. A press that fails leaves - * the click alone + * the click alone. Each press it takes is reported once, at its landing * @position Unit tests of packages/core/src/ContextMenu/contextMenuPress.ts */ @@ -180,6 +180,17 @@ describe('ContextMenuPressRecognizer', () => { expect(states).toEqual(['failed@90', 'possible@90']); }); + it('reports the press it takes once, with its touch and the time it landed', () => { + const {harness, press} = setup(); + const began: [string, number][] = []; + press.onPressBegan = (touch, time) => { + began.push([touch.pointerType, time]); + }; + harness.finger(1).down(10, 20, 5, {recognizers: [press]}); + harness.finger(2).down(50, 0, 120, {recognizers: [press]}); + expect(began).toEqual([['touch', 5]]); + }); + it('keeps the press while it fails, so the feedback knows which one ended', () => { const {harness, press} = setup(); let pressAtFailure: unknown = 'unset'; diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index dfc25022eeb40..0829874683a51 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -76,6 +76,11 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { * moves freely from here. */ isMenuDue = false; + /** + * Hears each press as the recognizer takes it: the touch, and the time it + * landed on the arena's clock. + */ + onPressBegan: ((touch: GestureTouch, time: number) => void) | null = null; /** The finger the hold follows. */ private pressTouchId: number | null = null; /** Where the finger landed, while its hold runs. The drift counts from here. */ @@ -121,6 +126,7 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { this.holdFrom = {x: touch.x, y: touch.y}; this.holdStart = event.time; this.setTimer(event.time + commitMs, () => this.commit()); + this.onPressBegan?.(touch, event.time); } } diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx new file mode 100644 index 0000000000000..2a1879ca09f9c --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -0,0 +1,332 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file contextMenuPressFeedback.test.tsx + * @input useContextMenuPressFeedback on a trigger, with the animator replaced + * @output Checks that the growth starts at the press machine's "on" and + * keeps going when the machine lets the press go. It returns when + * ContextMenu's recognizer ends the press with no menu. The growth plays + * `springs.contextMenuLift`, and each return, then or as the menu closes, + * `springs.contextMenuDismiss` + * @position Unit tests of packages/core/src/ContextMenu/contextMenuPressFeedback.ts + */ + +import {render} from '@testing-library/react'; +import {useRef} from 'react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {contextMenu} from '../motion/uikit/contextMenu'; +import {springs} from '../motion/uikit/springs'; +import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; +import { + useContextMenuPressFeedback, + type ContextMenuPressFeedback, +} from './contextMenuPressFeedback'; + +const animator = vi.hoisted(() => ({ + element: null as HTMLElement | null, + /** The element each spring ran on, in order. */ + animated: [] as HTMLElement[], + play: vi.fn((..._args: unknown[]) => ({ + finished: new Promise(() => {}), + })), + animate: vi.fn((..._args: unknown[]) => ({ + finished: new Promise(() => {}), + })), + stop: vi.fn(), + dispose: vi.fn(), + get: vi.fn(() => 1), + getVelocity: vi.fn(() => 0), + reducedMotion: vi.fn(() => 'off'), +})); + +vi.mock('../motion/animator', () => ({ + createMotionEngine: (element: HTMLElement) => { + animator.element = element; + return { + ...animator, + animate: (...args: unknown[]) => { + animator.animated.push(element); + return animator.animate(...args); + }, + }; + }, +})); + +let feedback: ContextMenuPressFeedback | null = null; + +function Trigger() { + const ref = useRef(null); + feedback = useContextMenuPressFeedback(ref, true); + return
; +} + +/** What the recognizer follows now, as ContextMenu's refs report it. */ +const recognizer = {isFollowing: true, isFinger: false}; +function TriggerWithRecognizer() { + const ref = useRef(null); + const isFollowedRef = useRef(() => recognizer.isFollowing); + const landedAtRef = useRef((): number | null => null); + const followsFingerRef = useRef( + () => recognizer.isFollowing && recognizer.isFinger, + ); + feedback = useContextMenuPressFeedback( + ref, + true, + isFollowedRef, + landedAtRef, + followsFingerRef, + ); + return
; +} + +/** A trigger whose feedback can go while the trigger stays, as when it is disabled. */ +function FeedbackLayer({ + triggerRef, +}: { + triggerRef: React.RefObject; +}) { + feedback = useContextMenuPressFeedback(triggerRef, true); + return null; +} + +function TriggerWithLayer({hasLayer}: {hasLayer: boolean}) { + const ref = useRef(null); + return ( + <> +
+ {hasLayer ? : null} + + ); +} + +/** A trigger whose content is a pressable control, as a Button is. */ +function TriggerWithControl() { + const ref = useRef(null); + feedback = useContextMenuPressFeedback(ref, true); + return ( +
+ +
+ ); +} + +const nested: { + outer: ContextMenuPressFeedback | null; + inner: ContextMenuPressFeedback | null; +} = {outer: null, inner: null}; + +/** A trigger inside another trigger, beside a plain control of the outer one. */ +function NestedTriggers({isInnerShown = true}: {isInnerShown?: boolean}) { + const outerRef = useRef(null); + const innerRef = useRef(null); + nested.outer = useContextMenuPressFeedback(outerRef, true); + nested.inner = useContextMenuPressFeedback(innerRef, isInnerShown); + return ( +
+ +
+
+ ); +} + +const growths = () => + animator.animate.mock.calls.filter( + ([to]) => ((to as {scale?: number}).scale ?? 1) > 1, + ); + +/** Lets the shared mutation observer deliver its records. */ +const flush = async () => + new Promise(resolve => { + setTimeout(resolve, 0); + }); + +describe('useContextMenuPressFeedback', () => { + afterEach(() => { + vi.clearAllMocks(); + animator.animated.length = 0; + feedback = null; + }); + + it('keeps growing when the press machine lets the press go, and springs back when the recognizer ends it', async () => { + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + // The press machine's slop is shorter than the recognizer's tolerance. + trigger.removeAttribute(PRESSED_ATTRIBUTE); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + feedback?.end(performance.now()); + expect(animator.animate).toHaveBeenCalledTimes(2); + }); + + it('grows when the press machine marks a pressable control inside the trigger, the innermost surface it marks', async () => { + const {getByTestId} = render(); + getByTestId('control').setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + getByTestId('control').removeAttribute(PRESSED_ATTRIBUTE); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + }); + + it('grows only the innermost trigger when one trigger sits inside another', async () => { + const {getByTestId} = render(); + getByTestId('inner').setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animated).toEqual([getByTestId('inner')]); + getByTestId('inner').removeAttribute(PRESSED_ATTRIBUTE); + await flush(); + getByTestId('outer-control').setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animated).toEqual([ + getByTestId('inner'), + getByTestId('outer'), + ]); + }); + + it('grows no outer trigger for a press on a nested trigger that shows no growth', async () => { + const {getByTestId} = render(); + getByTestId('inner').setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animated).toEqual([]); + }); + + it('gives the trigger back its size when its feedback goes while the menu it opened is up', async () => { + const {getByTestId, rerender} = render(); + const trigger = getByTestId('trigger'); + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + // The menu opened: the animator froze the growth on the element. + feedback?.hold(); + trigger.style.scale = '1.0735'; + rerender(); + expect(trigger.style.scale).toBe(''); + expect(animator.dispose).toHaveBeenCalledOnce(); + }); + + it('grows toward the held scale on springs.contextMenuLift, from the onset', async () => { + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + const [to, transition, options] = animator.animate.mock + .lastCall as unknown as [ + {scale: number}, + {spring: unknown}, + {at: number}, + ]; + expect(to).toEqual({scale: contextMenu.press.heldScale}); + expect(transition).toEqual({spring: springs.contextMenuLift}); + expect(typeof options.at).toBe('number'); + expect(animator.play).not.toHaveBeenCalled(); + }); + + it('returns on springs.contextMenuDismiss, at the time the recognizer ended the press', async () => { + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + feedback?.end(1000); + expect(animator.animate.mock.lastCall).toEqual([ + {scale: 1}, + {spring: springs.contextMenuDismiss}, + {at: 1000}, + ]); + expect(animator.play).not.toHaveBeenCalled(); + }); + + it('grows a finger at its onset, 150 ms after the landing the recognizer reports', async () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + const {getByTestId} = render(); + vi.advanceTimersByTime(1000); + // The recognizer reports the landing 40 ms late, on a busy main thread. + const landedAt = performance.now() - 40; + feedback?.begin(landedAt, getByTestId('trigger')); + await vi.advanceTimersByTimeAsync(109); + expect(growths()).toHaveLength(0); + await vi.advanceTimersByTimeAsync(1); + expect(growths().map(call => (call[2] as {at: number}).at)).toEqual([ + landedAt + 150, + ]); + } finally { + vi.useRealTimers(); + } + }); + + it('keeps a finger’s onset when the press machine marks the press later', async () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + recognizer.isFinger = true; + const {getByTestId} = render(); + vi.advanceTimersByTime(1000); + const landedAt = performance.now(); + feedback?.begin(landedAt, getByTestId('trigger')); + await vi.advanceTimersByTimeAsync(240); + getByTestId('trigger').setAttribute(PRESSED_ATTRIBUTE, 'on'); + await vi.advanceTimersByTimeAsync(200); + expect(growths().map(call => (call[2] as {at: number}).at)).toEqual([ + landedAt + 150, + ]); + } finally { + recognizer.isFinger = false; + vi.useRealTimers(); + } + }); + + it('starts a pen’s growth at its mark after a finger’s press ended', async () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + recognizer.isFinger = true; + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + feedback?.begin(performance.now(), trigger); + await vi.advanceTimersByTimeAsync(150); + expect(growths()).toHaveLength(1); + feedback?.end(performance.now()); + // A pen's press: the press machine's mark starts its growth. + recognizer.isFinger = false; + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await vi.advanceTimersByTimeAsync(0); + expect(growths()).toHaveLength(2); + } finally { + recognizer.isFinger = false; + vi.useRealTimers(); + } + }); + + it('grows only the innermost trigger for a finger the recognizer reports on a nested trigger', async () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + const {getByTestId} = render(); + const inner = getByTestId('inner'); + nested.outer?.begin(performance.now(), inner); + nested.inner?.begin(performance.now(), inner); + await vi.advanceTimersByTimeAsync(150); + expect(animator.animated).toEqual([inner]); + } finally { + vi.useRealTimers(); + } + }); + + it('returns on springs.contextMenuDismiss when the menu the press opened closes', async () => { + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + await flush(); + feedback?.hold(); + feedback?.release(); + expect(animator.animate.mock.lastCall).toEqual([ + {scale: 1}, + {spring: springs.contextMenuDismiss}, + ]); + expect(animator.play).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts new file mode 100644 index 0000000000000..f9e808c1a6217 --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -0,0 +1,317 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file contextMenuPressFeedback.ts + * @input UIKit's context-menu springs, the context-menu constants, the + * compositor animator, the presses ContextMenu's recognizer takes, and the + * press state core's press machine writes + * @output useContextMenuPressFeedback: hold and release, from ContextMenu's + * menu; the growth follows the recognizer's finger, or a pen's press mark + * @position The press feedback of ContextMenu's touch invocation + * + * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx + */ + +// The growth starts at the onset, 150 ms after a finger lands, while the +// recognizer follows that finger. The recognizer reports the landing; a +// pointer-only pen's press waits for the press machine's "on". Only the +// recognizer's failure or cancel returns it. A long press is a gesture, so the +// growth plays UIKit's lift spring and each return its dismissal spring. The +// compositor plays them, so a busy main thread does not stall them. Once the +// menu opens, the trigger holds its size until the menu closes. Then it returns +// on the dismissal spring. An inline trigger and Reduce Motion show no growth. + +import {useCallback, useRef, type RefObject} from 'react'; +import {useAttachment} from '../hooks/useAttachment'; +import {usePressFeedback} from '../hooks/usePressFeedback'; +import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; +import {PRESS_ONSET_MS} from '../utils/pressGesture'; +import {observeMutations} from '../utils/sharedMutationObserver'; +import {createMotionEngine, type Animator} from '../motion/animator'; +import {contextMenu} from '../motion/uikit/contextMenu'; +import { + CONTEXT_MENU_DISMISS_SPRING, + CONTEXT_MENU_LIFT_SPRING, +} from '../motion/uikit/springs'; + +const {heldScale} = contextMenu.press; + +export interface ContextMenuPressFeedback { + /** + * The recognizer took a finger that landed at `landedAt` on `target`: grow + * at its onset, 150 ms later. + */ + begin(landedAt: number, target: Element | null): void; + /** The menu the press opened closed: return on the dismissal spring. */ + release(): void; + /** + * The recognizer ended the press with no menu, at `time`: return on the + * dismissal spring. + */ + end(time: number): void; + /** + * The menu showed: the feedback stops where it is. The menu's cursor anchor + * sits inside the trigger, and anchor positioning follows its transformed + * box. So a trigger that still grows would carry the open menu with it. + */ + hold(): void; +} + +/** A press feedback with no recognizer to ask grows at every "on". */ +const ALWAYS_FOLLOWED: RefObject<() => boolean> = {current: () => true}; + +/** With no recognizer to ask, the onset is the "on" itself. */ +const NO_LANDING: RefObject<() => number | null> = {current: () => null}; + +/** With no recognizer to ask, every "on" is a pen's. */ +const NO_FINGER: RefObject<() => boolean> = {current: () => false}; + +// The triggers a press mark belongs to: every mounted trigger, whether it +// shows growth or not. A mark inside a trigger belongs to the nearest of them +// at or above it. So a press on a nested trigger grows no outer trigger. +const pressMarkOwners = new WeakSet(); + +function pressMarkOwnerOf(marked: Element): Element | null { + for ( + let node: Element | null = marked; + node != null; + node = node.parentElement + ) { + if (pressMarkOwners.has(node)) { + return node; + } + } + return null; +} + +/** + * The press feedback of a ContextMenu trigger. `isShown` is read at each + * press: false for an inline trigger. It follows the element behind + * `triggerRef`, so a replaced trigger (`triggerAs`) is followed too. The + * `isFollowed` ref says whether ContextMenu's recognizer follows a finger or + * a pen now: the growth starts only then. The `landedAt` ref gives the time + * that finger landed, so the growth starts at its onset. The `followsFinger` + * ref says whether that contact is a finger, whose onset `begin` sets. + */ +export function useContextMenuPressFeedback( + triggerRef: RefObject, + isShown: boolean, + isFollowed: RefObject<() => boolean> = ALWAYS_FOLLOWED, + landedAt: RefObject<() => number | null> = NO_LANDING, + followsFinger: RefObject<() => boolean> = NO_FINGER, +): ContextMenuPressFeedback { + // The press machine's document listener, while this feedback is mounted. + usePressFeedback(); + const animatorRef = useRef(null); + const isShownRef = useRef(isShown); + isShownRef.current = isShown; + // Whether the trigger carries a scale of ours (to put back and clear). + const isGrownRef = useRef(false); + // The menu the press opened is up: the growth holds until it closes. + const isHeldRef = useRef(false); + // Null while no shown trigger is attached, so `begin` grows nothing. + const fingerOnsetRef = useRef< + ((landedAt: number, target: Element | null) => void) | null + >(null); + + // The compositor animator lives with the trigger it follows. A replaced + // trigger, or a feedback that goes while the trigger stays, takes the + // animation and the scale of ours with it. + useAttachment( + triggerRef, + element => () => { + animatorRef.current?.dispose(); + animatorRef.current = null; + if (isGrownRef.current) { + isGrownRef.current = false; + element.style.removeProperty('scale'); + } + }, + null, + ); + + const animatorFor = useCallback((): Animator | null => { + const element = triggerRef.current; + if (element == null) { + return null; + } + animatorRef.current ??= createMotionEngine(element); + return animatorRef.current; + }, [triggerRef]); + + // Back at 1: drop the inline scale, which would otherwise leave the trigger + // a stacking context and a containing block for fixed descendants. + const settleBack = useCallback((finished: Promise) => { + void finished.then(isDone => { + const element = animatorRef.current?.element; + if (isDone && element != null && isGrownRef.current) { + isGrownRef.current = false; + element.style.removeProperty('scale'); + } + }); + }, []); + + const start = useCallback( + (time: number) => { + if (!isShownRef.current || isHeldRef.current || !isFollowed.current()) { + return; + } + const animator = animatorFor(); + const element = animator?.element; + // Under Reduce Motion the view does not grow (UIKit's + // `reducedMotionFeedback`), and no fade stands in for it. + if ( + animator == null || + element == null || + (animator.reducedMotion() !== 'off' && + !contextMenu.reducedMotionFeedback) + ) { + return; + } + isGrownRef.current = true; + // `time` is the onset: 150 ms after the finger lands, or a later mark. + animator.animate( + {scale: heldScale}, + {spring: CONTEXT_MENU_LIFT_SPRING}, + {at: time}, + ); + }, + [animatorFor, isFollowed], + ); + + const end = useCallback( + (time: number) => { + const animator = animatorRef.current; + const element = animator?.element; + if ( + animator == null || + element == null || + !isGrownRef.current || + isHeldRef.current + ) { + return; + } + settleBack( + animator.animate( + {scale: 1}, + {spring: CONTEXT_MENU_DISMISS_SPRING}, + {at: time}, + ).finished, + ); + }, + [settleBack], + ); + + const release = useCallback(() => { + isHeldRef.current = false; + const animator = animatorRef.current; + const element = animator?.element; + if (animator == null || element == null || !isGrownRef.current) { + return; + } + settleBack( + animator.animate({scale: 1}, {spring: CONTEXT_MENU_DISMISS_SPRING}) + .finished, + ); + }, [settleBack]); + + const begin = useCallback((landed: number, target: Element | null) => { + fingerOnsetRef.current?.(landed, target); + }, []); + + const hold = useCallback(() => { + isHeldRef.current = true; + if (isGrownRef.current) { + animatorRef.current?.stop(['scale']); + } + }, []); + + // Grow at the onset, 150 ms after the finger lands. The recognizer reports + // the landing as it takes the finger, whether or not the press machine + // marks the press. Inside a scroll view the machine marks late, and it never + // marks a press that travels past 10 px first. A pen's onset waits for the + // mark. The machine marks the innermost pressable surface, so a control + // inside the trigger can carry the mark. Only the recognizer ends the growth + // (`end`). + useAttachment( + triggerRef, + element => { + pressMarkOwners.add(element); + if (!isShown) { + return () => { + pressMarkOwners.delete(element); + }; + } + const isMarkedOn = () => + element.getAttribute(PRESSED_ATTRIBUTE) === 'on' || + [...element.querySelectorAll(`[${PRESSED_ATTRIBUTE}="on"]`)].some( + marked => pressMarkOwnerOf(marked) === element, + ); + let isPressed = isMarkedOn(); + let markedAt = 0; + let onsetTimer: ReturnType | undefined; + const startAt = (onsetAt: number) => { + const wait = onsetAt - performance.now(); + if (wait > 0) { + onsetTimer = setTimeout(() => start(onsetAt), wait); + } else { + start(onsetAt); + } + }; + // A pen's mark: the gesture host took that pen from the same input + // before the mark's record comes, so the recognizer follows it already. + const growAtMark = () => { + // The recognizer times a finger's onset from its landing. + if (followsFinger.current() || !isFollowed.current()) { + return; + } + const landed = landedAt.current(); + startAt( + landed == null + ? markedAt + : Math.max(markedAt, landed + PRESS_ONSET_MS), + ); + }; + fingerOnsetRef.current = (landed, target) => { + // A finger on a nested trigger grows only that trigger. + if (target != null && pressMarkOwnerOf(target) !== element) { + return; + } + clearTimeout(onsetTimer); + startAt(landed + PRESS_ONSET_MS); + }; + const stopObserving = observeMutations( + element, + {attributes: true, attributeFilter: [PRESSED_ATTRIBUTE], subtree: true}, + () => { + const next = isMarkedOn(); + if (next !== isPressed) { + isPressed = next; + if (next) { + if (!followsFinger.current()) { + clearTimeout(onsetTimer); + markedAt = performance.now(); + growAtMark(); + } + } else if (!isFollowed.current()) { + // A finger the recognizer still follows keeps its onset, past + // the machine's shorter travel. + clearTimeout(onsetTimer); + } + } + }, + ); + return () => { + clearTimeout(onsetTimer); + stopObserving(); + fingerOnsetRef.current = null; + pressMarkOwners.delete(element); + }; + }, + isShown, + ); + + return {begin, release, end, hold}; +} diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index c739deaa6c701..a5c31c92649d6 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -18,7 +18,7 @@ roles through `resolveMotion`. | `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. | | `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, `delaysContentTouches`, scroll to top. | | `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. | -| `uikit/contextMenu.ts` | UIContextMenuInteraction: touch timeline (feedback, commit, menu), drift tolerance, commit haptic. | +| `uikit/contextMenu.ts` | UIContextMenuInteraction: touch timeline (feedback, commit, menu), drift tolerance, the press feedback's held scale, commit haptic. | | `uikit/paging.ts` | A paging UIScrollView: the integrator that settles a release on its page, the page rule, the catch, `setContentOffset(animated:)`. | | `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | diff --git a/packages/core/src/motion/uikit/contextMenu.ts b/packages/core/src/motion/uikit/contextMenu.ts index a6c168b433270..7d7743e20b664 100644 --- a/packages/core/src/motion/uikit/contextMenu.ts +++ b/packages/core/src/motion/uikit/contextMenu.ts @@ -4,12 +4,13 @@ * @file contextMenu.ts * @input Measurements of UIContextMenuInteraction on iOS 26.2 * @output `contextMenu`: UIContextMenuInteraction's touch timeline, drift - * tolerance and commit haptic + * tolerance, held scale and commit haptic * @position The context-menu domain of the UIKit constants table. Only * ContextMenu's own modules import it. The table's barrel does not * re-export it. * - * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md and + * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md, + * /packages/core/src/ContextMenu/contextMenuPressFeedback.ts and * /packages/core/src/ContextMenu/contextMenuPress.ts */ @@ -76,6 +77,18 @@ export const contextMenu = { * 0.5 s displayed at the lift (529 ms) */ menuDisplayMs: 735, + /** + * The size the press copy reaches when the menu displays, as a fraction + * of the view. It is the second ramp at `menuDisplayMs`: 1 + 0.1 per + * second since the touch. The trigger grows toward it on + * `springs.contextMenuLift`, not on UIKit's ramp. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, per-frame model frames of the press platter over a + * 200 × 120 pt view, Oct 23 2026: 0.1001 per second, linear over 19 + * frames, zero at the touch (−1.4 ms), at 735 ms + * @measure M-CM2 + */ + heldScale: 1.0735, }, /** * The click haptic at the commit, as a vibration where that is the only @@ -91,4 +104,14 @@ export const contextMenu = { * @measure M-CM5 */ commitHaptic: 'impactMedium', + /** + * Reduce Motion: whether the press feedback still grows the view. It does + * not; only the copy's shadow fades in, and the haptic and the menu stay. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, per-frame platter frames with Reduce Motion on, Prefer + * Cross-Fade off and on, Oct 23 2026: the platter stays at scale 1 and + * opacity 1 through the hold while its shadow opacity rises 0 → 0.31 by + * 0.6 s; a press lifted at 0.25 s does not grow either + */ + reducedMotionFeedback: false, } as const; diff --git a/packages/core/src/utils/pressableCoverage.test.ts b/packages/core/src/utils/pressableCoverage.test.ts index c4b2c88b0c5ba..d610665016df5 100644 --- a/packages/core/src/utils/pressableCoverage.test.ts +++ b/packages/core/src/utils/pressableCoverage.test.ts @@ -15,7 +15,10 @@ * holds it equal to the marked set: * * - A file paints a press when its StyleX carries an `':active` key, a - * `[data-astryx-press` arm, or composes `interactionOverlayStyles`. + * `[data-astryx-press` arm, or composes `interactionOverlayStyles`. It + * also paints one when its script follows the pressed state that a + * controller writes, as ContextMenu's growth does. A script that also + * writes that state is a press controller, so it is part of the model. * - A file is marked when it calls `usePressFeedback(`. * - A file whose press arms are read off an ancestor scope marker * (`stylex.when.ancestor(':active', someScope)`, the way an indicator @@ -71,6 +74,13 @@ const source = new Map( // a bare attribute selector or inside `:is(…)`. const PRESS_ARM = /':active|'(?::is\()?\[data-astryx-press=|interactionOverlayStyles\./; +function paintsPress(text: string): boolean { + return ( + PRESS_ARM.test(text) || + (text.includes('getAttribute(PRESSED_ATTRIBUTE)') && + !text.includes('setAttribute(PRESSED_ATTRIBUTE')) + ); +} const ANCESTOR_ARM = /stylex\.when\.ancestor\(\s*'(?::active|\[data-astryx-press=[^)]*)',\s*(\w+)\s*,?\s*\)/g; @@ -143,7 +153,7 @@ function importers(file: string): string[] { } const pressArmFiles = [...source.entries()] - .filter(([file, text]) => !MODEL_FILES.has(file) && PRESS_ARM.test(text)) + .filter(([file, text]) => !MODEL_FILES.has(file) && paintsPress(text)) .map(([file]) => file) .sort(); @@ -227,7 +237,7 @@ describe('every surface that paints a press is reachable by the touch press cont ); const unexplained = marked.filter(file => { const text = source.get(file) ?? ''; - if (PRESS_ARM.test(text)) { + if (paintsPress(text)) { return false; } return ![...scopeNames].some(scope => From 7f9d428f31937808390de8659a7202f9d2d15ac6 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 009/151] test(ContextMenu): each animation hold names the motion it judges main's hold now rejects a hold that names no judged motion. The curve and storyboard proofs judge the trigger's scale, so they say so. --- .../ContextMenuLongPress.interaction.browser.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index b83c187617373..f237674bbeed4 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -682,7 +682,9 @@ test('the press feedback plays its computed curve on the compositor, frame by fr const played = playedCurve(); const playing = driver.play(hold(center, commitMs + 300)); await waitForAnimation(trigger, {minProgressMs: 16}); - await holdAnimations(page, trigger); + await holdAnimations(page, trigger, { + judges: {target: trigger, property: 'scale'}, + }); // Seek the held curve (its time 0 is the onset after the touch) to every // 60 Hz frame and read the presented scale. const samples = await trigger.evaluate((element, times) => { @@ -976,6 +978,7 @@ test( height: box.height + 48, }, scope: trigger, + judges: {target: trigger, property: 'scale'}, // t counts from the visible ramp's start, the onset after the touch. times: timeline(menuDisplayMs - feedbackOnsetMs, 1000 / 30), measure: async () => ({ From 791357ddfaaf6364f63e96da0b05a59e8dc88157 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 010/151] test(ContextMenu): a late touch grows from rest at its onset (red) A touch that reaches the page 90 ms after its timestamp waits for Chromium's timer hold, so the growth starts about 50 ms late, and its back-dated curve skips its first frames. The proof wants the frame before the growth at rest, the first grown frame no further along than the spring one frame in, and that frame within two frames of the onset. --- ...tMenuLongPress.interaction.browser.spec.ts | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index f237674bbeed4..87bbbbb8c2c2f 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -675,6 +675,95 @@ test('a drift within the tolerance still opens the menu; past it on one axis can expect(await menuShownAt(page)).toBeNull(); }); +test('a touch that reaches the page late grows from the first frame at its onset, from rest', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + test.skip( + !driver.scriptedTimestamps, + 'only a Chromium touch takes its timestamp from the script', + ); + const played = playedCurve(); + await page.evaluate(() => { + const trigger = document.querySelector( + '[data-testid="touch-context-menu"]', + ); + const record = { + touchedAt: 0, + handledAt: 0, + frames: [] as {t: number; scale: number}[], + }; + (window as unknown as {__lateTouch: typeof record}).__lateTouch = record; + const sample = (t: number) => { + const scale = getComputedStyle(trigger as HTMLElement).scale; + record.frames.push({ + t, + scale: scale === 'none' ? 1 : Number.parseFloat(scale), + }); + if (t - record.touchedAt < 320) { + requestAnimationFrame(sample); + } + }; + addEventListener( + 'touchstart', + event => { + record.touchedAt = event.timeStamp; + record.handledAt = performance.now(); + // Added during the dispatch, it runs after the page's own touchstart + // listeners. So each frame, the sampler reads after the page's work. + addEventListener('touchstart', () => requestAnimationFrame(sample), { + once: true, + passive: true, + }); + }, + {capture: true, once: true, passive: true}, + ); + }); + const cdp = await page.context().newCDPSession(page); + // The touch reaches the page 90 ms after its own timestamp, as through a + // slow input path. Chromium then holds the page's timers until about + // 100 ms after it handles the touch. + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [{...center, id: 1, radiusX: 1, radiusY: 1, force: 1}], + timestamp: (Date.now() - 90) / 1000, + }); + await page.waitForTimeout(250); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + timestamp: Date.now() / 1000, + }); + const {touchedAt, handledAt, frames} = await page.evaluate( + () => + ( + window as unknown as { + __lateTouch: { + touchedAt: number; + handledAt: number; + frames: {t: number; scale: number}[]; + }; + } + ).__lateTouch, + ); + expect(handledAt - touchedAt).toBeGreaterThanOrEqual(80); + const grown = frames.findIndex(frame => frame.scale > 1); + expect(grown, 'the trigger never grew').toBeGreaterThan(0); + const before = frames[grown - 1]; + const first = frames[grown]; + const frameMs = first.t - before.t; + // From rest: the frame before is at rest, and the first grown frame is no + // further along than the spring one frame in. + expect(before.scale).toBe(1); + expect(first.scale).toBeLessThanOrEqual(played.at(frameMs / 1000) + 0.0005); + // On time: the curve starts in the first frame at or after the onset. So + // its first grown frame comes within two frames of the onset. + expect(before.t - touchedAt).toBeGreaterThanOrEqual(feedbackOnsetMs); + expect(first.t - touchedAt).toBeLessThanOrEqual( + feedbackOnsetMs + 2 * frameMs + 1, + ); +}); + test('the press feedback plays its computed curve on the compositor, frame by frame', async ({ page, }, testInfo) => { From 6fd83b267732257cde29f694ff54ee3ab8aec0fc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 011/151] fix(ContextMenu): a frame, not a timer, starts the touch growth Chromium holds every timer for about 100 ms after it handles a touchstart, so a touch that reached the page late grew late, and its back-dated curve skipped its first frames. The first frame at or after the onset now starts the spring from rest. The motion engine is built in the first frame after the finger lands, not in its touchstart handler. A lift, a move past the tolerance, a cancel and the menu's display stop the frame watch. --- .../ContextMenuTouchGrowth.test.tsx | 108 +++++++++++++++--- .../contextMenuPressFeedback.test.tsx | 91 ++++++++++++--- .../ContextMenu/contextMenuPressFeedback.ts | 82 +++++++++---- 3 files changed, 231 insertions(+), 50 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index e6aea9a540b25..307a5479f6ab3 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -55,7 +55,7 @@ interface Contact { } function dispatchTouch( - type: 'touchstart' | 'touchmove' | 'touchend', + type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel', target: EventTarget, changed: Contact[], all: Contact[], @@ -78,6 +78,10 @@ const advance = (ms: number) => vi.advanceTimersByTime(ms); }); +// Fake animation frames come every 16 ms. The growth starts in the first one +// at or after its onset. +const FRAME_MS = 16; + /** The press machine's "on", as core's press machine writes it. */ async function pressMachineOn(trigger: HTMLElement) { trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); @@ -148,7 +152,7 @@ describe('ContextMenu’s growth under a finger', () => { const trigger = renderMenu(); const contact = {id: 1, x: 20, y: 20}; dispatchTouch('touchstart', trigger, [contact], [contact]); - advance(150); + advance(150 + FRAME_MS); await pressMachineOn(trigger); expect(growths(trigger)).toHaveLength(1); advance(100); @@ -162,6 +166,16 @@ describe('ContextMenu’s growth under a finger', () => { element === trigger && ((to as {scale?: number}).scale ?? 1) > 1, ); const startOf = (call: unknown[]) => (call[3] as {at: number}).at; + // One growth, started from rest in the first frame at or after the onset. + const expectGrowthFromOnsetFrame = ( + trigger: HTMLElement, + landedAt: number, + ) => { + const starts = growths(trigger).map(startOf); + expect(starts).toHaveLength(1); + expect(starts[0]).toBeGreaterThanOrEqual(landedAt + 150); + expect(starts[0]).toBeLessThan(landedAt + 150 + FRAME_MS); + }; it('starts the growth at the onset, 150 ms after the finger lands, when the press machine marks the press as the finger lands', async () => { const trigger = renderMenu(); @@ -172,8 +186,8 @@ describe('ContextMenu’s growth under a finger', () => { await pressMachineOn(trigger); advance(149); expect(growths(trigger)).toHaveLength(0); - advance(1); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(1 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); }); it('grows the trigger at the onset when the press machine marks the press before the recognizer has the finger', async () => { @@ -184,8 +198,8 @@ describe('ContextMenu’s growth under a finger', () => { await pressMachineOn(trigger); const landedAt = performance.now(); dispatchTouch('touchstart', trigger, [contact], [contact]); - advance(150); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(150 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); }); it('still grows at the onset after a drift past the press machine’s 10 px that the recognizer’s 11.5 px tolerance still follows', async () => { @@ -199,8 +213,8 @@ describe('ContextMenu’s growth under a finger', () => { const drifted = {...contact, x: 31}; dispatchTouch('touchmove', trigger, [drifted], [drifted]); await pressMachineOff(trigger); - advance(90); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(90 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); }); it('grows at the onset after a drift the press machine never marks, as inside a scroll view, that the recognizer still follows', async () => { @@ -213,8 +227,8 @@ describe('ContextMenu’s growth under a finger', () => { // marks the press, and inside the recognizer's 11.5 px. const drifted = {...contact, x: 28, y: 28}; dispatchTouch('touchmove', trigger, [drifted], [drifted]); - advance(90); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(90 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); }); it('grows at the onset, 150 ms after the finger lands, even when the press machine marks the press later', async () => { @@ -222,8 +236,8 @@ describe('ContextMenu’s growth under a finger', () => { const contact = {id: 1, x: 20, y: 20}; const landedAt = performance.now(); dispatchTouch('touchstart', trigger, [contact], [contact]); - advance(150); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(150 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); // Inside a scroll view the machine's own timer marks it later. advance(90); await pressMachineOn(trigger); @@ -250,10 +264,76 @@ describe('ContextMenu’s growth under a finger', () => { expect(trigger.getAttribute(PRESSED_ATTRIBUTE)).toBe('on'); advance(149); expect(growths(trigger)).toHaveLength(0); - advance(1); - expect(growths(trigger).map(startOf)).toEqual([landedAt + 150]); + advance(1 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); + }); + + it('builds the motion engine in the first frame after the finger lands, not in its touchstart handler', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + dispatchTouch('touchstart', trigger, [contact], [contact]); + expect(animator.elements).not.toContain(trigger); + advance(FRAME_MS); + expect(animator.elements).toContain(trigger); + expect(growths(trigger)).toHaveLength(0); }); + it('shows nothing for a quick tap: no animation and no inline style', async () => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + const style = trigger.getAttribute('style'); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(40); + dispatchTouch('touchend', trigger, [contact], []); + advance(400); + expect(animator.animate).not.toHaveBeenCalled(); + expect(animator.play).not.toHaveBeenCalled(); + expect(trigger.getAttribute('style')).toBe(style); + }); + + it.each([ + [ + 'the finger lifts', + (trigger: HTMLElement, contact: Contact) => + dispatchTouch('touchend', trigger, [contact], []), + ], + [ + 'the finger moves past the hold’s tolerance', + (trigger: HTMLElement, contact: Contact) => { + const moved = {...contact, x: contact.x + 20}; + dispatchTouch('touchmove', trigger, [moved], [moved]); + }, + ], + [ + 'the browser cancels the touch', + (trigger: HTMLElement, contact: Contact) => + dispatchTouch('touchcancel', trigger, [contact], [contact]), + ], + ])( + 'stops watching frames for the onset when %s before it', + async (_, stop) => { + const trigger = renderMenu(); + const contact = {id: 1, x: 20, y: 20}; + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(60); + const frames = vi.spyOn(window, 'requestAnimationFrame'); + const cancels = vi.spyOn(window, 'cancelAnimationFrame'); + try { + stop(trigger, contact); + expect(cancels).toHaveBeenCalled(); + advance(200); + // The onset's watch asks for no frame after it stops. + expect( + frames.mock.calls.filter(([callback]) => callback.name === 'look'), + ).toEqual([]); + expect(growths(trigger)).toHaveLength(0); + } finally { + frames.mockRestore(); + cancels.mockRestore(); + } + }, + ); + it('does not grow the trigger for a press its recognizer does not follow, such as a mouse', async () => { const trigger = renderMenu(); await pressMachineOn(trigger); diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx index 2a1879ca09f9c..10f4830f570e2 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -139,15 +139,39 @@ const growths = () => ); /** Lets the shared mutation observer deliver its records. */ +// The growth starts in the next animation frame. const flush = async () => new Promise(resolve => { - setTimeout(resolve, 0); + requestAnimationFrame(() => { + setTimeout(resolve, 0); + }); }); +// Fake animation frames come every 16 ms. +const FRAME_MS = 16; +const FAKE_TIMERS = { + toFake: [ + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + ] as const, +}; +const startsOf = () => growths().map(call => (call[2] as {at: number}).at); +// One growth, started from rest in the first frame at or after the onset. +const expectGrowthFromOnsetFrame = (onsetAt: number) => { + const starts = startsOf(); + expect(starts).toHaveLength(1); + expect(starts[0]).toBeGreaterThanOrEqual(onsetAt); + expect(starts[0]).toBeLessThan(onsetAt + FRAME_MS); +}; + describe('useContextMenuPressFeedback', () => { afterEach(() => { vi.clearAllMocks(); animator.animated.length = 0; + animator.element = null; feedback = null; }); @@ -243,7 +267,7 @@ describe('useContextMenuPressFeedback', () => { }); it('grows a finger at its onset, 150 ms after the landing the recognizer reports', async () => { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); try { const {getByTestId} = render(); vi.advanceTimersByTime(1000); @@ -252,17 +276,15 @@ describe('useContextMenuPressFeedback', () => { feedback?.begin(landedAt, getByTestId('trigger')); await vi.advanceTimersByTimeAsync(109); expect(growths()).toHaveLength(0); - await vi.advanceTimersByTimeAsync(1); - expect(growths().map(call => (call[2] as {at: number}).at)).toEqual([ - landedAt + 150, - ]); + await vi.advanceTimersByTimeAsync(1 + FRAME_MS); + expectGrowthFromOnsetFrame(landedAt + 150); } finally { vi.useRealTimers(); } }); it('keeps a finger’s onset when the press machine marks the press later', async () => { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); try { recognizer.isFinger = true; const {getByTestId} = render(); @@ -272,9 +294,7 @@ describe('useContextMenuPressFeedback', () => { await vi.advanceTimersByTimeAsync(240); getByTestId('trigger').setAttribute(PRESSED_ATTRIBUTE, 'on'); await vi.advanceTimersByTimeAsync(200); - expect(growths().map(call => (call[2] as {at: number}).at)).toEqual([ - landedAt + 150, - ]); + expectGrowthFromOnsetFrame(landedAt + 150); } finally { recognizer.isFinger = false; vi.useRealTimers(); @@ -282,19 +302,19 @@ describe('useContextMenuPressFeedback', () => { }); it('starts a pen’s growth at its mark after a finger’s press ended', async () => { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); try { recognizer.isFinger = true; const {getByTestId} = render(); const trigger = getByTestId('trigger'); feedback?.begin(performance.now(), trigger); - await vi.advanceTimersByTimeAsync(150); + await vi.advanceTimersByTimeAsync(150 + FRAME_MS); expect(growths()).toHaveLength(1); feedback?.end(performance.now()); // A pen's press: the press machine's mark starts its growth. recognizer.isFinger = false; trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); - await vi.advanceTimersByTimeAsync(0); + await vi.advanceTimersByTimeAsync(FRAME_MS); expect(growths()).toHaveLength(2); } finally { recognizer.isFinger = false; @@ -303,19 +323,60 @@ describe('useContextMenuPressFeedback', () => { }); it('grows only the innermost trigger for a finger the recognizer reports on a nested trigger', async () => { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); try { const {getByTestId} = render(); const inner = getByTestId('inner'); nested.outer?.begin(performance.now(), inner); nested.inner?.begin(performance.now(), inner); - await vi.advanceTimersByTimeAsync(150); + await vi.advanceTimersByTimeAsync(150 + FRAME_MS); expect(animator.animated).toEqual([inner]); } finally { vi.useRealTimers(); } }); + it('builds the motion engine in the first frame after the landing, before the onset', async () => { + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); + try { + const {getByTestId} = render(); + const trigger = getByTestId('trigger'); + feedback?.begin(performance.now(), trigger); + expect(animator.element).toBeNull(); + await vi.advanceTimersByTimeAsync(FRAME_MS); + expect(animator.element).toBe(trigger); + expect(growths()).toHaveLength(0); + } finally { + vi.useRealTimers(); + } + }); + + it.each([ + ['the recognizer ends the press', () => feedback?.end(performance.now())], + ['the menu shows', () => feedback?.hold()], + ])( + 'stops watching frames for the onset when %s before it', + async (_, stop) => { + vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); + try { + const {getByTestId} = render(); + feedback?.begin(performance.now(), getByTestId('trigger')); + await vi.advanceTimersByTimeAsync(60); + const frames = vi.spyOn(window, 'requestAnimationFrame'); + try { + stop(); + await vi.advanceTimersByTimeAsync(200); + expect(frames).not.toHaveBeenCalled(); + expect(growths()).toHaveLength(0); + } finally { + frames.mockRestore(); + } + } finally { + vi.useRealTimers(); + } + }, + ); + it('returns on springs.contextMenuDismiss when the menu the press opened closes', async () => { const {getByTestId} = render(); const trigger = getByTestId('trigger'); diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index f9e808c1a6217..9e591e59b10a5 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -14,10 +14,12 @@ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx */ -// The growth starts at the onset, 150 ms after a finger lands, while the -// recognizer follows that finger. The recognizer reports the landing; a -// pointer-only pen's press waits for the press machine's "on". Only the -// recognizer's failure or cancel returns it. A long press is a gesture, so the +// The growth starts in the first frame at or after the onset, 150 ms after a +// finger lands, while the recognizer follows that finger. It plays its whole +// spring from rest, from that frame, as Core Animation starts an animation at +// its commit. The recognizer reports the landing; a pointer-only pen's press +// waits for the press machine's "on". Only the recognizer's failure or cancel +// returns it. A long press is a gesture, so the // growth plays UIKit's lift spring and each return its dismissal spring. The // compositor plays them, so a busy main thread does not stall them. Once the // menu opens, the trigger holds its size until the menu closes. Then it returns @@ -41,14 +43,14 @@ const {heldScale} = contextMenu.press; export interface ContextMenuPressFeedback { /** * The recognizer took a finger that landed at `landedAt` on `target`: grow - * at its onset, 150 ms later. + * from the first frame at or after its onset, 150 ms later. */ begin(landedAt: number, target: Element | null): void; /** The menu the press opened closed: return on the dismissal spring. */ release(): void; /** * The recognizer ended the press with no menu, at `time`: return on the - * dismissal spring. + * dismissal spring. A growth still to come does not start. */ end(time: number): void; /** @@ -73,6 +75,32 @@ const NO_FINGER: RefObject<() => boolean> = {current: () => false}; // at or above it. So a press on a nested trigger grows no outer trigger. const pressMarkOwners = new WeakSet(); +/** + * Calls `onDue` in the first animation frame that runs at or after `dueAt`, on + * the event clock, with the time its callback runs. `onWait` runs in each frame + * before it. It reads only the clock. A frame comes on time where a timer does + * not: Chromium holds the page's timers for about 100 ms after it handles a + * touchstart. Returns the function that stops it. + */ +function watchFramesFrom( + dueAt: number, + onWait: () => void, + onDue: (time: number) => void, +): () => void { + let frame = requestAnimationFrame(function look() { + const time = performance.now(); + if (time >= dueAt) { + onDue(time); + return; + } + onWait(); + frame = requestAnimationFrame(look); + }); + return () => { + cancelAnimationFrame(frame); + }; +} + function pressMarkOwnerOf(marked: Element): Element | null { for ( let node: Element | null = marked; @@ -115,6 +143,12 @@ export function useContextMenuPressFeedback( const fingerOnsetRef = useRef< ((landedAt: number, target: Element | null) => void) | null >(null); + // Stops the frame watch of a growth still to come. + const stopOnsetRef = useRef<(() => void) | null>(null); + const stopOnset = useCallback(() => { + stopOnsetRef.current?.(); + stopOnsetRef.current = null; + }, []); // The compositor animator lives with the trigger it follows. A replaced // trigger, or a feedback that goes while the trigger stays, takes the @@ -171,7 +205,8 @@ export function useContextMenuPressFeedback( return; } isGrownRef.current = true; - // `time` is the onset: 150 ms after the finger lands, or a later mark. + // `time` is when the first frame at or after the onset runs. The curve + // starts there from rest, so no frame skips into it. animator.animate( {scale: heldScale}, {spring: CONTEXT_MENU_LIFT_SPRING}, @@ -183,6 +218,7 @@ export function useContextMenuPressFeedback( const end = useCallback( (time: number) => { + stopOnset(); const animator = animatorRef.current; const element = animator?.element; if ( @@ -201,7 +237,7 @@ export function useContextMenuPressFeedback( ).finished, ); }, - [settleBack], + [settleBack, stopOnset], ); const release = useCallback(() => { @@ -222,13 +258,14 @@ export function useContextMenuPressFeedback( }, []); const hold = useCallback(() => { + stopOnset(); isHeldRef.current = true; if (isGrownRef.current) { animatorRef.current?.stop(['scale']); } - }, []); + }, [stopOnset]); - // Grow at the onset, 150 ms after the finger lands. The recognizer reports + // Grow from the onset, 150 ms after the finger lands. The recognizer reports // the landing as it takes the finger, whether or not the press machine // marks the press. Inside a scroll view the machine marks late, and it never // marks a press that travels past 10 px first. A pen's onset waits for the @@ -251,14 +288,18 @@ export function useContextMenuPressFeedback( ); let isPressed = isMarkedOn(); let markedAt = 0; - let onsetTimer: ReturnType | undefined; const startAt = (onsetAt: number) => { - const wait = onsetAt - performance.now(); - if (wait > 0) { - onsetTimer = setTimeout(() => start(onsetAt), wait); - } else { - start(onsetAt); - } + stopOnset(); + stopOnsetRef.current = watchFramesFrom( + onsetAt, + // The engine is built in a frame, not in the handler of the touch, + // so the frame that starts the growth only creates its animation. + animatorFor, + time => { + stopOnsetRef.current = null; + start(time); + }, + ); }; // A pen's mark: the gesture host took that pen from the same input // before the mark's record comes, so the recognizer follows it already. @@ -279,7 +320,6 @@ export function useContextMenuPressFeedback( if (target != null && pressMarkOwnerOf(target) !== element) { return; } - clearTimeout(onsetTimer); startAt(landed + PRESS_ONSET_MS); }; const stopObserving = observeMutations( @@ -291,20 +331,20 @@ export function useContextMenuPressFeedback( isPressed = next; if (next) { if (!followsFinger.current()) { - clearTimeout(onsetTimer); + stopOnset(); markedAt = performance.now(); growAtMark(); } } else if (!isFollowed.current()) { // A finger the recognizer still follows keeps its onset, past // the machine's shorter travel. - clearTimeout(onsetTimer); + stopOnset(); } } }, ); return () => { - clearTimeout(onsetTimer); + stopOnset(); stopObserving(); fingerOnsetRef.current = null; pressMarkOwners.delete(element); From d44956d08bd3c696d39fe4e0ef720513e34d930a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 012/151] test(ContextMenu): the lift shows the menu inside its own dispatch The proof read "the menu shows in the lift's task" as "within one frame of the lift". Merged with main, the menu's render in that task takes 17 ms in the WebKit CI container, so the time proxy failed while the menu still showed before any frame. A page flag now records whether the menu shows while the lift's listeners run. --- ...tMenuLongPress.interaction.browser.spec.ts | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 87bbbbb8c2c2f..f4ee001b28a2b 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -90,11 +90,14 @@ async function openTouchStory( const w = window as unknown as { __menuShownAt?: number | null; __liftHandledAt?: number | null; + __menuShownInLift?: boolean | null; __menuShownTimerAt?: number | null; }; w.__menuShownAt = null; w.__liftHandledAt = null; + w.__menuShownInLift = null; w.__menuShownTimerAt = null; + let isInLift = false; // When the timer task that runs now started. The hold's moments come from // the gesture arena's timers. The menu commits in the task that decides // it, so its show runs inside that timer task. @@ -120,12 +123,22 @@ async function openTouchStory( timeout, ...args, )) as typeof window.setTimeout; - // When the page gets to the lift (the event's own timestamp is the - // hardware's, or the script's): the menu shows in the same task. + // When the page gets to the lift. The event's own timestamp is the + // hardware's, or the script's. Also whether the menu shows while the + // lift's listeners run: then no frame paints between the two. addEventListener( 'touchend', () => { w.__liftHandledAt = performance.now(); + isInLift = true; + // Added during the dispatch, it runs after the page's own listeners. + addEventListener( + 'touchend', + () => { + isInLift = false; + }, + {once: true, passive: true}, + ); }, {capture: true, passive: true}, ); @@ -142,6 +155,7 @@ async function openTouchStory( // Only the first show counts, so a later one cannot stand in for it. if (w.__menuShownAt == null) { w.__menuShownAt = performance.now(); + w.__menuShownInLift = isInLift; w.__menuShownTimerAt = timerAt; } } @@ -501,18 +515,24 @@ test('a finger lifted after the commit gets the menu at the lift, and sends no c await driver.play(hold(center, 530)); await page.waitForTimeout(300); await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); - const {lift, shown} = await page.evaluate(() => { + const {lift, shown, isInLift} = await page.evaluate(() => { const w = window as unknown as { __menuShownAt?: number | null; __liftHandledAt?: number | null; + __menuShownInLift?: boolean | null; + }; + return { + lift: w.__liftHandledAt ?? null, + shown: w.__menuShownAt ?? null, + isInLift: w.__menuShownInLift ?? null, }; - return {lift: w.__liftHandledAt ?? null, shown: w.__menuShownAt ?? null}; }); expect(lift).not.toBeNull(); expect(shown).not.toBeNull(); - // In the lift's own task: after it, and before the next frame could paint. + // In the lift's own dispatch: after it, and before the next frame could + // paint, however long the menu's render takes in that task. expect((shown as number) - (lift as number)).toBeGreaterThanOrEqual(0); - expect((shown as number) - (lift as number)).toBeLessThan(1000 / 60); + expect(isInLift).toBe(true); const log = await readInputLog(page); const end = log.filter(record => record.type === 'touchend').at(-1); expect(end?.defaultPrevented, JSON.stringify(log)).toBe(true); From 409e581997fa24733af5e3bbe8a178992bd3f5ce Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 013/151] test(ContextMenu): the menu loads the animator at once for its growth Merged with main, the lazy-sheet bundle proof pins that a menu with an on-demand sheet keeps the animator on demand. ContextMenu's touch growth plays on the animator from the first touch, so the animator loads with the menu. The proof now expects that for ContextMenu, and `rideKeyboard` still loads only with the sheet. --- scripts/lazy-sheet-bundle.test.mjs | 33 +++++++++++++++++++----------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/scripts/lazy-sheet-bundle.test.mjs b/scripts/lazy-sheet-bundle.test.mjs index d0f74abb83cb5..807fb86c36323 100644 --- a/scripts/lazy-sheet-bundle.test.mjs +++ b/scripts/lazy-sheet-bundle.test.mjs @@ -7,8 +7,9 @@ * @output Pins that a menu's static import keeps its on-demand bottom sheet's * keyboard code on demand. The sheet's keyboard ride (the animator and * `rideKeyboard`) stays in the chunks the import loads only when the sheet - * opens. This holds though the layer runtime's keyboard cap imports the - * keyboard module statically. + * opens. A menu that uses the animator at once loads it with the menu. This + * holds though the layer runtime's keyboard cap imports the keyboard module + * statically. * @position Node test over source, so it needs no build */ @@ -110,20 +111,28 @@ function rideIn(bytes) { describe('a menu with an on-demand bottom sheet', () => { it.each([ - ['DropdownMenu', 'packages/core/src/DropdownMenu/index.ts'], - ['ContextMenu', 'packages/core/src/ContextMenu/index.ts'], - ['Selector', 'packages/core/src/Selector/index.ts'], - ['MultiSelector', 'packages/core/src/MultiSelector/index.ts'], + ['DropdownMenu', 'packages/core/src/DropdownMenu/index.ts', []], + // ContextMenu's touch growth plays on the animator, so the animator loads + // with the menu. The sheet's own ride is then `rideKeyboard` alone. + [ + 'ContextMenu', + 'packages/core/src/ContextMenu/index.ts', + ['packages/core/src/motion/animator.ts'], + ], + ['Selector', 'packages/core/src/Selector/index.ts', []], + ['MultiSelector', 'packages/core/src/MultiSelector/index.ts', []], ])( "%s loads the sheet's keyboard ride only with the sheet", - (name, entry) => { + (name, entry, eagerRide) => { const {eager, onDemand} = importOf(entry, name); // The sheet still rides the keyboard, on demand. - expect(rideIn(onDemand)).toEqual([ - 'packages/core/src/keyboard/rideKeyboard.ts', - 'packages/core/src/motion/animator.ts', - ]); - expect(rideIn(eager)).toEqual([]); + expect(rideIn(onDemand)).toEqual( + [ + 'packages/core/src/keyboard/rideKeyboard.ts', + 'packages/core/src/motion/animator.ts', + ].filter(input => !eagerRide.includes(input)), + ); + expect(rideIn(eager)).toEqual(eagerRide); }, ); }); From abb70e167d42684a20ea59c03959758be7d7e72b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 014/151] test(ContextMenu): a starved page fails the 735 ms proof by name A WebKit CI run showed the menu at 890 ms, inside the timer task that decided it, so that task itself started late. The proof now logs the page's frames. A deciding task that starts within a frame of its due time keeps the 20 ms bound. A later start that a frame gap over 50 ms covers fails with FrameStarvationError, its numbers named; any other late start fails bare. The bound does not move. --- ...tMenuLongPress.interaction.browser.spec.ts | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index efba3d49c46db..deddefbbed4bf 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -21,6 +21,8 @@ import { } from '@astryxdesign/a11y-spec/playwright'; import { drag, + FRAME_STARVATION_MS, + FrameStarvationError, installInputLog, openStory, readInputLog, @@ -149,11 +151,79 @@ const touchStartedAt = async (page: Page) => lastInput(page, 'touchstart'); /** A finger held still for `ms`, then lifted. */ const hold = (at: {x: number; y: number}, ms: number) => tap(at, {holdMs: ms}); +/** One frame at 60 Hz, ms. */ +const FRAME_MS = 1000 / 60; + +/** Logs when each frame's callbacks run, on the page clock, until read. */ +async function startFrameLog(page: Page) { + await page.evaluate(() => { + const w = window as unknown as {__frameLog?: number[]}; + const log: number[] = []; + w.__frameLog = log; + const tick = () => { + log.push(performance.now()); + if (w.__frameLog === log) { + requestAnimationFrame(tick); + } + }; + requestAnimationFrame(tick); + }); +} + +/** Stops the frame log and reads it. */ +async function readFrameLog(page: Page): Promise { + return page.evaluate(() => { + const w = window as unknown as {__frameLog?: number[]}; + const log = w.__frameLog ?? []; + w.__frameLog = undefined; + return log; + }); +} + +/** + * The timer task that decides the menu starts within a frame of its due + * time. A later start that a frame gap over `FRAME_STARVATION_MS` covers + * fails by name: the page was starved of frames. Any other late start fails + * bare, because something on the page held the timer. + */ +function expectDecidedOnTime( + frames: ReadonlyArray, + dueAt: number, + startedAt: number, +) { + const lateMs = startedAt - dueAt; + if (lateMs <= FRAME_MS) { + return; + } + let longestGapMs = 0; + for (let i = 1; i < frames.length; i++) { + const coversLateStart = + frames[i - 1] <= dueAt + FRAME_MS && frames[i] >= startedAt - FRAME_MS; + if (coversLateStart) { + longestGapMs = Math.max(longestGapMs, frames[i] - frames[i - 1]); + } + } + if (longestGapMs > FRAME_STARVATION_MS) { + throw new FrameStarvationError({ + during: `the menu's timer task was due, and it started ${lateMs.toFixed(1)} ms late`, + frames: frames.filter(t => t > dueAt && t < startedAt).length, + min: Math.max(1, Math.floor(lateMs / FRAME_MS)), + longestGapMs, + }); + } + expect( + lateMs, + 'the timer task that decides the menu started late while frames ran', + ).toBeLessThanOrEqual(FRAME_MS); +} + test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async ({ page, }) => { const {driver, center} = await openTouchStory(page); + await startFrameLog(page); await driver.play(hold(center, menuDisplayMs + 200)); + const frames = await readFrameLog(page); const start = await touchStartedAt(page); const shown = await menuShownAt(page); const decided = await menuShownTimerAt(page); @@ -165,6 +235,7 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async 'the menu showed after the task that decided it', ).not.toBeNull(); expect((decided as number) - start).toBeGreaterThanOrEqual(menuDisplayMs - 1); + expectDecidedOnTime(frames, start + menuDisplayMs, decided as number); const after = (shown as number) - start; // The timer runs at its deadline, give or take a task. expect(after).toBeGreaterThanOrEqual(menuDisplayMs); From 983e46f38d1b10aa89835e80dba9ec844db299f7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 7 Nov 2026 10:41:35 -0800 Subject: [PATCH 015/151] feat(ContextMenu): the finger that opened the menu slides to an item Where a coarse pointer's held finger opens the menu, the same finger slides onto an item, which lights under it, and its lift selects it. A presentation="popover" or fine-pointer long press hands nothing over. It carries this pull request's own diff from bc4efd0469, replayed on main after #9814's squash, and folds these 11 commits (the history of bc4efd0469 has each one): - test(useMenuPress): a pointer that went down elsewhere is the menu's opening press - feat(useMenuPress): a pointer that went down elsewhere is the menu's opening press - test(ContextMenu): the finger a long press opened the menu under slides onto an item and its lift selects it - feat(ContextMenu): the finger a long press opened the menu under slides onto an item, and its lift selects it - docs(ContextMenu): FR12 records the slide onto an item after a long press opens the menu - docs(ContextMenu): the slide's release note and docs say the menu opens at the finger - docs(ContextMenu): FR12's slide follows a long press that opens the menu at the finger - docs(ContextMenu): FR5 points the slide to FR13 - docs(core): useMenuPress's @output keeps main's sentence - docs(ContextMenu): the slide changeset names where the slide applies - docs(ContextMenu): the slide changeset covers adaptive popovers too --- .changeset/contextmenu-touch-slide-to-pick.md | 7 + .../storybook/stories/ContextMenu.stories.tsx | 62 ++++--- .../ContextMenu/ContextMenu.spec.md | 13 +- .../core/src/ContextMenu/ContextMenu.doc.mjs | 4 +- .../core/src/ContextMenu/ContextMenu.test.tsx | 126 ++++++++++++++ packages/core/src/ContextMenu/ContextMenu.tsx | 31 ++-- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 45 ++++- ...tMenuLongPress.interaction.browser.spec.ts | 122 +++++++++++++- packages/core/src/hooks/useMenuPress.test.tsx | 159 ++++++++++++++++++ packages/core/src/hooks/useMenuPress.ts | 118 ++++++++++--- 10 files changed, 612 insertions(+), 75 deletions(-) create mode 100644 .changeset/contextmenu-touch-slide-to-pick.md diff --git a/.changeset/contextmenu-touch-slide-to-pick.md b/.changeset/contextmenu-touch-slide-to-pick.md new file mode 100644 index 0000000000000..a1d8f0392d6b0 --- /dev/null +++ b/.changeset/contextmenu-touch-slide-to-pick.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] ContextMenu where the primary pointer is coarse and the menu opens at the finger (`presentation` unset, or `adaptive` where it stays a popover): after the held finger opens the menu, the same finger may slide onto an action without lifting, as on iOS. Lifting over an action picks it, and lifting over no action leaves the menu open. The finger picks only after it has moved 10 px in the open menu, so a still lift picks nothing. + +@vjeux diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 0c25ea1cea0b4..c2892ca28c1fd 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -649,6 +649,12 @@ export const BottomSheetSubmenu: Story = { }; const touchStyles = stylex.create({ + demo: { + display: 'flex', + flexDirection: 'column', + alignItems: 'flex-start', + gap: '12px', + }, card: { width: '200px', height: '120px', @@ -667,31 +673,47 @@ export const TouchLongPress: Story = { docs: { description: { story: - 'Where the primary pointer is coarse (a touch screen), hold a finger on the card. As on iOS, it starts to grow after 150 ms, a haptic plays at 400 ms where the device can play one, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the card springs back to its size. While the menu is up, the page still scrolls: a touch outside the menu closes it as it begins to pan. The card returns to its size when the menu closes.', + 'Where the primary pointer is coarse (a touch screen), hold a finger on the card. As on iOS, it starts to grow after 150 ms, a haptic plays at 400 ms where the device can play one, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. Once the menu is up, the same finger may slide onto an action without lifting: lifting over an action picks it, and lifting over no action leaves the menu open. The last action picked shows below the card. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the card springs back to its size. While the menu is up, the page still scrolls: a touch outside the menu closes it as it begins to pan. The card returns to its size when the menu closes.', }, }, }, - render: () => ( - {}}, - {label: 'Share', icon: ShareIcon, onClick: () => {}}, - {label: 'Save to Files', icon: ArrowDownTrayIcon, onClick: () => {}}, - {type: 'divider'}, - { - label: 'Delete', - icon: TrashIcon, - variant: 'destructive', - onClick: () => {}, - }, - ]}> -
Hold for actions
-
- ), + render: () => , }; +/** The touch story's menu, and the last action it picked. */ +function TouchLongPressDemo() { + const [lastAction, setLastAction] = useState(null); + const pick = (label: string) => () => setLastAction(label); + return ( +
+ +
Hold for actions
+
+

+ {lastAction == null ? 'No action yet' : `Last action: ${lastAction}`} +

+
+ ); +} + export const TouchLongPressPopover: Story = { name: 'Touch / long press, presentation="popover"', parameters: { diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 5b9cc4172ffde..c12b61417580e 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -106,7 +106,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR2 | The `context-menu` target stays on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | `architecture:component-theming-surface`; current source | | FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | | FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | -| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, the opening finger is not handed to the menu so it cannot slide to a row, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | +| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. The long press that opened the menu does not close it as it lifts; a tap outside closes it, and a mouse press outside closes it at the press. Under a finger the menu MUST close as a pan that starts outside it begins (`spec:AST-094` FR32), MUST hand the held finger that opened it to the menu as the opening press, and MUST treat a pen's press outside as FR32 does (FR33). The held finger may then slide onto an item and lift to select it (FR13). The lift and the grow apply only to a menu opened by touch (a touch-initiated open on a coarse pointer); a menu opened by mouse or keyboard keeps its released appearance and motion, with no lift, no tint and no grow. A touch-opened menu MUST grow out of the finger's point and shrink back into it (`spec:AST-094` FR31) as its own surface, by transform and opacity only (`spec:AST-094` FR5), with no second element such as a glass surface growing behind it, and on a block trigger MUST lift the trigger above the page with the menu beside it (FR33; DD1, DEC-2). The long-press presentation is a gesture component, so the trigger's lift plays `springs.contextMenuLift`, the menu's grow `springs.contextMenuMorph`, and the trigger's return, part of the menu's exit, `springs.contextMenuDismiss` (`spec:AST-094` FR4, FR7, FR45). Implementation gap: it keeps the layer's own entrance and exit, no trigger lift or page tint exists, and a pen press outside closes it at the press. Right-click, Shift+F10, long-press invocation, and keyboard navigation are as FR1 and FR8 state. | `module:DropdownMenu/useMenuPress`; `spec:AST-094` FR26–FR33 | | FR6 | With `triggerAs="span"` the Trigger area is an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Right-click, Shift+F10, long-press, and `context-menu` target placement all use that box. | DEC-1 | | FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | | FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. Implementation gap: the arrow keys and typeahead skip disabled rows today (Current-state impact). | Current source and tests | @@ -114,6 +114,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | | FR12 | Under a finger, a block trigger whose menu opens at the finger grows during a hold toward 1.0735 times its size on `springs.contextMenuLift`, from the onset, 150 ms after the finger lands, and it returns after a lift before the commit on `springs.contextMenuDismiss`, as FR5 names them. The hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured on iOS 26.2 (`motion/uikit/contextMenu.ts`): UIKit commits at 400 ms, shows the menu at 735 ms, and grows the view on a linear ramp chased by a spring. `spec:AST-094` FR4, FR45: the two moments are measured input, and the long-press presentation is a gesture component (FR5), so the growth and its return play their spring roles | +| FR13 | After a long press opens the menu at the finger, the same finger may slide onto an item without lifting; lifting over an item selects it, and lifting over no item leaves the menu open. A lift before the finger has moved UIMenu's handoff distance selects nothing (`spec:AST-094` FR33). | `module:DropdownMenu/useMenuPress` FR11; `spec:AST-094` FR33 | ### Allowed variation @@ -253,7 +254,7 @@ anchor is positioning infrastructure rather than consumer anatomy. | FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | | FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | | FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | -| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | +| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow or the FR33 lift. | `audit:ContextMenu/behavior` | | FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | | FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | | FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | @@ -265,6 +266,7 @@ anchor is positioning infrastructure rather than consumer anatomy. | FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | | FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | | FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does"; `contextMenuPress.test.ts`; `contextMenuPressFeedback.test.tsx` "grows toward the held scale on springs.contextMenuLift, from the onset" and "returns on springs.contextMenuDismiss, at the time the recognizer ended the press"; `ContextMenuTouchGrowth.test.tsx` onset cases; the touch story's browser curve and busy-thread cases in Chromium, and an iOS Safari recording for WebKit | A held finger: the commit, the display, the onset, the growth, the early-lift return, their springs | A commit or a display off UIKit's moments, a growth before the onset, or a growth or return off its spring role fails | `audit:ContextMenu/behavior` | +| FR13 | `ContextMenu.test.tsx` "lets the finger the menu opened under slide onto an item, and its lift selects it" and its handoff, no-item and lift-open cases; `ContextMenuLongPress.interaction.browser.spec.ts` "the finger the menu opened under slides onto an item, which lights under it, and its lift selects it" and its early-lift and slide-past cases; `useMenuPress.test.tsx` continuation suite | Held until the menu opens: a slide onto an item, a still lift, a slide past the menu; a menu opened at the lift | A still lift that selects an item, a slide whose lift selects nothing or another item, a lift over no item that closes the menu, or a page that scrolls under the slide fails. | `audit:ContextMenu/behavior` | | Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | | RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | @@ -276,10 +278,9 @@ anchor is positioning infrastructure rather than consumer anatomy. - **No headless factory (FR10).** No headless context menu ships, so ContextMenu owns its invocation, open state, and outside-press listener itself, against `spec:AST-107` FR8. -- **Touch grow, handoff, and lift (FR5).** A touch-opened menu keeps the - layer's own entrance and exit instead of growing from the finger, the held - finger that opened it cannot slide to a row, and a block trigger is not - lifted over a tinted page; a pen press outside closes it at the press. All +- **Touch grow and lift (FR5).** A touch-opened menu keeps the layer's own + entrance and exit instead of growing from the finger, and a block trigger is + not lifted over a tinted page; a pen press outside closes it at the press. All are against `spec:AST-094` FR31, FR32, and FR33. A menu opened by mouse or keyboard already keeps its released appearance and motion. diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs index 7390609678f8b..26fbc9e526aac 100644 --- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs +++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -159,7 +159,7 @@ export const docs = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons. Under a finger, where the primary pointer is coarse, a held finger opens it with iOS timing: a block trigger whose menu opens at the finger starts to grow at 150 ms, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions without cluttering the UI with visible buttons. Under a finger, where the primary pointer is coarse, a held finger opens it with iOS timing: a block trigger whose menu opens at the finger starts to grow at 150 ms, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. When the menu opens at the finger, the same finger can then slide onto an action and lift to pick it.', bestPractices: [ { guidance: true, @@ -269,7 +269,7 @@ export const docsDense = { usage: { anatomy, description: - 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (a coarse primary pointer): a held finger opens it at 735 ms, or on a lift after 400 ms; a block trigger whose menu opens at the finger grows from 150 ms.', + 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (a coarse primary pointer): a held finger opens it at 735 ms, or on a lift after 400 ms; a block trigger whose menu opens at the finger grows from 150 ms; when the menu opens at the finger, the same finger then slides onto an action and lifts to pick it.', bestPractices: [ {guidance: true, description: 'Keep items concise and action-oriented.'}, { diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index e65447bba669b..f9cddd35cecce 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -761,6 +761,27 @@ const advance = (ms: number) => vi.advanceTimersByTime(ms); }); +/** A finger's pointer event, stamped on the (faked) clock. */ +function dispatchPointer( + type: 'pointerdown' | 'pointermove' | 'pointerup', + target: EventTarget, + {pointerId, x, y}: {pointerId: number; x: number; y: number}, +): void { + const event = new PointerEvent(type, { + bubbles: true, + cancelable: true, + composed: true, + pointerId, + pointerType: 'touch', + clientX: x, + clientY: y, + button: 0, + buttons: type === 'pointerup' ? 0 : 1, + }); + Object.defineProperty(event, 'timeStamp', {value: performance.now()}); + target.dispatchEvent(event); +} + /** The primary pointer answers `matches` to `(pointer: coarse)`. */ function stubPointer(isCoarse: boolean) { vi.stubGlobal( @@ -1235,6 +1256,111 @@ describe.each([ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); press.up(); }); + /** A menu with two rows, held open by a finger that is still down. */ + function holdUntilTheMenuShows() { + const onCopy = vi.fn(); + const onShare = vi.fn(); + render( + +
Long-press me
+
, + ); + const trigger = screen.getByTestId('ctx'); + const contact = {id: 1, x: 20, y: 20}; + // A finger's pointer comes first, then its touch, as browsers send them. + dispatchPointer('pointerdown', trigger, {pointerId: 7, x: 20, y: 20}); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + const row = (name: string) => + screen.getByRole('menuitem', {hidden: true, name}); + const slide = (target: EventTarget, x: number, y: number) => { + dispatchPointer('pointermove', target, {pointerId: 7, x, y}); + dispatchTouch( + 'touchmove', + trigger, + [{...contact, x, y}], + [{...contact, x, y}], + ); + }; + const lift = (target: EventTarget, x: number, y: number) => { + dispatchPointer('pointerup', target, {pointerId: 7, x, y}); + dispatchTouch('touchend', trigger, [{...contact, x, y}], []); + }; + return {onCopy, onShare, row, slide, lift}; + } + + it('lets the finger the menu opened under slide onto an item, and its lift selects it', () => { + const {onCopy, onShare, row, slide, lift} = holdUntilTheMenuShows(); + // UIMenu's handoff counts from the first position the open menu sees. + slide(row('Share'), 20, 30); + slide(row('Share'), 20, 45); + expect(row('Share')).toHaveFocus(); + act(() => { + lift(row('Share'), 20, 45); + }); + expect(onShare).toHaveBeenCalledTimes(1); + expect(onCopy).not.toHaveBeenCalled(); + }); + + it('selects nothing for a lift before UIMenu’s handoff, however long the finger rests on an item, and leaves the menu open', () => { + const {onCopy, onShare, row, slide, lift} = holdUntilTheMenuShows(); + slide(row('Share'), 20, 26); + // Past the settle time a mouse would pick here; a finger needs the + // handoff. + advance(400); + act(() => { + lift(row('Share'), 20, 26); + }); + expect(onShare).not.toHaveBeenCalled(); + expect(onCopy).not.toHaveBeenCalled(); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + }); + + it('leaves the menu open for a lift over no item after the slide', () => { + const {onCopy, onShare, row, slide, lift} = holdUntilTheMenuShows(); + slide(row('Share'), 20, 30); + slide(row('Share'), 20, 45); + const menu = screen.getByRole('menu', {hidden: true}); + slide(menu, 20, 300); + act(() => { + lift(menu, 20, 300); + }); + expect(onShare).not.toHaveBeenCalled(); + expect(onCopy).not.toHaveBeenCalled(); + expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled(); + }); + + it('hands nothing over when the menu opens at the lift: the finger is gone', () => { + const onShare = vi.fn(); + render( + +
Long-press me
+
, + ); + const trigger = screen.getByTestId('ctx'); + const contact = {id: 1, x: 20, y: 20}; + dispatchPointer('pointerdown', trigger, {pointerId: 7, x: 20, y: 20}); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(500); + act(() => { + dispatchPointer('pointerup', trigger, {pointerId: 7, x: 20, y: 20}); + dispatchTouch('touchend', trigger, [contact], []); + }); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + // A later move of that pointer id is no press of this menu's. + const row = screen.getByRole('menuitem', {hidden: true, name: 'Share'}); + dispatchPointer('pointermove', row, {pointerId: 7, x: 20, y: 60}); + expect(row).not.toHaveFocus(); + expect(onShare).not.toHaveBeenCalled(); + }); }, ); diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 83adbec81a3c2..4d450dc91bc67 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -84,12 +84,13 @@ import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn'; import {useInternalListFocus} from '../hooks/useListFocus'; import {useLongPress} from '../hooks/useLongPress'; import {pressableProps} from '../utils/pressFeedback'; -import {useMenuPress} from '../hooks/useMenuPress'; +import {useDropdownMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; import {shadowHostOf} from '../utils/flatTree'; import {usePresentation} from '../utils/presentation'; import { ContextMenuTouchLayer, + type ContextMenuHeldPointer, type ContextMenuTouchHandle, } from './ContextMenuTouchLayer'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; @@ -786,18 +787,32 @@ export function ContextMenu({ [isDisabled, openAtLocalPoint, getAnchorBaseRect], ); + const menuPress = useDropdownMenuPress({ + menuRef: listRef, + itemSelector: MENU_ITEM_SELECTOR, + onDismiss: closeMenu, + isEnabled: !usesBottomSheet, + }); + const {continueGesture} = menuPress; + // Touch invocation. Under the touch model, the touch layer runs UIKit's long // press and asks for the menu here, at the client point where the finger // landed. const openFromFinger = useCallback( - (point: {x: number; y: number}) => { + (point: {x: number; y: number}, held: ContextMenuHeldPointer | null) => { const local = toTriggerLocal(point); // The finger is still down: its lift belongs to the press that opened // the menu, so it does not close it. openingGestureRef.current = currentGesture(); openAtLocalPoint(local.x, local.y, triggerRef.current, 'menu'); + // A finger still down goes on into the menu as its opening press: it + // slides onto an item, and its lift selects it. A lift over no item + // leaves the menu open. + if (held != null) { + continueGesture({...held, time: Date.now()}); + } }, - [openAtLocalPoint, toTriggerLocal], + [continueGesture, openAtLocalPoint, toTriggerLocal], ); // Today's long press for a finger outside the touch model: under a fine @@ -896,16 +911,6 @@ export function ContextMenu({ isOpen && !usesBottomSheet, ); - // The press model: the row under a release acts, the highlight follows a - // held pointer, a mouse released outside dismisses and a finger leaves the - // menu open. - const menuPress = useMenuPress({ - menuRef: listRef, - itemSelector: MENU_ITEM_SELECTOR, - onDismiss: closeMenu, - isEnabled: !usesBottomSheet, - }); - const renderedMenu = (
; - /** Open the menu at a client point (where the finger landed). */ - onOpen: (point: {x: number; y: number}) => void; + /** + * Open the menu at a client point (where the finger landed). `held` is the + * finger or pen that is still down as the menu opens. It goes on into the + * menu. It is null for a menu that opens at the lift. + */ + onOpen: ( + point: {x: number; y: number}, + held: ContextMenuHeldPointer | null, + ) => void; /** * The hold committed: the menu shows at its moment or at the lift, so its * content can mount now, hidden. @@ -50,6 +64,22 @@ export interface ContextMenuTouchLayerProps { onCancel?: () => void; } +/** + * The pointer that the gesture host paired with the press's finger, for the + * menu's press model. Null where the finger has no pointer. + */ +function heldPointerOf( + press: ContextMenuPressRecognizer, + doc: Document | undefined, +): ContextMenuHeldPointer | null { + const touch = press.trackedTouches[0]; + if (touch == null || doc == null || touch.pointerType === 'mouse') { + return null; + } + const pointerId = getGestureHost(doc).pointerIdOf(touch); + return pointerId == null ? null : {pointerId, pointerType: touch.pointerType}; +} + /** * UIContextMenuInteraction's long press. iOS Safari never fires `contextmenu` * for a held finger. So the trigger runs its own recognizer on UIKit's @@ -57,7 +87,8 @@ export interface ContextMenuTouchLayerProps { * recognizer claims the finger. The page stops scrolling under it, and its * lift sends no click and no compatibility mouse events. The menu opens where * the finger landed: at `menuDisplayMs` if it is still down, or at the lift. - * A lift before the commit, a second finger or a scroll gets no menu. So does + * A finger still down goes on into the menu. A lift before the commit, a + * second finger or a scroll gets no menu. So does * a drift past the tolerance before the menu shows. The press feedback grows * the trigger from the onset, 150 ms after the finger lands, while the * recognizer follows the finger. It springs back when the recognizer ends the @@ -121,7 +152,7 @@ export function ContextMenuTouchLayer({ return recognizer; }, press => { - const open = () => { + const open = (held: ContextMenuHeldPointer | null) => { // The press feedback grew the trigger from its center, and the cursor // anchor inside it moves with that scale. So stop the growth where it // is. ContextMenu places the anchor under the finger. @@ -129,7 +160,7 @@ export function ContextMenuTouchLayer({ hasPressOpenedRef.current = true; // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the menu shows in the task that decides it, as UIKit shows it at its moment, not a scheduled task later flushSync(() => { - onOpenRef.current(press.press ?? press.location()); + onOpenRef.current(press.press ?? press.location(), held); }); }; switch (press.state) { @@ -144,12 +175,12 @@ export function ContextMenuTouchLayer({ break; case 'changed': if (press.isMenuDue && !hasPressOpenedRef.current) { - open(); + open(heldPointerOf(press, triggerRef.current?.ownerDocument)); } break; case 'ended': if (!hasPressOpenedRef.current) { - open(); + open(null); } break; case 'possible': diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 97ca0567f393a..9dbcb16168968 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -6,9 +6,9 @@ * the interaction harness, the context-menu constants and UIKit's frames * @output Interaction and animation proofs for a context menu that a held * finger opens on UIKit's timeline. They cover the menu's moments, the - * press feedback against UIKit's frames and a blocked main thread. They - * also cover the page under the finger, a pan outside and a storyboard of - * the press + * held finger's slide onto an item, the press feedback against UIKit's + * frames and a blocked main thread. They also cover the page under the + * finger, a pan outside and a storyboard of the press * @position Interaction specs of packages/core/src/ContextMenu; Chromium's * finger stands for Android's engine, and WebKit's for iOS */ @@ -41,6 +41,7 @@ import { tap, thawTimers, timeline, + toTouchEvents, touchDriver, trackMarker, traceRendering, @@ -556,6 +557,121 @@ test('the lift after the menu shows keeps it open and sends no click', async ({ expect(log.filter(record => record.type === 'click')).toEqual([]); }); +/** The Share row's center: open the menu once with a held press, measure, close it. */ +async function shareRowCenter( + page: Page, + driver: TouchDriver, + at: {x: number; y: number}, +): Promise<{x: number; y: number}> { + const menu = page.getByRole('menu', {name: 'Photo actions'}); + await driver.play(hold(at, menuDisplayMs + 100)); + await expect(menu).toBeVisible(); + const row = await page.getByRole('menuitem', {name: 'Share'}).boundingBox(); + if (row == null) { + throw new Error('no Share row'); + } + await page.keyboard.press('Escape'); + await expect(menu).toBeHidden(); + // The trigger returns to its size before the next press. + await expect + .poll(async () => presentedScale(page.getByTestId('touch-context-menu'))) + .toBe(1); + return {x: row.x + row.width / 2, y: row.y + row.height / 2}; +} + +/** The text of the focused row, or null when no row holds the focus. */ +const litRow = async (page: Page) => + page.evaluate(() => + document.activeElement?.getAttribute('role') === 'menuitem' + ? (document.activeElement.textContent ?? '') + : null, + ); + +test('the finger the menu opened under slides onto an item, which lights under it, and its lift selects it', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + const share = await shareRowCenter(page, driver, center); + const script = drag(center, share, { + holdMs: menuDisplayMs + 100, + durationMs: 250, + restMs: 120, + }); + const lastMove = + toTouchEvents(script).filter(e => e.type === 'touchMove').length - 1; + let moves = 0; + let lit: string | null = null; + await driver.play(script, { + onEvent: async step => { + if (step.type === 'touchMove' && moves++ === lastMove) { + lit = await litRow(page); + } + }, + }); + expect(lit).toContain('Share'); + await expect(page.getByTestId('touch-context-menu-last')).toHaveText( + 'Last action: Share', + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); +}); + +test('a lift before UIMenu’s handoff selects nothing and leaves the menu open', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + // 6 px after the menu opens: short of UIMenu's 10 pt handoff. + await driver.play( + drag( + center, + {x: center.x, y: center.y + 6}, + {holdMs: menuDisplayMs + 100, durationMs: 100, restMs: 120}, + ), + ); + await page.waitForTimeout(300); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + await expect(page.getByTestId('touch-context-menu-last')).toHaveText( + 'No action yet', + ); +}); + +test('a finger that slides on past the menu leaves it open with no row lit, selects nothing, and scrolls nothing', async ({ + page, +}) => { + const {driver, center, top} = await openScrollableStory(page); + const before = await top(); + // Held until the menu opens under it, then down and a little inward through + // the rows, and on past the menu's bottom. + const script = drag( + center, + {x: center.x + 24, y: center.y + 260}, + {holdMs: menuDisplayMs + 100, durationMs: 400, restMs: 120}, + ); + const lastMove = + toTouchEvents(script).filter(e => e.type === 'touchMove').length - 1; + let moves = 0; + let lit: string | null = null; + let isLitOnTheWay = false; + await driver.play(script, { + onEvent: async step => { + if (step.type !== 'touchMove') { + return; + } + const row = await litRow(page); + isLitOnTheWay ||= row != null; + if (moves++ === lastMove) { + lit = row; + } + }, + }); + expect(await top()).toBe(before); + expect(isLitOnTheWay).toBe(true); + expect(lit).toBeNull(); + await expect(page.getByTestId('touch-context-menu-last')).toHaveText( + 'No action yet', + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + test('the menu’s anchor sits under the finger, on screen and as laid out, while the trigger is grown, and the menu stays put', async ({ page, }) => { diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx index d78c85cb2bcaa..2e6876f359070 100644 --- a/packages/core/src/hooks/useMenuPress.test.tsx +++ b/packages/core/src/hooks/useMenuPress.test.tsx @@ -22,6 +22,8 @@ import { __resetMenuPressForTest, useDropdownMenuPress, useMenuPress, + type DropdownMenuPressReturn, + type UseMenuPressReturn, } from './useMenuPress'; import {MENU_PRESS_HANDOFF_PX, MENU_PRESS_SETTLE_MS} from './menuPressGesture'; import {holdInput, isInputShield} from '../Layer/inputHold'; @@ -40,6 +42,8 @@ interface HarnessProps { getScroller?: () => HTMLElement | null; onHighlight?: (row: HTMLElement | null) => void; touchModel?: 'pointer' | 'uikit'; + /** Receives the hook's return, for calls the trigger does not make. */ + pressRef?: {current: DropdownMenuPressReturn | null}; } function Harness({ @@ -50,6 +54,7 @@ function Harness({ getScroller, onHighlight, touchModel, + pressRef, }: HarnessProps) { const menuRef = useRef(null); const triggerRef = useRef(null); @@ -78,6 +83,9 @@ function Harness({ onHighlight, touchModel, }); + if (pressRef != null) { + pressRef.current = press; + } return ( <>
))} +
+ {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + ]}> + + +
+ +
+
), }; diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index c5604ddce5ec4..bc841028e4a2b 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -758,11 +758,11 @@ for (const input of ['finger', 'pen'] as const) { }); } -test('the trigger’s visual lays out its children as the trigger would: a block, a row and a grid trigger each match a plain box with the same style', async ({ +test('the trigger’s visual lays out its children as the trigger would: a block, a row, a grid and a set-height trigger each match a plain box with the same style', async ({ page, }) => { await openStory(page, storybook(), 'core-contextmenu--touch-trigger-layouts'); - for (const layout of ['block', 'row', 'grid']) { + for (const layout of ['block', 'row', 'grid', 'tall']) { const read = async (testId: string) => page.getByTestId(testId).evaluate(root => { const origin = root.getBoundingClientRect(); @@ -787,7 +787,7 @@ test('the trigger’s visual lays out its children as the trigger would: a block const trigger = await read(`layout-${layout}`); const reference = await read(`layout-${layout}-reference`); const detail = JSON.stringify({layout, trigger, reference}); - expect(trigger.children.length, detail).toBe(3); + expect(trigger.children.length, detail).toBe(layout === 'tall' ? 1 : 3); expect(trigger.children.length, detail).toBe(reference.children.length); expect(trigger.size.width, detail).toBeCloseTo(reference.size.width, 1); expect(trigger.size.height, detail).toBeCloseTo(reference.size.height, 1); From 3c39a05a474458f986ffc0fdcd307a56c09de9ff Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 11:43:41 -0800 Subject: [PATCH 027/151] test(ContextMenu): a late drift past 11.5 px cancels in every engine The case for a finger that drifts past 11.5 px after the commit, before the menu's moment, now runs in Chromium too. --- .../ContextMenuLongPress.interaction.browser.spec.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 321de791549e4..b9da7f55e6741 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -364,12 +364,7 @@ const afterTwoFrames = async (page: Page) => test('a slow drift past 11.5 px late in the hold cancels it: no menu and no click (AST-094 FR21)', async ({ page, - browserName, }) => { - test.fixme( - browserName === 'chromium', - 'Chromium opens the menu at about 736 ms after a drift past 11.5 px; WebKit cancels', - ); const {driver, center} = await openTouchStory(page); const clicks = await countTriggerClicks(page); // The finger rests past the commit at 400 ms, then drifts 14 px in 250 ms. From a4e040430c2700ae2ddb1b34865297ff5d655a8b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 12:55:23 -0800 Subject: [PATCH 028/151] fix(ContextMenu): the menu waits for the finger's late moves Under load, a held finger's moves can reach the page after the menu's moment, though they came before it, and the gesture arena's clock has then passed that moment. A finger that drifted past 11.5 px after the commit still got the menu. The touch layer now reports each pointermove of the held finger with its own time. At its moment the menu waits while such moves still come, so a drift in them ends the hold. --- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 63 +++++++++++++++++++ .../src/ContextMenu/contextMenuPress.test.ts | 28 +++++++++ .../core/src/ContextMenu/contextMenuPress.ts | 61 ++++++++++++++++-- 3 files changed, 148 insertions(+), 4 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index a42432403acf2..d3a8a7a1be0d0 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -16,6 +16,8 @@ import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; import {flushSync} from 'react-dom'; import {playHaptic} from '../gestures/haptics'; +import {useAttachment} from '../hooks/useAttachment'; +import {subscribeInput} from '../utils/inputStream'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './ContextMenuTouch'; @@ -41,6 +43,23 @@ export interface ContextMenuTouchLayerProps { onCancel?: () => void; } +/** + * An event's time on the gesture arena's clock, as the gesture host reads it. + * That is its `timeStamp`, which some engines and DOM emulators give from the + * epoch instead of from the page's time origin. + */ +function clockTime(event: Event): number { + const time = event.timeStamp; + if ( + time > 1e12 && + typeof performance !== 'undefined' && + performance.timeOrigin > 0 + ) { + return time - performance.timeOrigin; + } + return time; +} + /** * UIContextMenuInteraction's long press. iOS Safari never fires `contextmenu` * for a held finger. So the trigger runs its own recognizer on UIKit's @@ -117,6 +136,50 @@ export function ContextMenuTouchLayer({ }, ); + // Under load, the held finger's moves can reach the page after the menu's + // moment, though they came before it. The recognizer reads each move's own + // time here, so the menu waits for them, and a drift in them still ends the + // hold. + useAttachment( + triggerRef, + element => { + const view = element.ownerDocument.defaultView; + if (view == null) { + return () => {}; + } + let pointerId: number | null = null; + const onDown = (event: PointerEvent) => { + if (event.pointerType === 'touch' && event.isPrimary) { + pointerId = event.pointerId; + } + }; + const onMove = (event: PointerEvent) => { + if (event.pointerId !== pointerId) { + return; + } + recognizer.followMove(clockTime(event)); + }; + const onEnd = (event: PointerEvent) => { + if (event.pointerId === pointerId) { + pointerId = null; + } + }; + element.addEventListener('pointerdown', onDown, {capture: true}); + const unsubscribes = [ + subscribeInput(view, 'pointermove', onMove), + subscribeInput(view, 'pointerup', onEnd), + subscribeInput(view, 'pointercancel', onEnd), + ]; + return () => { + element.removeEventListener('pointerdown', onDown, {capture: true}); + for (const unsubscribe of unsubscribes) { + unsubscribe(); + } + }; + }, + recognizer, + ); + useImperativeHandle( ref, () => ({ diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index fdc7db94eb237..493b40f0a515f 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -97,6 +97,34 @@ describe('ContextMenuPressRecognizer', () => { expect(press.isMenuDue).toBe(false); }); + it('waits at the menu’s moment for moves that came before it but reach the page late, and a drift in them cancels', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // The page has just handled a move from 450 ms: more may still come. + press.followMove(450); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // A late move from before the moment, 14 px over: the hold ends. + finger.move(14, 0, DISPLAY + 10); + expect(states).toEqual([`began@${COMMIT}`, `cancelled@${DISPLAY + 10}`]); + expect(press.isMenuDue).toBe(false); + finger.up(DISPLAY + 300); + }); + + it('shows the menu once a move from its moment on reaches the page', () => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + press.followMove(450); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + press.followMove(DISPLAY + 5); + expect(press.isMenuDue).toBe(true); + expect(states.at(-1)).toBe(`changed@${DISPLAY}`); + finger.up(DISPLAY + 300); + }); + it('lets the finger move freely once the menu is due', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index dfc25022eeb40..eec04013993e0 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -23,6 +23,12 @@ import {contextMenu} from '../motion/uikit/contextMenu'; const {commitMs, menuDisplayMs, allowableMovement} = contextMenu.press; +/** + * How long the finger's moves may pause before the menu stops waiting for + * late ones, in ms: three frames at 60 Hz. + */ +const LATE_MOVE_GAP_MS = 50; + /** * The foundation's own press timer, which this recognizer never lets fire: * the hold below commits instead. It is longer than any hold, and under the @@ -80,8 +86,16 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { private pressTouchId: number | null = null; /** Where the finger landed, while its hold runs. The drift counts from here. */ private holdFrom: {x: number; y: number} | null = null; + /** + * The held finger's latest pointermove: when it came, on the event clock, + * and when the page got it. + */ + private latestMove: {time: number; arrivedAt: number} | null = null; /** When the finger landed, on the arena's clock. The deadlines count from it. */ private holdStart = 0; + /** The menu's moment passed while the finger's moves still came late. */ + private isMenuWaiting = false; + private moveWait: ReturnType | null = null; constructor(options: ContextMenuPressRecognizerOptions = {}) { super({ @@ -138,6 +152,18 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { super.touchesMoved(touches); } + /** + * ContextMenu's touch layer reports each pointermove of the held finger: + * the time it came, on the event clock. A move from the menu's moment on + * means no late move can still come before it. + */ + followMove(time: number): void { + this.latestMove = {time, arrivedAt: performance.now()}; + if (this.isMenuWaiting && time >= this.holdStart + menuDisplayMs) { + this.showMenu(); + } + } + /** * Follows the finger during its hold. A drift past `allowableMovement` on * either axis ends the hold. Returns whether the hold still runs. @@ -159,9 +185,18 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { private endHold(): void { this.clearTimer(); + this.stopMoveWait(); this.holdFrom = null; } + private stopMoveWait(): void { + this.isMenuWaiting = false; + if (this.moveWait != null) { + clearTimeout(this.moveWait); + this.moveWait = null; + } + } + /** The hold's commit claims the finger, then waits for the menu's moment. */ private commit(): void { if (this.holdFrom == null) { @@ -180,12 +215,29 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } } - /** The finger is still down at the menu's moment: the menu is due. */ + /** + * The finger is still down at the menu's moment: the menu is due. Under + * load, the finger's moves can reach the page after that moment, though + * they came before it. While they still come, the menu waits for them, so + * a drift in them still ends the hold. + */ private showMenu(): void { - if (this.holdFrom != null && isActive(this.state)) { - this.isMenuDue = true; - this.setState('changed'); + this.stopMoveWait(); + if (this.holdFrom == null || !isActive(this.state)) { + return; + } + const move = this.latestMove; + if ( + move != null && + move.time < this.holdStart + menuDisplayMs && + performance.now() - move.arrivedAt < LATE_MOVE_GAP_MS + ) { + this.isMenuWaiting = true; + this.moveWait = setTimeout(() => this.showMenu(), LATE_MOVE_GAP_MS); + return; } + this.isMenuDue = true; + this.setState('changed'); } protected override reset(): void { @@ -193,6 +245,7 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { this.endHold(); this.pressTouchId = null; this.press = null; + this.latestMove = null; this.isMenuDue = false; } } From 7d23141f22db7feec950d08efe70302a356def79 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 13:13:11 -0800 Subject: [PATCH 029/151] fix(ContextMenu): the trigger's visual takes the trigger's height In block layout the inner visual box took its content's height, so a 100% tall child of a set-height trigger collapsed to its text. The box now fills the trigger in block layout too, as it does in flex and grid. --- packages/core/src/ContextMenu/ContextMenu.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 7ec64ec0ede47..3f84a40375ef4 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -143,9 +143,10 @@ const styles = stylex.create({ userSelect: 'none', }, // The trigger's own visual, which the press feedback grows. It lays its - // children out as the trigger would, and fills the trigger in a flex or - // grid layout. The cursor anchor stays outside it, so a layer never takes - // the press's scale. + // children out as the trigger would, and fills the trigger in block, flex + // and grid layout. A full-height child then keeps a set-height trigger's + // height. The cursor anchor stays outside it, so a layer never takes the + // press's scale. triggerVisual: { display: 'inherit', flexDirection: 'inherit', @@ -167,6 +168,7 @@ const styles = stylex.create({ gridColumn: '1 / -1', gridRow: '1 / -1', minWidth: 0, + height: '100%', borderRadius: 'inherit', }, // 1px anchor placed at the cursor point within the trigger. The menu is From a75cf0914f6b23a0afe614b0cd78f24f6bdb18ee Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 13:13:11 -0800 Subject: [PATCH 030/151] test(ContextMenu): the inner visual box adds no attribute The trigger keeps its own attributes, the inner box carries only its class, and the cursor anchor keeps its attributes. --- .../ContextMenu.triggerProps.test.tsx | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.triggerProps.test.tsx b/packages/core/src/ContextMenu/ContextMenu.triggerProps.test.tsx index e384ddc50099c..146b5d288debb 100644 --- a/packages/core/src/ContextMenu/ContextMenu.triggerProps.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.triggerProps.test.tsx @@ -4,7 +4,8 @@ * @file ContextMenu.triggerProps.test.tsx * @input vitest, @testing-library/react, ContextMenu * @output A guard that the trigger element receives only DOM props: React - * warns about nothing, and no hook-internal function lands on it. + * warns about nothing, and no hook-internal function lands on it. The + * inner visual box adds no attribute to the trigger. * @position Testing; validates ContextMenu.tsx. Its own file on purpose: React * warns about an unknown DOM prop once per module, so this case must be the * first ContextMenu render of its file to see the warning at all. @@ -51,4 +52,26 @@ describe('ContextMenu trigger element', () => { consoleError.mockRestore(); } }); + + it('keeps its own attributes: the inner visual box carries only its class', () => { + render( + +
Right-click me
+
, + ); + const trigger = screen.getByTestId('block'); + expect(trigger.getAttributeNames().sort()).toEqual([ + 'class', + 'data-testid', + ]); + const [visual, anchor] = Array.from(trigger.children); + expect(visual.tagName).toBe('DIV'); + expect(visual.getAttributeNames()).toEqual(['class']); + expect(visual.textContent).toBe('Right-click me'); + expect(anchor.getAttributeNames().sort()).toEqual([ + 'aria-hidden', + 'class', + 'style', + ]); + }); }); From 3b76a8c589d83265097166bdeec7de82c600e618 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 13:32:33 -0800 Subject: [PATCH 031/151] test(ContextMenu): a finger inside the tolerance at the menu's moment A finger still inside 11.5 px at 735 ms that crosses it just after keeps its menu: the tolerance holds until the menu shows. --- ...textMenuLongPress.interaction.browser.spec.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index b9da7f55e6741..e47db738395de 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -388,6 +388,22 @@ test('a slow drift past 11.5 px late in the hold cancels it: no menu and no clic } }); +test('a finger still inside 11.5 px at the menu’s moment that crosses it just after still gets the menu (AST-094 FR12)', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + // 14 px over 650–760 ms: 10.6 px at the last move before 735 ms, 12.7 px + // at the first move after it. + await driver.play( + drag( + center, + {x: center.x + 14, y: center.y}, + {holdMs: 650, durationMs: 110, restMs: 300}, + ), + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + test('a new finger that pans outside the open menu closes it, and the page scrolls', async ({ page, }) => { From 88cc0d8742431d162b5457a19079a978f4a0f22c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 13:52:17 -0800 Subject: [PATCH 032/151] fix(ContextMenu): the press reads each move's own time from the arena The gesture arena holds a late input's time at its clock, so a move that reached the page after the menu's moment looked as if it came at that moment. The arena now also keeps the time the input came with, as the touch's inputTime, and no other recognizer reads it. The press reads it: while the menu waits at its moment, a drift in a move from before the moment ends the hold, and a move from the moment on shows the menu. ContextMenu's own pointer listeners and clock copy are gone. --- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 63 ------------------- .../src/ContextMenu/contextMenuPress.test.ts | 56 ++++++++++++++--- .../core/src/ContextMenu/contextMenuPress.ts | 27 ++++---- packages/core/src/gestures/GestureArena.ts | 3 + .../core/src/gestures/__tests__/arena.test.ts | 21 ++++++- packages/core/src/gestures/types.ts | 6 ++ 6 files changed, 89 insertions(+), 87 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index d3a8a7a1be0d0..a42432403acf2 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -16,8 +16,6 @@ import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; import {flushSync} from 'react-dom'; import {playHaptic} from '../gestures/haptics'; -import {useAttachment} from '../hooks/useAttachment'; -import {subscribeInput} from '../utils/inputStream'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './ContextMenuTouch'; @@ -43,23 +41,6 @@ export interface ContextMenuTouchLayerProps { onCancel?: () => void; } -/** - * An event's time on the gesture arena's clock, as the gesture host reads it. - * That is its `timeStamp`, which some engines and DOM emulators give from the - * epoch instead of from the page's time origin. - */ -function clockTime(event: Event): number { - const time = event.timeStamp; - if ( - time > 1e12 && - typeof performance !== 'undefined' && - performance.timeOrigin > 0 - ) { - return time - performance.timeOrigin; - } - return time; -} - /** * UIContextMenuInteraction's long press. iOS Safari never fires `contextmenu` * for a held finger. So the trigger runs its own recognizer on UIKit's @@ -136,50 +117,6 @@ export function ContextMenuTouchLayer({ }, ); - // Under load, the held finger's moves can reach the page after the menu's - // moment, though they came before it. The recognizer reads each move's own - // time here, so the menu waits for them, and a drift in them still ends the - // hold. - useAttachment( - triggerRef, - element => { - const view = element.ownerDocument.defaultView; - if (view == null) { - return () => {}; - } - let pointerId: number | null = null; - const onDown = (event: PointerEvent) => { - if (event.pointerType === 'touch' && event.isPrimary) { - pointerId = event.pointerId; - } - }; - const onMove = (event: PointerEvent) => { - if (event.pointerId !== pointerId) { - return; - } - recognizer.followMove(clockTime(event)); - }; - const onEnd = (event: PointerEvent) => { - if (event.pointerId === pointerId) { - pointerId = null; - } - }; - element.addEventListener('pointerdown', onDown, {capture: true}); - const unsubscribes = [ - subscribeInput(view, 'pointermove', onMove), - subscribeInput(view, 'pointerup', onEnd), - subscribeInput(view, 'pointercancel', onEnd), - ]; - return () => { - element.removeEventListener('pointerdown', onDown, {capture: true}); - for (const unsubscribe of unsubscribes) { - unsubscribe(); - } - }; - }, - recognizer, - ); - useImperativeHandle( ref, () => ({ diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index 493b40f0a515f..c0b9606c8ca0d 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -13,7 +13,7 @@ * @position Unit tests of packages/core/src/ContextMenu/contextMenuPress.ts */ -import {describe, expect, it} from 'vitest'; +import {describe, expect, it, vi} from 'vitest'; import {createHarness} from '../gestures/__tests__/harness'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -102,29 +102,67 @@ describe('ContextMenuPressRecognizer', () => { const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); harness.advance(COMMIT); // The page has just handled a move from 450 ms: more may still come. - press.followMove(450); + finger.move(3, 0, 450); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); - // A late move from before the moment, 14 px over: the hold ends. - finger.move(14, 0, DISPLAY + 10); - expect(states).toEqual([`began@${COMMIT}`, `cancelled@${DISPLAY + 10}`]); + // A late move that came at 600 ms, 14 px over. The arena holds its time + // at the clock, and the recognizer reads the time it came with. + finger.move(14, 0, 600); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `cancelled@${DISPLAY}`, + ]); expect(press.isMenuDue).toBe(false); finger.up(DISPLAY + 300); }); - it('shows the menu once a move from its moment on reaches the page', () => { + it('shows the menu for a move stamped from its moment on, even past the tolerance, and lets the finger move freely after', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); harness.advance(COMMIT); - press.followMove(450); + finger.move(3, 0, 450); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); - press.followMove(DISPLAY + 5); + // Inside the tolerance at the moment, 14 px over 15 ms after it. + finger.move(14, 0, DISPLAY + 15); expect(press.isMenuDue).toBe(true); - expect(states.at(-1)).toBe(`changed@${DISPLAY}`); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `changed@${DISPLAY + 15}`, + `changed@${DISPLAY + 15}`, + ]); finger.up(DISPLAY + 300); }); + it('shows the menu once the late moves pause for 50 ms', () => { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 450); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + vi.advanceTimersByTime(49); + expect(press.isMenuDue).toBe(false); + vi.advanceTimersByTime(1); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); + } finally { + vi.useRealTimers(); + } + }); + + it('shows a still finger’s menu at its moment, with no wait', () => { + const {harness, press, states} = setup(); + harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([`began@${COMMIT}`, `changed@${DISPLAY}`]); + }); + it('lets the finger move freely once the menu is due', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index eec04013993e0..740d550e10e44 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -87,8 +87,8 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { /** Where the finger landed, while its hold runs. The drift counts from here. */ private holdFrom: {x: number; y: number} | null = null; /** - * The held finger's latest pointermove: when it came, on the event clock, - * and when the page got it. + * The held finger's latest move: the time it came with, and when the page + * got it. */ private latestMove: {time: number; arrivedAt: number} | null = null; /** When the finger landed, on the arena's clock. The deadlines count from it. */ @@ -140,6 +140,17 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { protected override touchesMoved(touches: ReadonlyArray): void { const touch = touches.find(each => each.id === this.pressTouchId); + if (touch != null) { + this.latestMove = {time: touch.inputTime, arrivedAt: performance.now()}; + // A move from the menu's moment on: the finger stayed inside the + // tolerance until then, so the menu shows, and it moves freely after. + if ( + this.isMenuWaiting && + touch.inputTime >= this.holdStart + menuDisplayMs + ) { + this.showMenu(); + } + } const hasDrifted = touch != null && !this.followHold(touch); if (hasDrifted && this.state === 'possible') { this.setState('failed'); @@ -152,18 +163,6 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { super.touchesMoved(touches); } - /** - * ContextMenu's touch layer reports each pointermove of the held finger: - * the time it came, on the event clock. A move from the menu's moment on - * means no late move can still come before it. - */ - followMove(time: number): void { - this.latestMove = {time, arrivedAt: performance.now()}; - if (this.isMenuWaiting && time >= this.holdStart + menuDisplayMs) { - this.showMenu(); - } - } - /** * Follows the finger during its hold. A drift past `allowableMovement` on * either axis ends the hold. Returns whether the hold still runs. diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index 62bf6d03374cd..edb5992a3b2d8 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -238,6 +238,7 @@ export class GestureArena { x: input.x, y: input.y, time, + inputTime: input.time, startX: input.x, startY: input.y, startTime: time, @@ -328,6 +329,7 @@ export class GestureArena { x: input.x, y: input.y, time, + inputTime: input.time, startX: input.x, startY: input.y, startTime: time, @@ -993,6 +995,7 @@ export class GestureArena { touch.x = input.x; touch.y = input.y; touch.time = time; + touch.inputTime = input.time; touch.phase = phase; changed.push(touch); } diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts index d5a724e20862d..72bad1a344e67 100644 --- a/packages/core/src/gestures/__tests__/arena.test.ts +++ b/packages/core/src/gestures/__tests__/arena.test.ts @@ -10,7 +10,8 @@ * requirements, idle recognizers), shouldBegin and shouldReceiveTouch, * innermost resolution, independent touches, delivery to the view (claims, * cancelsTouchesInView, delaysTouchesBegan, deferred and replayed clicks, - * the browser taking a touch), cancellation, and the event clock + * the browser taking a touch), cancellation, and the event clock, which + * holds a late input at its time and keeps the time the input came with * @position Unit tests of packages/core/src/gestures/GestureArena.ts and the * state machine of GestureRecognizer.ts */ @@ -402,6 +403,24 @@ describe('arena: cancellation and time', () => { h.finger(1).move(5, 0, 90); expect(h.log).toEqual(['r:began@100']); }); + it('holds a late input at the clock, and keeps the time it came with', () => { + const h = createHarness(); + const seen: {time: number; inputTime: number}[] = []; + const r = new Scripted('r', { + moved: recognizer => { + const [touch] = recognizer.trackedTouches; + seen.push({time: touch.time, inputTime: touch.inputTime}); + }, + }); + h.finger(1).down(0, 0, 100, {recognizers: [r]}); + h.advance(500); + h.finger(1).move(5, 0, 300); + h.finger(1).move(6, 0, 520); + expect(seen).toEqual([ + {time: 500, inputTime: 300}, + {time: 520, inputTime: 520}, + ]); + }); }); /** A clock whose timers run one task at a time, as an event loop does. */ diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts index ef646cecde9d2..38c510eca9e33 100644 --- a/packages/core/src/gestures/types.ts +++ b/packages/core/src/gestures/types.ts @@ -81,6 +81,12 @@ export interface GestureTouch { y: number; /** Timestamp of the latest position. */ time: number; + /** + * The latest position's own timestamp, as the host read it. The arena's + * clock never runs back, so a late input's `time` is held at the clock; + * this field keeps the time the input came with. + */ + inputTime: number; readonly startX: number; readonly startY: number; readonly startTime: number; From 46bc0da3ad1744aecb662d10f8f182544213a569 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 14:58:48 -0800 Subject: [PATCH 033/151] test(ContextMenu): coalesced late samples and an on-time move A late move whose coalesced samples cross 11.5 px before the menu's moment ends the hold, as the same samples as separate moves do. A finger that shifts slightly just before 735 ms, with its move on time, gets the menu at 735 ms. A late timer after a recent move still waits. The test harness's finger moves can carry coalesced samples. --- ...tMenuLongPress.interaction.browser.spec.ts | 20 ++ .../src/ContextMenu/contextMenuPress.test.ts | 175 ++++++++++++++---- .../core/src/gestures/__tests__/harness.ts | 17 +- 3 files changed, 170 insertions(+), 42 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index e47db738395de..f866dc632b4b0 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -245,6 +245,26 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); +test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms when its move reaches the page on time (AST-094 FR12)', async ({ + page, +}) => { + const {driver, center} = await openTouchStory(page); + // One 3 px move at 700 ms, then still. An idle page gets the move at once. + await driver.play( + drag( + center, + {x: center.x + 3, y: center.y}, + {holdMs: 699, durationMs: 1, restMs: 300}, + ), + ); + const start = await touchStartedAt(page); + const shown = await menuShownAt(page); + expect(shown, 'the menu never showed').not.toBeNull(); + const after = (shown as number) - start; + expect(after).toBeGreaterThanOrEqual(menuDisplayMs); + expect(after).toBeLessThan(menuDisplayMs + 20); +}); + test('the menu mounts at the commit, closed and out of the accessibility tree, and shows at 735 ms', async ({ page, }) => { diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index c0b9606c8ca0d..577f1a8fe4d06 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -33,6 +33,20 @@ function setup( return {harness, press, states}; } +/** + * Runs `body` with the page's clock (`performance.now()`) and window timers + * faked. `at(time)` moves the page's clock to when the page gets the next + * input, which may be after the time the input came with. + */ +function withPageClock(body: (at: (time: number) => void) => void): void { + vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + try { + body(time => vi.advanceTimersByTime(time - performance.now())); + } finally { + vi.useRealTimers(); + } +} + describe('ContextMenuPressRecognizer', () => { it('commits at UIKit’s moment (iOS 26.2: 400 ms, first 60 Hz tick 417 ms), not a millisecond before', () => { const {harness, press, states} = setup(); @@ -98,51 +112,101 @@ describe('ContextMenuPressRecognizer', () => { }); it('waits at the menu’s moment for moves that came before it but reach the page late, and a drift in them cancels', () => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - // The page has just handled a move from 450 ms: more may still come. - finger.move(3, 0, 450); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // A late move that came at 600 ms, 14 px over. The arena holds its time - // at the clock, and the recognizer reads the time it came with. - finger.move(14, 0, 600); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `cancelled@${DISPLAY}`, - ]); - expect(press.isMenuDue).toBe(false); - finger.up(DISPLAY + 300); + withPageClock(at => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // The page gets a move from 450 ms only at 700 ms: it is behind. + at(700); + finger.move(3, 0, 450); + at(DISPLAY); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // A late move that came at 600 ms, 14 px over. The arena holds its time + // at the clock, and the recognizer reads the time it came with. + at(DISPLAY + 10); + finger.move(14, 0, 600); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `cancelled@${DISPLAY}`, + ]); + expect(press.isMenuDue).toBe(false); + finger.up(DISPLAY + 300); + }); }); it('shows the menu for a move stamped from its moment on, even past the tolerance, and lets the finger move freely after', () => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - finger.move(3, 0, 450); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // Inside the tolerance at the moment, 14 px over 15 ms after it. - finger.move(14, 0, DISPLAY + 15); - expect(press.isMenuDue).toBe(true); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `changed@${DISPLAY + 15}`, - `changed@${DISPLAY + 15}`, - ]); - finger.up(DISPLAY + 300); + withPageClock(at => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + at(700); + finger.move(3, 0, 450); + at(DISPLAY); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // Inside the tolerance at the moment, 14 px over 15 ms after it. + at(DISPLAY + 20); + finger.move(14, 0, DISPLAY + 15); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `changed@${DISPLAY + 15}`, + `changed@${DISPLAY + 15}`, + ]); + finger.up(DISPLAY + 300); + }); + }); + + it('judges each coalesced sample of a late move at its own time while the menu waits', () => { + withPageClock(at => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + at(700); + finger.move(3, 0, 450); + at(DISPLAY); + harness.advance(DISPLAY); + // One late move with two samples: 13 px at 725 ms, before the moment, + // then 14 px at 740 ms. Two separate moves would end the hold at the + // first, so this one does too. + at(DISPLAY + 20); + finger.move(14, 0, DISPLAY + 5, [{x: 13, y: 0, time: DISPLAY - 10}]); + expect(press.isMenuDue).toBe(false); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `cancelled@${DISPLAY + 5}`, + ]); + }); + }); + + it('shows the waiting menu for a coalesced move whose samples before the moment stay inside the tolerance', () => { + withPageClock(at => { + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + at(700); + finger.move(3, 0, 450); + at(DISPLAY); + harness.advance(DISPLAY); + at(DISPLAY + 20); + finger.move(14, 0, DISPLAY + 5, [{x: 10, y: 0, time: DISPLAY - 10}]); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); + }); }); it('shows the menu once the late moves pause for 50 ms', () => { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); - try { + withPageClock(at => { const {harness, press} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); harness.advance(COMMIT); + at(700); finger.move(3, 0, 450); + at(DISPLAY); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); vi.advanceTimersByTime(49); @@ -150,9 +214,44 @@ describe('ContextMenuPressRecognizer', () => { vi.advanceTimersByTime(1); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); - } finally { - vi.useRealTimers(); - } + }); + }); + + it('shows the menu at its moment after a move that reached the page on time, with no wait', () => { + withPageClock(at => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // A 3 px shift at 720 ms that the page gets at once: it is not behind. + at(720); + finger.move(3, 0, 720); + at(DISPLAY); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@720', + `changed@${DISPLAY}`, + ]); + }); + }); + + it('waits at the menu’s moment when its own timer runs late after a recent move', () => { + withPageClock(at => { + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + at(730); + finger.move(3, 0, 730); + // The page is busy: the moment's timer runs 40 ms late, so later moves + // may still be queued. + at(DISPLAY + 40); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + vi.advanceTimersByTime(50); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); + }); }); it('shows a still finger’s menu at its moment, with no wait', () => { diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.ts index 37f8796de614d..5b9c46c2681ce 100644 --- a/packages/core/src/gestures/__tests__/harness.ts +++ b/packages/core/src/gestures/__tests__/harness.ts @@ -5,8 +5,8 @@ * @input Nothing * @output Exports the synthetic-input harness the gesture tests share: a * manual clock, an arena wired to a transition log, fingers that land, - * move and lift at explicit timestamps, and a coarse primary pointer for - * tests that go through the document's host + * move (with coalesced samples) and lift at explicit timestamps, and a + * coarse primary pointer for tests that go through the document's host * @position Test-only helper of packages/core/src/gestures (excluded from the * build with the rest of __tests__) */ @@ -18,6 +18,7 @@ import type { GestureTouch, NativeScrollProbe, TouchConsumer, + TouchSample, } from '../types'; /** @@ -189,12 +190,20 @@ export class Finger { return this; } - move(x: number, y: number, time: number): this { + /** `history`: the coalesced samples before this one, oldest first. */ + move( + x: number, + y: number, + time: number, + history?: ReadonlyArray, + ): this { this.x = x; this.y = y; this.time = time; this.harness.clock.time = time; - this.harness.arena.moved([{id: this.id, x, y, time}]); + this.harness.arena.moved([ + {id: this.id, x, y, time, ...(history == null ? {} : {history})}, + ]); return this; } From cad79ec4d6bc5ffee6d487bfd86ea5ed4d37d7ac Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 15:36:45 -0800 Subject: [PATCH 034/151] fix(ContextMenu): judge each sample at its time, wait only when late The gesture arena now keeps each coalesced sample of a move at the time it came with, as the touch's inputSamples, and no other recognizer reads them. The press follows the finger through each of them: a drift past 11.5 px before the menu's moment ends the hold, and a sample from the moment on shows a waiting menu. The menu waits at its moment only when the page is behind its input: a recent move from before the moment, or the moment's timer, ran more than two frames late. The wait runs on the arena's clock, like the hold's deadlines. An on-time finger gets the menu at 735 ms. --- .../src/ContextMenu/contextMenuPress.test.ts | 19 ++-- .../core/src/ContextMenu/contextMenuPress.ts | 100 +++++++++++------- packages/core/src/gestures/GestureArena.ts | 9 ++ .../core/src/gestures/__tests__/arena.test.ts | 26 ++++- packages/core/src/gestures/types.ts | 6 ++ 5 files changed, 114 insertions(+), 46 deletions(-) diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index 577f1a8fe4d06..290cd0cbc48eb 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -34,12 +34,12 @@ function setup( } /** - * Runs `body` with the page's clock (`performance.now()`) and window timers - * faked. `at(time)` moves the page's clock to when the page gets the next - * input, which may be after the time the input came with. + * Runs `body` with the page's clock (`performance.now()`) faked. `at(time)` + * moves it to when the page gets the next input, which may be after the time + * the input came with. */ function withPageClock(body: (at: (time: number) => void) => void): void { - vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'performance']}); + vi.useFakeTimers({toFake: ['performance']}); try { body(time => vi.advanceTimersByTime(time - performance.now())); } finally { @@ -209,9 +209,12 @@ describe('ContextMenuPressRecognizer', () => { at(DISPLAY); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); - vi.advanceTimersByTime(49); + // The wait runs on the arena's clock. + at(DISPLAY + 49); + harness.advance(DISPLAY + 49); expect(press.isMenuDue).toBe(false); - vi.advanceTimersByTime(1); + at(DISPLAY + 50); + harness.advance(DISPLAY + 50); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); @@ -248,7 +251,9 @@ describe('ContextMenuPressRecognizer', () => { at(DISPLAY + 40); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); - vi.advanceTimersByTime(50); + // No more moves came: the wait ends 50 ms on, on the arena's clock. + at(DISPLAY + 90); + harness.advance(DISPLAY + 50); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index 740d550e10e44..344c007e6cbf9 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -29,6 +29,12 @@ const {commitMs, menuDisplayMs, allowableMovement} = contextMenu.press; */ const LATE_MOVE_GAP_MS = 50; +/** + * The page counts as behind its input when an input or a timer runs this long + * after its own time. In ms: two frames at 60 Hz. + */ +const LATE_INPUT_MS = 33; + /** * The foundation's own press timer, which this recognizer never lets fire: * the hold below commits instead. It is longer than any hold, and under the @@ -95,7 +101,6 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { private holdStart = 0; /** The menu's moment passed while the finger's moves still came late. */ private isMenuWaiting = false; - private moveWait: ReturnType | null = null; constructor(options: ContextMenuPressRecognizerOptions = {}) { super({ @@ -142,14 +147,6 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { const touch = touches.find(each => each.id === this.pressTouchId); if (touch != null) { this.latestMove = {time: touch.inputTime, arrivedAt: performance.now()}; - // A move from the menu's moment on: the finger stayed inside the - // tolerance until then, so the menu shows, and it moves freely after. - if ( - this.isMenuWaiting && - touch.inputTime >= this.holdStart + menuDisplayMs - ) { - this.showMenu(); - } } const hasDrifted = touch != null && !this.followHold(touch); if (hasDrifted && this.state === 'possible') { @@ -164,22 +161,31 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } /** - * Follows the finger during its hold. A drift past `allowableMovement` on - * either axis ends the hold. Returns whether the hold still runs. + * Follows the finger during its hold, through each sample of the move at + * the time it came with. A sample from the menu's moment on shows a + * waiting menu: the finger stayed inside the tolerance until then, and it + * moves freely after. A drift past `allowableMovement` on either axis ends + * the hold. Returns whether the hold still runs. */ private followHold(touch: GestureTouch): boolean { - const from = this.holdFrom; - if (from == null) { - return false; - } - if ( - Math.abs(touch.x - from.x) > allowableMovement || - Math.abs(touch.y - from.y) > allowableMovement - ) { - this.endHold(); - return false; + const moment = this.holdStart + menuDisplayMs; + for (const sample of touch.inputSamples) { + const from = this.holdFrom; + if (from == null) { + return false; + } + if (this.isMenuWaiting && sample.time >= moment) { + this.presentMenu(); + } + if ( + Math.abs(sample.x - from.x) > allowableMovement || + Math.abs(sample.y - from.y) > allowableMovement + ) { + this.endHold(); + return false; + } } - return true; + return this.holdFrom != null; } private endHold(): void { @@ -189,10 +195,9 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } private stopMoveWait(): void { - this.isMenuWaiting = false; - if (this.moveWait != null) { - clearTimeout(this.moveWait); - this.moveWait = null; + if (this.isMenuWaiting) { + this.isMenuWaiting = false; + this.clearTimer(); } } @@ -215,30 +220,49 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } /** - * The finger is still down at the menu's moment: the menu is due. Under - * load, the finger's moves can reach the page after that moment, though - * they came before it. While they still come, the menu waits for them, so - * a drift in them still ends the hold. + * The finger is still down at the menu's moment: the menu is due. When the + * page is behind its input, the finger's moves can reach it after that + * moment, though they came before it. While they still come, the menu + * waits for them, so a drift in them still ends the hold. */ private showMenu(): void { this.stopMoveWait(); - if (this.holdFrom == null || !isActive(this.state)) { + if (this.holdFrom == null || !isActive(this.state) || this.isMenuDue) { return; } - const move = this.latestMove; - if ( - move != null && - move.time < this.holdStart + menuDisplayMs && - performance.now() - move.arrivedAt < LATE_MOVE_GAP_MS - ) { + if (this.isBehindInput()) { this.isMenuWaiting = true; - this.moveWait = setTimeout(() => this.showMenu(), LATE_MOVE_GAP_MS); + // On the arena's clock, like the hold's own deadlines. + this.setTimer(this.now() + LATE_MOVE_GAP_MS, () => this.showMenu()); return; } + this.presentMenu(); + } + + private presentMenu(): void { + this.stopMoveWait(); this.isMenuDue = true; this.setState('changed'); } + /** + * Whether the page may still hold moves from before the menu's moment. A + * move from before it reached the page in the last `LATE_MOVE_GAP_MS`, and + * that move or the moment's timer ran more than `LATE_INPUT_MS` late. + */ + private isBehindInput(): boolean { + const move = this.latestMove; + const moment = this.holdStart + menuDisplayMs; + const now = performance.now(); + return ( + move != null && + move.time < moment && + now - move.arrivedAt < LATE_MOVE_GAP_MS && + (move.arrivedAt - move.time > LATE_INPUT_MS || + now - moment > LATE_INPUT_MS) + ); + } + protected override reset(): void { super.reset(); this.endHold(); diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index edb5992a3b2d8..d9a353fad7ab1 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -239,6 +239,10 @@ export class GestureArena { y: input.y, time, inputTime: input.time, + inputSamples: [ + ...(input.history ?? []), + {x: input.x, y: input.y, time: input.time}, + ], startX: input.x, startY: input.y, startTime: time, @@ -330,6 +334,7 @@ export class GestureArena { y: input.y, time, inputTime: input.time, + inputSamples: [{x: input.x, y: input.y, time: input.time}], startX: input.x, startY: input.y, startTime: time, @@ -996,6 +1001,10 @@ export class GestureArena { touch.y = input.y; touch.time = time; touch.inputTime = input.time; + touch.inputSamples = [ + ...(input.history ?? []), + {x: input.x, y: input.y, time: input.time}, + ]; touch.phase = phase; changed.push(touch); } diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts index 72bad1a344e67..13f798c14339b 100644 --- a/packages/core/src/gestures/__tests__/arena.test.ts +++ b/packages/core/src/gestures/__tests__/arena.test.ts @@ -11,7 +11,8 @@ * innermost resolution, independent touches, delivery to the view (claims, * cancelsTouchesInView, delaysTouchesBegan, deferred and replayed clicks, * the browser taking a touch), cancellation, and the event clock, which - * holds a late input at its time and keeps the time the input came with + * holds a late input at its time and keeps the times the input and its + * coalesced samples came with * @position Unit tests of packages/core/src/gestures/GestureArena.ts and the * state machine of GestureRecognizer.ts */ @@ -421,6 +422,29 @@ describe('arena: cancellation and time', () => { {time: 520, inputTime: 520}, ]); }); + it('keeps a late move’s coalesced samples at the times they came with', () => { + const h = createHarness(); + const seen: {samples: number[]; inputSamples: number[]}[] = []; + const r = new Scripted('r', { + moved: recognizer => { + const [touch] = recognizer.trackedTouches; + seen.push({ + samples: touch.samples.map(sample => sample.time), + inputSamples: touch.inputSamples.map(sample => sample.time), + }); + }, + }); + h.finger(1).down(0, 0, 100, {recognizers: [r]}); + h.advance(500); + h.finger(1).move(5, 0, 300); + // Both late: the clock holds them at 500 ms, and `samples` drops the + // earlier one, which comes before the touch's held time. + h.finger(1).move(7, 0, 320, [{x: 6, y: 0, time: 310}]); + expect(seen).toEqual([ + {samples: [500], inputSamples: [300]}, + {samples: [500], inputSamples: [310, 320]}, + ]); + }); }); /** A clock whose timers run one task at a time, as an event loop does. */ diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts index 38c510eca9e33..598501a78456c 100644 --- a/packages/core/src/gestures/types.ts +++ b/packages/core/src/gestures/types.ts @@ -87,6 +87,12 @@ export interface GestureTouch { * this field keeps the time the input came with. */ inputTime: number; + /** + * The latest event's positions at the times they came with, oldest first, + * ending with the current one at `inputTime`. The arena's clock filters + * `samples`; it does not filter these. + */ + inputSamples: TouchSample[]; readonly startX: number; readonly startY: number; readonly startTime: number; From 889adedc07ec9a26417eda437334fc530134f9d4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 16:07:28 -0800 Subject: [PATCH 035/151] test(ContextMenu): moves held behind a block decide before the menu A finger that crosses 11.5 px at 650 ms while the page is blocked past the menu's moment, until 760, 800 or 900 ms, ends the hold when its coalesced move arrives, as separate moves do. A still finger behind a block gets its menu once no move comes. Every case fakes the page's clock from 0, and the on-time browser case checks that the moment's own timer task shows the menu. --- ...tMenuLongPress.interaction.browser.spec.ts | 9 +++ .../src/ContextMenu/contextMenuPress.test.ts | 64 ++++++++++++++++--- 2 files changed, 63 insertions(+), 10 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index f866dc632b4b0..df976edbcfc5b 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -249,6 +249,7 @@ test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms w page, }) => { const {driver, center} = await openTouchStory(page); + await startFrameLog(page); // One 3 px move at 700 ms, then still. An idle page gets the move at once. await driver.play( drag( @@ -257,9 +258,17 @@ test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms w {holdMs: 699, durationMs: 1, restMs: 300}, ), ); + const frames = await readFrameLog(page); const start = await touchStartedAt(page); const shown = await menuShownAt(page); + const decided = await menuShownTimerAt(page); expect(shown, 'the menu never showed').not.toBeNull(); + // The moment's own timer task shows the menu: nothing waits. + expect( + decided, + 'the menu showed after the task that decided it', + ).not.toBeNull(); + expectDecidedOnTime(frames, start + menuDisplayMs, decided as number); const after = (shown as number) - start; expect(after).toBeGreaterThanOrEqual(menuDisplayMs); expect(after).toBeLessThan(menuDisplayMs + 20); diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index 290cd0cbc48eb..81d0e7eecaa3c 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -13,7 +13,7 @@ * @position Unit tests of packages/core/src/ContextMenu/contextMenuPress.ts */ -import {describe, expect, it, vi} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {createHarness} from '../gestures/__tests__/harness'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -34,20 +34,23 @@ function setup( } /** - * Runs `body` with the page's clock (`performance.now()`) faked. `at(time)` - * moves it to when the page gets the next input, which may be after the time - * the input came with. + * Runs `body` with the page's clock (`performance.now()`), which every case + * fakes from 0. `at(time)` moves it to when the page gets the next input, + * which may be after the time the input came with. */ function withPageClock(body: (at: (time: number) => void) => void): void { - vi.useFakeTimers({toFake: ['performance']}); - try { - body(time => vi.advanceTimersByTime(time - performance.now())); - } finally { - vi.useRealTimers(); - } + body(time => vi.advanceTimersByTime(time - performance.now())); } describe('ContextMenuPressRecognizer', () => { + // The page's clock starts with the harness's, so no case runs late by it. + beforeEach(() => { + vi.useFakeTimers({toFake: ['performance']}); + }); + afterEach(() => { + vi.useRealTimers(); + }); + it('commits at UIKit’s moment (iOS 26.2: 400 ms, first 60 Hz tick 417 ms), not a millisecond before', () => { const {harness, press, states} = setup(); harness.finger(1).down(100, 200, 1000, {recognizers: [press]}); @@ -199,6 +202,47 @@ describe('ContextMenuPressRecognizer', () => { }); }); + for (const blockedUntil of [760, 800, 900]) { + it(`judges a coalesced move from behind a block until ${blockedUntil} ms before the menu shows`, () => { + withPageClock(at => { + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // On time until 640 ms. Then the page is blocked past the moment. + at(640); + finger.move(3, 0, 640); + // The finger crossed 11.5 px at 650 ms. Its moves wait behind the + // block and come as one coalesced move. + at(blockedUntil); + finger.move(14, 0, blockedUntil - 5, [ + {x: 13, y: 0, time: 650}, + {x: 14, y: 0, time: 700}, + ]); + expect(press.isMenuDue).toBe(false); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@640', + `cancelled@${blockedUntil - 5}`, + ]); + }); + }); + } + + it('shows a still finger’s menu after a block, once no move comes from behind it', () => { + withPageClock(at => { + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + // The moment's timer runs 65 ms late behind a block. + at(DISPLAY + 65); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + at(DISPLAY + 115); + harness.advance(DISPLAY + 50); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); + }); + }); + it('shows the menu once the late moves pause for 50 ms', () => { withPageClock(at => { const {harness, press} = setup(); From 45bfb443caab5da2ec78aa94cb81d235679abb38 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 16:16:26 -0800 Subject: [PATCH 036/151] fix(ContextMenu): a late menu timer waits for moves behind the block When the menu's timer runs more than a frame late, the page was blocked, and the finger's moves from before the moment may still be queued. The menu then waits up to 50 ms, counted from when the page runs again, so those moves are judged at their own times first. On an idle page the timer runs on time, and nothing waits. The record's FR16 gap line states the shift and its 50 ms bound. --- .../specs/AST-094-touch-presentations/spec.md | 5 ++ .../src/ContextMenu/contextMenuPress.test.ts | 6 +- .../core/src/ContextMenu/contextMenuPress.ts | 57 ++++++++++++++----- 3 files changed, 51 insertions(+), 17 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index f34804ca76a50..201c4232848e3 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -1036,6 +1036,11 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and - FR6 gap: under a starved compositor, Chromium can show a frame 40 to 60 ms after the main-thread frame that builds it. A retarget then first shows that far into its curve: up to 6.5 px on a loaded Switch. +- FR16 gap: ContextMenu's long press keeps its outcome on a blocked main + thread, but its menu can show later. When the menu's timer runs more than a + frame late, the menu waits up to 50 ms for moves still queued. A move from + before the moment that reaches the page more than two frames late holds it + the same way. - Consumer docs: none until a component ships its touch presentation; each component documents its own, including the `presentation` value that keeps the released surface (FR25). diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index 81d0e7eecaa3c..b2f979513a0e8 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -237,7 +237,7 @@ describe('ContextMenuPressRecognizer', () => { harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); at(DISPLAY + 115); - harness.advance(DISPLAY + 50); + harness.advance(DISPLAY + 115); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); @@ -295,9 +295,9 @@ describe('ContextMenuPressRecognizer', () => { at(DISPLAY + 40); harness.advance(DISPLAY); expect(press.isMenuDue).toBe(false); - // No more moves came: the wait ends 50 ms on, on the arena's clock. + // No more moves came: the wait ends 50 ms after the late timer ran. at(DISPLAY + 90); - harness.advance(DISPLAY + 50); + harness.advance(DISPLAY + 90); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index 344c007e6cbf9..2084d06856f76 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -35,6 +35,13 @@ const LATE_MOVE_GAP_MS = 50; */ const LATE_INPUT_MS = 33; +/** + * The menu's timer ran behind a blocked page when it runs this long after its + * deadline. In ms: one frame at 60 Hz. A timer has no dispatch delay of its + * own, so one frame is enough. + */ +const LATE_TIMER_MS = 17; + /** * The foundation's own press timer, which this recognizer never lets fire: * the hold below commits instead. It is longer than any hold, and under the @@ -223,22 +230,47 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { * The finger is still down at the menu's moment: the menu is due. When the * page is behind its input, the finger's moves can reach it after that * moment, though they came before it. While they still come, the menu - * waits for them, so a drift in them still ends the hold. + * waits for them, so a drift in them still ends the hold. A timer that ran + * late ran behind a blocked page, which may hold such moves too. */ private showMenu(): void { + if (!this.isMenuPending()) { + return; + } + const moment = this.holdStart + menuDisplayMs; + if (performance.now() - moment > LATE_TIMER_MS || this.hasLateMove()) { + this.waitForMoves(); + return; + } + this.presentMenu(); + } + + /** The wait's end: moves that still come late keep the menu waiting. */ + private endMoveWait(): void { this.stopMoveWait(); - if (this.holdFrom == null || !isActive(this.state) || this.isMenuDue) { + if (!this.isMenuPending()) { return; } - if (this.isBehindInput()) { - this.isMenuWaiting = true; - // On the arena's clock, like the hold's own deadlines. - this.setTimer(this.now() + LATE_MOVE_GAP_MS, () => this.showMenu()); + if (this.hasLateMove()) { + this.waitForMoves(); return; } this.presentMenu(); } + private isMenuPending(): boolean { + return this.holdFrom != null && isActive(this.state) && !this.isMenuDue; + } + + private waitForMoves(): void { + this.isMenuWaiting = true; + // On the arena's clock, like the hold's own deadlines. It counts from when + // the page runs again. Behind a block, the event clock still reads the + // moment, and moves stamped after it are still queued. + const from = Math.max(this.now(), performance.now()); + this.setTimer(from + LATE_MOVE_GAP_MS, () => this.endMoveWait()); + } + private presentMenu(): void { this.stopMoveWait(); this.isMenuDue = true; @@ -246,20 +278,17 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } /** - * Whether the page may still hold moves from before the menu's moment. A - * move from before it reached the page in the last `LATE_MOVE_GAP_MS`, and - * that move or the moment's timer ran more than `LATE_INPUT_MS` late. + * Whether a move from before the menu's moment reached the page in the last + * `LATE_MOVE_GAP_MS`, more than `LATE_INPUT_MS` after its own time. */ - private isBehindInput(): boolean { + private hasLateMove(): boolean { const move = this.latestMove; - const moment = this.holdStart + menuDisplayMs; const now = performance.now(); return ( move != null && - move.time < moment && + move.time < this.holdStart + menuDisplayMs && now - move.arrivedAt < LATE_MOVE_GAP_MS && - (move.arrivedAt - move.time > LATE_INPUT_MS || - now - moment > LATE_INPUT_MS) + move.arrivedAt - move.time > LATE_INPUT_MS ); } From d7439227a9522e8b3c1c604c5a0a1972ded277df Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 17:14:58 -0800 Subject: [PATCH 037/151] test(ContextMenu): the press's page time comes from the arena's clock The press's units drive the page's time with the gesture arena's own injected clock, the test harness's manual clock, instead of faking performance.now(). A move can reach the page after its own time, and a blocked page runs the menu's timer late on that clock. A blocked main thread until 900 ms now shows the still finger's menu at 950 ms. --- .../src/ContextMenu/contextMenuPress.test.ts | 317 ++++++++---------- .../core/src/gestures/__tests__/harness.ts | 20 +- 2 files changed, 153 insertions(+), 184 deletions(-) diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index b2f979513a0e8..324e11d6e7a12 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -13,7 +13,7 @@ * @position Unit tests of packages/core/src/ContextMenu/contextMenuPress.ts */ -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {describe, expect, it} from 'vitest'; import {createHarness} from '../gestures/__tests__/harness'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -33,24 +33,7 @@ function setup( return {harness, press, states}; } -/** - * Runs `body` with the page's clock (`performance.now()`), which every case - * fakes from 0. `at(time)` moves it to when the page gets the next input, - * which may be after the time the input came with. - */ -function withPageClock(body: (at: (time: number) => void) => void): void { - body(time => vi.advanceTimersByTime(time - performance.now())); -} - describe('ContextMenuPressRecognizer', () => { - // The page's clock starts with the harness's, so no case runs late by it. - beforeEach(() => { - vi.useFakeTimers({toFake: ['performance']}); - }); - afterEach(() => { - vi.useRealTimers(); - }); - it('commits at UIKit’s moment (iOS 26.2: 400 ms, first 60 Hz tick 417 ms), not a millisecond before', () => { const {harness, press, states} = setup(); harness.finger(1).down(100, 200, 1000, {recognizers: [press]}); @@ -66,10 +49,13 @@ describe('ContextMenuPressRecognizer', () => { const {harness, press, states} = setup(); harness.finger(1).down(0, 0, 0, {recognizers: [press]}); // Nothing ran until 900 ms (a blocked main thread): the press still - // began at 400, and the menu was due at 735. + // began at 400. The menu's timer ran late, so it waits 50 ms for moves + // queued behind the block, and none came. harness.advance(900); - expect(states).toEqual([`began@${COMMIT}`, `changed@${DISPLAY}`]); + expect(states).toEqual([`began@${COMMIT}`]); expect(press.beganAt).toBe(COMMIT); + harness.advance(950); + expect(states).toEqual([`began@${COMMIT}`, 'changed@950']); }); it('claims the finger at the commit and drops the lift’s click', () => { @@ -115,192 +101,167 @@ describe('ContextMenuPressRecognizer', () => { }); it('waits at the menu’s moment for moves that came before it but reach the page late, and a drift in them cancels', () => { - withPageClock(at => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - // The page gets a move from 450 ms only at 700 ms: it is behind. - at(700); - finger.move(3, 0, 450); - at(DISPLAY); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // A late move that came at 600 ms, 14 px over. The arena holds its time - // at the clock, and the recognizer reads the time it came with. - at(DISPLAY + 10); - finger.move(14, 0, 600); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `cancelled@${DISPLAY}`, - ]); - expect(press.isMenuDue).toBe(false); - finger.up(DISPLAY + 300); - }); + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // The page gets a move from 450 ms only at 700 ms: it is behind. + finger.move(3, 0, 450, undefined, 700); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // A late move that came at 600 ms, 14 px over. The arena holds its time + // at the clock, and the recognizer reads the time it came with. + finger.move(14, 0, 600, undefined, DISPLAY + 10); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `cancelled@${DISPLAY}`, + ]); + expect(press.isMenuDue).toBe(false); + finger.up(DISPLAY + 300); }); it('shows the menu for a move stamped from its moment on, even past the tolerance, and lets the finger move freely after', () => { - withPageClock(at => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - at(700); - finger.move(3, 0, 450); - at(DISPLAY); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // Inside the tolerance at the moment, 14 px over 15 ms after it. - at(DISPLAY + 20); - finger.move(14, 0, DISPLAY + 15); - expect(press.isMenuDue).toBe(true); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `changed@${DISPLAY + 15}`, - `changed@${DISPLAY + 15}`, - ]); - finger.up(DISPLAY + 300); - }); + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 450, undefined, 700); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // Inside the tolerance at the moment, 14 px over 15 ms after it. + finger.move(14, 0, DISPLAY + 15, undefined, DISPLAY + 20); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `changed@${DISPLAY + 15}`, + `changed@${DISPLAY + 15}`, + ]); + finger.up(DISPLAY + 300); }); it('judges each coalesced sample of a late move at its own time while the menu waits', () => { - withPageClock(at => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - at(700); - finger.move(3, 0, 450); - at(DISPLAY); - harness.advance(DISPLAY); - // One late move with two samples: 13 px at 725 ms, before the moment, - // then 14 px at 740 ms. Two separate moves would end the hold at the - // first, so this one does too. - at(DISPLAY + 20); - finger.move(14, 0, DISPLAY + 5, [{x: 13, y: 0, time: DISPLAY - 10}]); - expect(press.isMenuDue).toBe(false); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `cancelled@${DISPLAY + 5}`, - ]); - }); + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 450, undefined, 700); + harness.advance(DISPLAY); + // One late move with two samples: 13 px at 725 ms, before the moment, + // then 14 px at 740 ms. Two separate moves would end the hold at the + // first, so this one does too. + finger.move( + 14, + 0, + DISPLAY + 5, + [{x: 13, y: 0, time: DISPLAY - 10}], + DISPLAY + 20, + ); + expect(press.isMenuDue).toBe(false); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@450', + `cancelled@${DISPLAY + 5}`, + ]); }); it('shows the waiting menu for a coalesced move whose samples before the moment stay inside the tolerance', () => { - withPageClock(at => { - const {harness, press} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - at(700); - finger.move(3, 0, 450); - at(DISPLAY); - harness.advance(DISPLAY); - at(DISPLAY + 20); - finger.move(14, 0, DISPLAY + 5, [{x: 10, y: 0, time: DISPLAY - 10}]); - expect(press.isMenuDue).toBe(true); - finger.up(DISPLAY + 300); - }); + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 450, undefined, 700); + harness.advance(DISPLAY); + finger.move( + 14, + 0, + DISPLAY + 5, + [{x: 10, y: 0, time: DISPLAY - 10}], + DISPLAY + 20, + ); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); }); for (const blockedUntil of [760, 800, 900]) { it(`judges a coalesced move from behind a block until ${blockedUntil} ms before the menu shows`, () => { - withPageClock(at => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - // On time until 640 ms. Then the page is blocked past the moment. - at(640); - finger.move(3, 0, 640); - // The finger crossed 11.5 px at 650 ms. Its moves wait behind the - // block and come as one coalesced move. - at(blockedUntil); - finger.move(14, 0, blockedUntil - 5, [ + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // On time until 640 ms. Then the page is blocked past the moment. + finger.move(3, 0, 640); + // The finger crossed 11.5 px at 650 ms. Its moves wait behind the block + // and come as one coalesced move. + finger.move( + 14, + 0, + blockedUntil - 5, + [ {x: 13, y: 0, time: 650}, {x: 14, y: 0, time: 700}, - ]); - expect(press.isMenuDue).toBe(false); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@640', - `cancelled@${blockedUntil - 5}`, - ]); - }); + ], + blockedUntil, + ); + expect(press.isMenuDue).toBe(false); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@640', + `cancelled@${blockedUntil - 5}`, + ]); }); } it('shows a still finger’s menu after a block, once no move comes from behind it', () => { - withPageClock(at => { - const {harness, press} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - // The moment's timer runs 65 ms late behind a block. - at(DISPLAY + 65); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - at(DISPLAY + 115); - harness.advance(DISPLAY + 115); - expect(press.isMenuDue).toBe(true); - finger.up(DISPLAY + 300); - }); + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + // The moment's timer runs 65 ms late behind a block. + harness.advance(DISPLAY, DISPLAY + 65); + expect(press.isMenuDue).toBe(false); + harness.advance(DISPLAY + 115); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); }); it('shows the menu once the late moves pause for 50 ms', () => { - withPageClock(at => { - const {harness, press} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - at(700); - finger.move(3, 0, 450); - at(DISPLAY); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // The wait runs on the arena's clock. - at(DISPLAY + 49); - harness.advance(DISPLAY + 49); - expect(press.isMenuDue).toBe(false); - at(DISPLAY + 50); - harness.advance(DISPLAY + 50); - expect(press.isMenuDue).toBe(true); - finger.up(DISPLAY + 300); - }); + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 450, undefined, 700); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(false); + // The wait runs on the arena's clock. + harness.advance(DISPLAY + 49); + expect(press.isMenuDue).toBe(false); + harness.advance(DISPLAY + 50); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); }); it('shows the menu at its moment after a move that reached the page on time, with no wait', () => { - withPageClock(at => { - const {harness, press, states} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - // A 3 px shift at 720 ms that the page gets at once: it is not behind. - at(720); - finger.move(3, 0, 720); - at(DISPLAY); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(true); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@720', - `changed@${DISPLAY}`, - ]); - }); + const {harness, press, states} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + // A 3 px shift at 720 ms that the page gets at once: it is not behind. + finger.move(3, 0, 720); + harness.advance(DISPLAY); + expect(press.isMenuDue).toBe(true); + expect(states).toEqual([ + `began@${COMMIT}`, + 'changed@720', + `changed@${DISPLAY}`, + ]); }); it('waits at the menu’s moment when its own timer runs late after a recent move', () => { - withPageClock(at => { - const {harness, press} = setup(); - const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); - at(730); - finger.move(3, 0, 730); - // The page is busy: the moment's timer runs 40 ms late, so later moves - // may still be queued. - at(DISPLAY + 40); - harness.advance(DISPLAY); - expect(press.isMenuDue).toBe(false); - // No more moves came: the wait ends 50 ms after the late timer ran. - at(DISPLAY + 90); - harness.advance(DISPLAY + 90); - expect(press.isMenuDue).toBe(true); - finger.up(DISPLAY + 300); - }); + const {harness, press} = setup(); + const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.advance(COMMIT); + finger.move(3, 0, 730); + // The page is busy: the moment's timer runs 40 ms late, so later moves + // may still be queued. + harness.advance(DISPLAY, DISPLAY + 40); + expect(press.isMenuDue).toBe(false); + // No more moves came: the wait ends 50 ms after the late timer ran. + harness.advance(DISPLAY + 90); + expect(press.isMenuDue).toBe(true); + finger.up(DISPLAY + 300); }); it('shows a still finger’s menu at its moment, with no wait', () => { diff --git a/packages/core/src/gestures/__tests__/harness.ts b/packages/core/src/gestures/__tests__/harness.ts index 5b9c46c2681ce..3e7fecf58ff86 100644 --- a/packages/core/src/gestures/__tests__/harness.ts +++ b/packages/core/src/gestures/__tests__/harness.ts @@ -83,8 +83,11 @@ export interface Harness { view?: {left?: number; top?: number; width: number; height: number}; }; finger(id: number): Finger; - /** Advance the clock and run every timer due by `time`. */ - advance(time: number): void; + /** + * Advance the clock and run every timer due by `time`. `runsAt`: when the + * page runs those timers on the clock, later behind a block. + */ + advance(time: number, runsAt?: number): void; } export function createHarness(): Harness { @@ -139,8 +142,8 @@ export function createHarness(): Harness { } return finger; }, - advance: time => { - clock.time = time; + advance: (time, runsAt = time) => { + clock.time = runsAt; arena.advanceTime(time); }, }; @@ -190,17 +193,22 @@ export class Finger { return this; } - /** `history`: the coalesced samples before this one, oldest first. */ + /** + * `history`: the coalesced samples before this one, oldest first. + * `arrivesAt`: when the page gets the move on the clock, for a move that + * reaches it after its own time. + */ move( x: number, y: number, time: number, history?: ReadonlyArray, + arrivesAt = time, ): this { this.x = x; this.y = y; this.time = time; - this.harness.clock.time = time; + this.harness.clock.time = arrivesAt; this.harness.arena.moved([ {id: this.id, x, y, time, ...(history == null ? {} : {history})}, ]); From cae3644e6c5569e3ac09bdb775420cfd487dc891 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 17:14:58 -0800 Subject: [PATCH 038/151] fix(ContextMenu): the press reads the page's time from the arena The press measured how late a move or its timer ran with performance.now(). It now reads the gesture arena's injected clock, whose new pageTime() returns the clock's own reading. In a browser that clock is performance.now(), so nothing changes there; the units drive it with the test harness's manual clock. --- packages/core/src/ContextMenu/contextMenuPress.ts | 13 +++++++++---- packages/core/src/gestures/GestureArena.ts | 8 ++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index 2084d06856f76..f62761fd92bc0 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -153,7 +153,7 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { protected override touchesMoved(touches: ReadonlyArray): void { const touch = touches.find(each => each.id === this.pressTouchId); if (touch != null) { - this.latestMove = {time: touch.inputTime, arrivedAt: performance.now()}; + this.latestMove = {time: touch.inputTime, arrivedAt: this.pageTime()}; } const hasDrifted = touch != null && !this.followHold(touch); if (hasDrifted && this.state === 'possible') { @@ -238,7 +238,7 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { return; } const moment = this.holdStart + menuDisplayMs; - if (performance.now() - moment > LATE_TIMER_MS || this.hasLateMove()) { + if (this.pageTime() - moment > LATE_TIMER_MS || this.hasLateMove()) { this.waitForMoves(); return; } @@ -267,10 +267,15 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { // On the arena's clock, like the hold's own deadlines. It counts from when // the page runs again. Behind a block, the event clock still reads the // moment, and moves stamped after it are still queued. - const from = Math.max(this.now(), performance.now()); + const from = Math.max(this.now(), this.pageTime()); this.setTimer(from + LATE_MOVE_GAP_MS, () => this.endMoveWait()); } + /** When the page runs now, on the arena's injected clock. */ + private pageTime(): number { + return this.arena?.pageTime() ?? this.now(); + } + private presentMenu(): void { this.stopMoveWait(); this.isMenuDue = true; @@ -283,7 +288,7 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { */ private hasLateMove(): boolean { const move = this.latestMove; - const now = performance.now(); + const now = this.pageTime(); return ( move != null && move.time < this.holdStart + menuDisplayMs && diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index d9a353fad7ab1..6a0cf0887a85f 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -181,6 +181,14 @@ export class GestureArena { return this.currentTime ?? Math.max(this.latestTime, this.clock.now()); } + /** + * The injected clock's own reading: when the page runs now. Behind a block, + * the event clock lags it. + */ + pageTime(): number { + return this.clock.now(); + } + /** Whether a recognizer owns this touch, so the browser must not pan or zoom it. */ isClaimed(id: number): boolean { return this.records.get(id)?.isClaimed === true; From 17cab2a6ded6d92f91ca8fa778550b663d8106cd Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 10 Nov 2026 17:55:39 -0800 Subject: [PATCH 039/151] test(ContextMenu): the stays-put case reads the menu as laid out The menu's entrance plays as a transform on its layer. A slow first frame, such as WebKit's on a cold shader cache, can hold that transform at its start when the case first reads the menu. The case now reads the menu's laid-out position, which an anchor that moved the menu still changes and the entrance does not. --- ...extMenuLongPress.interaction.browser.spec.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 55564a42b8069..0ff362ce4939d 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -955,7 +955,9 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil } const menu = page.getByRole('menu', {name: 'Photo actions'}); // The cursor anchor (the trigger's last child), on screen and as laid out - // (engines differ on which one anchor positioning reads), and the menu. + // (engines differ on which one anchor positioning reads). The menu as laid + // out. Its entrance plays as a transform on its layer, and a slow first frame + // (a cold shader cache) can hold it at its start. const read = async () => trigger.evaluate(el => { const anchor = el.lastElementChild as HTMLElement | null; @@ -964,9 +966,8 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil const left = box.left + (box.width - host.offsetWidth) / 2; const top = box.top + (box.height - host.offsetHeight) / 2; const onScreen = anchor?.getBoundingClientRect(); - const list = document - .querySelector('[role="menu"]') - ?.getBoundingClientRect(); + const list = document.querySelector('[role="menu"]'); + const layer = list?.closest('[popover]'); return { onScreen: onScreen == null ? null : {x: onScreen.x, y: onScreen.y}, laidOut: @@ -976,7 +977,13 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil x: left + host.clientLeft + anchor.offsetLeft, y: top + host.clientTop + anchor.offsetTop, }, - menu: list == null ? null : {x: list.x, y: list.y}, + menu: + list == null || layer == null + ? null + : { + x: layer.offsetLeft + list.offsetLeft, + y: layer.offsetTop + list.offsetTop, + }, }; }); // The middle of the card and near its far corner, where an anchor placed From 6db12ac9e276a513fe490033cf0031486b7a48d6 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 01:40:51 -0800 Subject: [PATCH 040/151] docs(useMenuPress): name continueGesture in the handoff row FR11's row names the member of useMenuPress's return through which an opener hands its held pointer to the menu. --- docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md index 0036c515ee46c..f48495e165f74 100644 --- a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md +++ b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md @@ -163,7 +163,7 @@ Consumer migration instructions belong in consumer docs and release notes. | FR8 | On a mouse a DropdownMenu trigger MUST open its menu on press-down (button 0, no Control), and a drag from the trigger into the menu that releases over an enabled row MUST act on it. The opening gesture's release MUST act only if the pointer entered the menu or the press lasted the settle time; otherwise nothing acts and the menu stays open. Pressing the trigger of an open menu MUST close it and MUST NOT reopen it in the same gesture. A mouse pointer handed to the menu as it opens (FR11) follows the same settle rule. | Proposed DEC-4; `DropdownMenu.test.tsx` press model suite, `menuPressGesture.test.ts` trigger states | proposed; pending owner review | | FR9 | Opening a menu from its trigger under a finger and the opening finger's handoff are governed by `spec:AST-094` FR29, under every primary pointer (`spec:AST-094` FR43). | `spec:AST-094` FR29 | as `spec:AST-094` states | | FR10 | A finger released on a sub-menu's row MUST open that sub-menu, as the row's own click would (the lift acts, `spec:AST-094` FR26; on a compact touch screen an `adaptive` row drills in, FR34); a finger resting on the row MUST NOT open it. A finger that slides from a row onto the rows of an open flyout picks there under ORD1. | DEC-8; `DropdownMenuSubMenu.test.tsx` press cases | verify | -| FR11 | A pointer that went down elsewhere, such as a context menu's long press, and is handed to the menu as it opens MUST be the opening press. Under every primary pointer, a finger picks only after the handoff distance, counted from the first position the menu sees after it opened as `spec:AST-094` FR33 counts it, and its lift before that acts on nothing and leaves the menu open. | DEC-8; `useMenuPress.test.tsx` continuation suite | verify | +| FR11 | A pointer that went down elsewhere, such as a context menu's long press, and is handed to the menu as it opens MUST be the opening press. Under every primary pointer, a finger picks only after the handoff distance, counted from the first position the menu sees after it opened as `spec:AST-094` FR33 counts it, and its lift before that acts on nothing and leaves the menu open. The opener hands the pointer over through `continueGesture` on `useMenuPress`'s return. | DEC-8; `useMenuPress.test.tsx` continuation suite | verify | ### Transformation and precedence order From 4e93b5f5b453daf1b2d8211c6bce064c38b64385 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 01:57:13 -0800 Subject: [PATCH 041/151] refactor(ContextMenu): a private mark finds the trigger, not a registry The press feedback kept every mounted trigger in a module-level set to find the trigger a press mark belongs to. Each trigger now carries the private context-menu-trigger attribute while its press feedback is attached, and closest() finds it. The attribute's owner module is privateAttributes/contextMenuTrigger.stylex.ts. --- .../ContextMenu/contextMenuPressFeedback.ts | 42 +++++++------------ .../contextMenuTrigger.stylex.ts | 27 ++++++++++++ 2 files changed, 42 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index 7f6c4462cc450..f05de1af2fc0c 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -5,8 +5,9 @@ /** * @file contextMenuPressFeedback.ts * @input UIKit's context-menu springs, the context-menu constants, the - * compositor animator, the presses ContextMenu's recognizer takes, and the - * press state core's press machine writes + * compositor animator, the presses ContextMenu's recognizer takes, the + * press state core's press machine writes, and the context-menu-trigger + * mark (privateAttributes/contextMenuTrigger.stylex.ts) * @output useContextMenuPressFeedback: hold and release, from ContextMenu's * menu; the growth follows the recognizer's finger, or a pen's press mark * @position The press feedback of ContextMenu's touch invocation @@ -28,6 +29,10 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useAttachment} from '../hooks/useAttachment'; import {usePressFeedback} from '../hooks/usePressFeedback'; +import { + closestContextMenuTrigger, + markContextMenuTrigger, +} from '../privateAttributes/contextMenuTrigger.stylex'; import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; import {PRESS_ONSET_MS} from '../utils/pressGesture'; import {observeMutations} from '../utils/sharedMutationObserver'; @@ -69,11 +74,6 @@ const NO_LANDING: RefObject<() => number | null> = {current: () => null}; /** With no recognizer to ask, every "on" is a pen's. */ const NO_FINGER: RefObject<() => boolean> = {current: () => false}; -// The triggers a press mark belongs to: every mounted trigger, whether it -// shows growth or not. A mark inside a trigger belongs to the nearest of them -// at or above it. So a press on a nested trigger grows no outer trigger. -const pressMarkOwners = new WeakSet(); - /** * Calls `onDue` in the first animation frame that runs at or after `dueAt`, on * the event clock, with the time its callback runs. `onWait` runs in each frame @@ -100,19 +100,6 @@ function watchFramesFrom( }; } -function pressMarkOwnerOf(marked: Element): Element | null { - for ( - let node: Element | null = marked; - node != null; - node = node.parentElement - ) { - if (pressMarkOwners.has(node)) { - return node; - } - } - return null; -} - /** * The press feedback of a ContextMenu trigger. `isShown` is read at each * press: false for an inline trigger. It follows the press mark on the @@ -277,16 +264,17 @@ export function useContextMenuPressFeedback( useAttachment( triggerRef, element => { - pressMarkOwners.add(element); + // Every mounted trigger is marked, whether it shows growth or not. A + // press mark belongs to the nearest trigger at or above it, so a press + // on a nested trigger grows no outer trigger. + const unmark = markContextMenuTrigger(element); if (!isShown) { - return () => { - pressMarkOwners.delete(element); - }; + return unmark; } const isMarkedOn = () => element.getAttribute(PRESSED_ATTRIBUTE) === 'on' || [...element.querySelectorAll(`[${PRESSED_ATTRIBUTE}="on"]`)].some( - marked => pressMarkOwnerOf(marked) === element, + marked => closestContextMenuTrigger(marked) === element, ); let isPressed = isMarkedOn(); let markedAt = 0; @@ -319,7 +307,7 @@ export function useContextMenuPressFeedback( }; fingerOnsetRef.current = (landed, target) => { // A finger on a nested trigger grows only that trigger. - if (target != null && pressMarkOwnerOf(target) !== element) { + if (target != null && closestContextMenuTrigger(target) !== element) { return; } startAt(landed + PRESS_ONSET_MS); @@ -349,7 +337,7 @@ export function useContextMenuPressFeedback( stopOnset(); stopObserving(); fingerOnsetRef.current = null; - pressMarkOwners.delete(element); + unmark(); }; }, isShown, diff --git a/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts new file mode 100644 index 0000000000000..fb57645f753b2 --- /dev/null +++ b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts @@ -0,0 +1,27 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/contextMenuTrigger.stylex.ts + * @input A ContextMenu trigger whose touch press feedback is attached + * @output markContextMenuTrigger, which marks the trigger, and + * closestContextMenuTrigger, which finds the trigger at or above an element + * @position Owner module of the private context-menu-trigger attribute: the + * only file that writes its name. ContextMenu's press feedback + * (ContextMenu/contextMenuPressFeedback.ts) marks its trigger and finds the + * trigger a press belongs to. No package entry exports it. + */ + +const CONTEXT_MENU_TRIGGER = 'data-astryx-context-menu-trigger'; + +/** Marks `trigger` as a ContextMenu trigger. The returned call unmarks it. */ +export function markContextMenuTrigger(trigger: Element): () => void { + trigger.setAttribute(CONTEXT_MENU_TRIGGER, ''); + return () => { + trigger.removeAttribute(CONTEXT_MENU_TRIGGER); + }; +} + +/** The ContextMenu trigger at or above `element`, or null outside one. */ +export function closestContextMenuTrigger(element: Element): Element | null { + return element.closest(`[${CONTEXT_MENU_TRIGGER}]`); +} From f908089c3988263394ce2fab1254a2b8ee2c0d26 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 02:00:22 -0800 Subject: [PATCH 042/151] docs(ContextMenu): name the context-menu-trigger mark's owner The Ownership section names the private attribute's owner module, its writer and its closest reader. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 66321187e4214..9f68299d070a8 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -77,6 +77,11 @@ Consumer migration instructions belong in consumer docs and release notes. `context-menu` target. - Cursor-anchor placement across the two presentation paths, and open state (FR10). +- The private context-menu-trigger attribute and its owner module, + `privateAttributes/contextMenuTrigger.stylex.ts`: `markContextMenuTrigger` + marks a trigger while its touch press feedback is attached, and + `closestContextMenuTrigger` finds the trigger a press belongs to, so a press + on a nested trigger grows no outer trigger. **Does not own / non-goals** From b8301814f1584264e0b4ec6cc2447d04a1bcb58e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 02:32:51 -0800 Subject: [PATCH 043/151] docs(ContextMenu): the Chinese summary says slide to pick, too The Chinese summary gains the slide-to-pick sentence the English one has. A comment that only restated continueGesture goes. --- packages/core/src/ContextMenu/ContextMenu.doc.mjs | 2 +- packages/core/src/ContextMenu/ContextMenu.tsx | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs index 26fbc9e526aac..0d90d5f3a7f5d 100644 --- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs +++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -228,7 +228,7 @@ export const docs = { export const docsZh = { usage: { description: - '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在主指针为粗指针(触摸屏)时,按住手指即可打开,时序与 iOS 相同:150 毫秒时块级触发区域(菜单在手指处打开时)开始放大,735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。', + '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在主指针为粗指针(触摸屏)时,按住手指即可打开,时序与 iOS 相同:150 毫秒时块级触发区域(菜单在手指处打开时)开始放大,735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。当菜单在手指处打开时,同一根手指可以滑到某个操作上,抬起即可选择。', bestPractices: [ {guidance: true, description: '保持菜单项简洁和面向操作。'}, {guidance: true, description: '有很多项时使用分组和分隔线。'}, diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index c84468051833c..1d4723a19e81e 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -796,9 +796,6 @@ export function ContextMenu({ // the menu, so it does not close it. openingGestureRef.current = currentGesture(); openAtLocalPoint(local.x, local.y, triggerRef.current, 'menu'); - // A finger still down goes on into the menu as its opening press: it - // slides onto an item, and its lift selects it. A lift over no item - // leaves the menu open. if (held != null) { continueGesture({...held, time: Date.now()}); } From 03eb7d768dc7bd748f27cfe7e1932c2cd6776e7d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 00:47:10 -0800 Subject: [PATCH 044/151] refactor(ContextMenu): the touch layer imports its recognizer directly ContextMenuTouch.ts only re-exported the press recognizer for the touch layer, its one importer. The layer now imports contextMenuPress.ts. --- packages/core/src/ContextMenu/ContextMenu.tsx | 2 +- .../core/src/ContextMenu/ContextMenuTouch.ts | 17 ----------------- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 4 ++-- 3 files changed, 3 insertions(+), 20 deletions(-) delete mode 100644 packages/core/src/ContextMenu/ContextMenuTouch.ts diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 9af4297f24e84..85e569735845d 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -38,7 +38,7 @@ * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs * - /packages/core/src/ContextMenu/ContextMenu.test.tsx - * - /packages/core/src/ContextMenu/ContextMenuTouch.ts (the touch layer's one import site) + * - /packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx (the touch layer) * - /packages/core/src/ContextMenu/contextMenuPress.ts (touch timeline) * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx diff --git a/packages/core/src/ContextMenu/ContextMenuTouch.ts b/packages/core/src/ContextMenu/ContextMenuTouch.ts deleted file mode 100644 index f8f22f0b96c95..0000000000000 --- a/packages/core/src/ContextMenu/ContextMenuTouch.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Meta Platforms, Inc. and affiliates. - -'use client'; - -/** - * @file ContextMenuTouch.ts - * @input ContextMenu's touch modules - * @output ContextMenu's touch layer, its one import site: the press - * recognizer (contextMenuPress.ts) - * @position ContextMenuTouchLayer.tsx, which ContextMenu renders under the - * touch model, imports its touch behaviour from here only; the mouse and - * keyboard paths stay in ContextMenu.tsx - * - * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx - */ - -export {ContextMenuPressRecognizer} from './contextMenuPress'; diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index a42432403acf2..30d47b133048f 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -4,7 +4,7 @@ /** * @file ContextMenuTouchLayer.tsx - * @input ContextMenu's touch layer (ContextMenuTouch.ts), the gesture + * @input ContextMenu's press recognizer (contextMenuPress.ts), the gesture * foundation and the UIKit context-menu constants * @output ContextMenuTouchLayer: renders nothing; runs the trigger's press * recognizer while ContextMenu is under the touch model @@ -18,7 +18,7 @@ import {flushSync} from 'react-dom'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {contextMenu} from '../motion/uikit/contextMenu'; -import {ContextMenuPressRecognizer} from './ContextMenuTouch'; +import {ContextMenuPressRecognizer} from './contextMenuPress'; /** What ContextMenu reaches of a mounted touch layer. */ export interface ContextMenuTouchHandle { From f37d633d4c748125cfb07489674344560f7a4815 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 01:51:17 -0800 Subject: [PATCH 045/151] test(ContextMenu): a drift queued behind a block still ends the hold A finger crosses 11.5 px at 700 ms while the page is blocked from 600 ms to 850 ms, so its move reaches the page after the menu's moment. The hold must still end, with no menu. The case checks that the move reached the page behind the block and within the press's 50 ms wait. --- ...tMenuLongPress.interaction.browser.spec.ts | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index df976edbcfc5b..359dc9de1d1a0 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -20,6 +20,7 @@ import { type Page, } from '@astryxdesign/a11y-spec/playwright'; import { + blockMainThread, drag, FRAME_STARVATION_MS, FrameStarvationError, @@ -417,6 +418,95 @@ test('a slow drift past 11.5 px late in the hold cancels it: no menu and no clic } }); +test('a drift from before 735 ms that reaches the page behind a block still cancels the hold: no menu (AST-094 FR16)', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'touches stamped and sent while the page is blocked need Chromium’s protocol', + ); + // Each move's own time, and when the page got it. + await page.addInitScript(() => { + const w = window as unknown as {__moves: [number, number][]}; + w.__moves = []; + window.addEventListener( + 'pointermove', + event => { + w.__moves.push([event.timeStamp, performance.now()]); + }, + {capture: true, passive: true}, + ); + }); + const {center} = await openTouchStory(page); + const cdp = await page.context().newCDPSession(page); + const start = Date.now(); + const at = async (ms: number) => + new Promise(resolve => { + setTimeout(resolve, Math.max(0, start + ms - Date.now())); + }); + const touch = async ( + type: 'touchStart' | 'touchMove' | 'touchEnd', + ms: number, + dx: number | null, + ) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: dx == null ? [] : [{x: center.x + dx, y: center.y}], + timestamp: (start + ms) / 1000, + }); + await touch('touchStart', 0, 0); + // The page is blocked from 600 ms to 850 ms, past the menu's moment. The + // finger crosses 11.5 px at 700 ms, so the page gets that move after the + // block. + await at(600); + const blocking = blockMainThread(page, 250); + await at(650); + const moves = [touch('touchMove', 650, 6)]; + await at(700); + moves.push(touch('touchMove', 700, 14)); + const blocked = await blocking; + await Promise.all(moves); + await at(1150); + await touch('touchEnd', 1150, null); + await afterTwoFrames(page); + const moment = (await touchStartedAt(page)) + menuDisplayMs; + const origin = await page.evaluate(() => performance.timeOrigin); + const blockEnd = blocked.to - origin; + expect( + blocked.from - origin, + 'the block starts before the menu’s moment', + ).toBeLessThan(moment); + expect(blockEnd, 'the block ends after the menu’s moment').toBeGreaterThan( + moment, + ); + const early = ( + await page.evaluate( + () => (window as unknown as {__moves: [number, number][]}).__moves, + ) + ).filter(([time]) => time < moment); + expect( + early.length, + 'a move from before the menu’s moment reached the page', + ).toBeGreaterThan(0); + for (const [, receivedAt] of early) { + expect( + receivedAt, + 'the move reached the page after the block', + ).toBeGreaterThanOrEqual(blockEnd); + // The press waits 50 ms for moves still queued. + expect( + receivedAt - blockEnd, + 'the move reached the page within the press’s wait', + ).toBeLessThan(50); + } + expect( + await menuShownAt(page), + 'the menu showed for a drift from before its moment', + ).toBeNull(); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); +}); + test('a finger still inside 11.5 px at the menu’s moment that crosses it just after still gets the menu (AST-094 FR12)', async ({ page, }) => { From 8575ec71b84f00843cd95f8e8d0ded62eda8e44a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 02:07:31 -0800 Subject: [PATCH 046/151] docs(records): why the press keeps its own wait, and outsidePress types AST-094's current state says why the press keeps a 50 ms wait beside the arena's one-task yield, and names the arena's page time and the touch fields the press reads. The FR16 gap line stays as it was. Layer runtime's outsidePress owner line names ContextMenu's watch and its pressTypes option. --- docs/architecture/layer-runtime.md | 6 ++++-- docs/specs/AST-094-touch-presentations/spec.md | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 356f2a2210748..56c0fcc0613e9 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -820,8 +820,10 @@ it on the surface inside the layer and run no layout while it plays. touch-only outside listener for Tooltip/HoverCard. - `Layer/outsidePress.ts` owns the outside-press watch for a text field's manual layer, used by BaseTypeahead, DateInput, DateTimeInput and - ChatComposerInput's trigger menu, and the per-document count of outside - closes that a modal backdrop press reads (`family:overlay-dismissal` FR11). + ChatComposerInput's trigger menu, and for ContextMenu's menu, which judges + a mouse's or a pen's press as it goes down (`pressTypes`). It also owns the + per-document count of outside closes that a modal backdrop press reads + (`family:overlay-dismissal` FR11). - `DropdownMenuContext` and `DropdownMenuSubMenu` own the current local menu-cascade parent-close chain. - Dialog families own native modal/backdrop presentation and their local channel diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 201c4232848e3..6ec91e8aec18f 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -1041,6 +1041,10 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and frame late, the menu waits up to 50 ms for moves still queued. A move from before the moment that reaches the page more than two frames late holds it the same way. +- Two waits: the arena's yield covers one task; the press's 50 ms covers moves + Chromium queues past the task and frame (FR16). The press reads when the page + runs from the arena (`pageTime()`), and each touch carries the time and + samples of the input that moved it (`inputTime`, `inputSamples`). - Consumer docs: none until a component ships its touch presentation; each component documents its own, including the `presentation` value that keeps the released surface (FR25). From 22ae97e26191a36435c2b15fe5e2f83b4008bce1 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 02:38:11 -0800 Subject: [PATCH 047/151] docs(ContextMenu): name the measured table and the moved default The record now links motion/uikit/contextMenu.ts, the context menu's measured UIKit table, by path. Its public-contract line says that an omitted presentation means the touch model under a coarse pointer, with presentation="popover" as the way back, instead of no change. --- .../ContextMenu/ContextMenu.spec.md | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index c01fca1ee48c0..7adec14d50e81 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -34,17 +34,25 @@ system_specs: [spec:AST-094, spec:AST-107] # ContextMenu component contract + + +```json +{ + "paths": ["packages/core/src/motion/uikit/contextMenu.ts"] +} +``` + ## Contract at a glance -| Area | Contract | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Public contract | None changes. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | -| Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | -| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger; mouse and keyboard opens keep today's look. | -| Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | -| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow and trigger lift (FR5) are listed under Current-state impact. | -| Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | -| Governing rules | `spec:AST-107` FR8; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `family:overlay-dismissal`; `architecture:component-theming-surface`; `architecture:layer-runtime`. | +| Area | Contract | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Public contract | One default moves: under a coarse primary pointer, an omitted `presentation` means the touch model (`spec:AST-094` FR25), and `presentation="popover"` keeps the released surface. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | +| Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | +| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger; mouse and keyboard opens keep today's look. | +| Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | +| Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow and trigger lift (FR5) are listed under Current-state impact. | +| Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | +| Governing rules | `spec:AST-107` FR8; `spec:AST-094` FR26–FR35; `module:DropdownMenu/useMenuPress`; `family:overlay-dismissal`; `architecture:component-theming-surface`; `architecture:layer-runtime`. | This table is a review projection; the body below is authoritative. From 56b2f621a44a1b3323be4fa46f79a2b3ce0463aa Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 04:05:56 -0800 Subject: [PATCH 048/151] test(ContextMenu): a finger in a second document on its own clock A ContextMenu rendered into a same-origin iframe gets a 120 ms tap stamped on that window's clock. It must open no menu and keep its click. The gesture host reads each document's own clock since the second-document clock fix. --- .../core/src/ContextMenu/ContextMenu.test.tsx | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index 40ab42f49e959..aeb0c1705db1b 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -2514,6 +2514,78 @@ describe('ContextMenu outside dismissal', () => { fireEvent.mouseDown(outside); expect(onOpenChange).toHaveBeenLastCalledWith(false); }); + + it('times a finger on the second document’s own clock: a short tap opens no menu and keeps its click', () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'], + }); + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + const view = secondDocument.defaultView as Window & typeof globalThis; + // The frame opened after the page, so its clock reads 5 s less. Its + // events come stamped on that clock. + const frameNow = vi + .spyOn(view.performance, 'now') + .mockImplementation(() => performance.now() - 5000); + const coarse = vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + })); + vi.stubGlobal('matchMedia', coarse); + Object.defineProperty(view, 'matchMedia', { + value: coarse, + configurable: true, + }); + try { + const onOpenChange = vi.fn<(isOpen: boolean) => void>(); + render( + createPortal( + +
Long-press me
+
, + secondDocument.body, + ), + ); + const trigger = within(secondDocument.body).getByTestId('ctx'); + const send = (type: 'touchstart' | 'touchend') => { + const event = new view.Event(type, {bubbles: true, cancelable: true}); + const contact = { + identifier: 1, + clientX: 20, + clientY: 20, + target: trigger, + }; + Object.defineProperty(event, 'changedTouches', {value: [contact]}); + Object.defineProperty(event, 'touches', { + value: type === 'touchstart' ? [contact] : [], + }); + Object.defineProperty(event, 'timeStamp', { + value: view.performance.now(), + }); + trigger.dispatchEvent(event); + return event; + }; + send('touchstart'); + act(() => { + vi.advanceTimersByTime(120); + }); + const lift = send('touchend'); + act(() => { + vi.advanceTimersByTime(1000); + }); + expect(onOpenChange).not.toHaveBeenCalledWith(true); + expect(lift.defaultPrevented).toBe(false); + } finally { + frameNow.mockRestore(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + } + }); }); }); From fac565ad2390051c6d9d929ae7139a12256ecb2b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 06:34:23 -0800 Subject: [PATCH 049/151] docs(ContextMenu): the record owns the touch hold's two modules component:ContextMenu's Ownership names contextMenuPress.ts and ContextMenuTouchLayer.tsx: the touch hold's recognizer, and the layer that attaches it and opens the menu. Records only, no code. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 7adec14d50e81..709e0037b626a 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -81,6 +81,10 @@ Consumer migration instructions belong in consumer docs and release notes. **Owns** - The Trigger area's context-menu invocation wiring (FR10). +- The touch hold under a coarse pointer (FR12). `ContextMenuPressRecognizer`, + in `contextMenuPress.ts`, times the commit, the display and the drift. + `ContextMenuTouchLayer.tsx` attaches it to the Trigger area and opens the + menu. - The alternative Pointer menu surface and Touch menu surface and their shared `context-menu` target. - Cursor-anchor placement across the two presentation paths, and open state From 69e6dd86665f0fd6abd82f0abf1f1fb4253fa373 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 07:46:00 -0800 Subject: [PATCH 050/151] docs(ContextMenu): the hold's comments match what this code does The touch layer's header read as if any second finger ended the hold. The recognizer fails on a lift, a second finger or a scroll only before the commit. The timeline's header, the spec's header and one spec comment named a press feedback, its growing copy and its scales, which this code does not have. Comments only. --- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 4 ++-- ...textMenuLongPress.interaction.browser.spec.ts | 9 +++------ packages/core/src/motion/uikit/contextMenu.ts | 16 ++++++---------- 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 30d47b133048f..8b8814f6e0800 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -48,8 +48,8 @@ export interface ContextMenuTouchLayerProps { * recognizer claims the finger. The page stops scrolling under it, and its * lift sends no click and no compatibility mouse events. The menu opens where * the finger landed: at `menuDisplayMs` if it is still down, or at the lift. - * A lift before the commit, a second finger or a scroll gets no menu. So does - * a drift past the tolerance before the menu shows. + * Before the commit, a lift, a second finger or a scroll gets no menu. So + * does a drift past the tolerance before the menu shows. */ export function ContextMenuTouchLayer({ triggerRef, diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 359dc9de1d1a0..bdb2a1e64d345 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -5,10 +5,9 @@ * @input The built "Touch / long press" ContextMenu story, real touch input, * the interaction harness, the context-menu constants and UIKit's frames * @output Interaction and animation proofs for a context menu that a held - * finger opens on UIKit's timeline. They cover the menu's moments, the - * press feedback against UIKit's frames and a blocked main thread. They - * also cover the page under the finger, a pan outside and a storyboard of - * the press + * finger opens on UIKit's timeline. They cover the menu's moments, on + * time and behind a blocked main thread. They also cover the page under + * the finger, a pan outside and a storyboard of the press * @position Interaction specs of packages/core/src/ContextMenu; Chromium's * finger stands for Android's engine, and WebKit's for iOS */ @@ -305,8 +304,6 @@ async function openScrollableStory(page: Page) { throw new Error('no trigger'); } const center = {x: box.x + box.width / 2, y: box.y + box.height / 2}; - // Where the trigger's container sits: the trigger itself is scaled by the - // press feedback. const top = async () => story.trigger.evaluate( el => (el.parentElement ?? el).getBoundingClientRect().y, diff --git a/packages/core/src/motion/uikit/contextMenu.ts b/packages/core/src/motion/uikit/contextMenu.ts index a6c168b433270..1b7ac9cb221fd 100644 --- a/packages/core/src/motion/uikit/contextMenu.ts +++ b/packages/core/src/motion/uikit/contextMenu.ts @@ -15,22 +15,18 @@ /** * UIContextMenuInteraction's touch timeline on iOS 26.2. A context menu is not - * a plain long press. A finger that rests on the view starts a press feedback - * after 150 ms. A copy of the view grows uniformly, and its size follows a - * linear ramp through a spring. At 400 ms the press commits. The click haptic - * plays, and the touch can no longer become a tap. The menu displays at 735 ms - * if the finger is still down, or at the lift after the commit. A finger that - * lifts before the commit gets no menu, and the copy springs back. A finger - * that drifts too far before the menu displays gets the same. + * a plain long press. At 400 ms the press commits. The click haptic plays, and + * the touch can no longer become a tap. The menu displays at 735 ms if the + * finger is still down, or at the lift after the commit. A finger that lifts + * before the commit gets no menu. A finger that drifts too far before the menu + * displays gets the same. * * UIKit runs this on display-link ticks. So a 60 Hz screen shows each moment - * on the first frame after it: the feedback at 151 ms, the commit at 417 ms. + * on the first frame after it: the commit at 417 ms. * The times here are the moments themselves, from the `touchstart` timestamp. * UIKit counts from the main thread's receipt of the touch, about a frame * after the hardware timestamp that a browser stamps. A browser's compositor * shows a value about a frame after its time, so the two offsets cancel. - * Scales are fractions of the view's own size. The lift and dismissal springs - * are `springs.contextMenuLift` and `springs.contextMenuDismiss`. * * Every leaf has one or more `@source`. A GUESS value also has the `@measure` * task that confirms or replaces it. uikit.test.ts enforces both. From cecb382902baf60f62faa4ef12a4a93f794fddd9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:12:34 -0800 Subject: [PATCH 051/151] docs(ContextMenu): the timeline and the spec name the press feedback The press feedback ships here. So the timeline's header names it, its growing copy and its scales, and the long-press spec's header and its scroll helper name it again. Comments only. --- ...textMenuLongPress.interaction.browser.spec.ts | 9 ++++++--- packages/core/src/motion/uikit/contextMenu.ts | 16 ++++++++++------ 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index fc890e5e04532..f1268d10f5499 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -5,9 +5,10 @@ * @input The built "Touch / long press" ContextMenu story, real touch input, * the interaction harness, the context-menu constants and UIKit's frames * @output Interaction and animation proofs for a context menu that a held - * finger opens on UIKit's timeline. They cover the menu's moments, on - * time and behind a blocked main thread. They also cover the page under - * the finger, a pan outside and a storyboard of the press + * finger opens on UIKit's timeline. They cover the menu's moments, the + * press feedback against UIKit's frames and a blocked main thread. They + * also cover the page under the finger, a pan outside and a storyboard of + * the press * @position Interaction specs of packages/core/src/ContextMenu; Chromium's * finger stands for Android's engine, and WebKit's for iOS */ @@ -1293,6 +1294,8 @@ async function openScrollableStory(page: Page) { throw new Error('no trigger'); } const center = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + // Where the trigger's container sits: the trigger itself is scaled by the + // press feedback. const top = async () => story.trigger.evaluate( el => (el.parentElement ?? el).getBoundingClientRect().y, diff --git a/packages/core/src/motion/uikit/contextMenu.ts b/packages/core/src/motion/uikit/contextMenu.ts index e2ea9ddcb1230..7d7743e20b664 100644 --- a/packages/core/src/motion/uikit/contextMenu.ts +++ b/packages/core/src/motion/uikit/contextMenu.ts @@ -16,18 +16,22 @@ /** * UIContextMenuInteraction's touch timeline on iOS 26.2. A context menu is not - * a plain long press. At 400 ms the press commits. The click haptic plays, and - * the touch can no longer become a tap. The menu displays at 735 ms if the - * finger is still down, or at the lift after the commit. A finger that lifts - * before the commit gets no menu. A finger that drifts too far before the menu - * displays gets the same. + * a plain long press. A finger that rests on the view starts a press feedback + * after 150 ms. A copy of the view grows uniformly, and its size follows a + * linear ramp through a spring. At 400 ms the press commits. The click haptic + * plays, and the touch can no longer become a tap. The menu displays at 735 ms + * if the finger is still down, or at the lift after the commit. A finger that + * lifts before the commit gets no menu, and the copy springs back. A finger + * that drifts too far before the menu displays gets the same. * * UIKit runs this on display-link ticks. So a 60 Hz screen shows each moment - * on the first frame after it: the commit at 417 ms. + * on the first frame after it: the feedback at 151 ms, the commit at 417 ms. * The times here are the moments themselves, from the `touchstart` timestamp. * UIKit counts from the main thread's receipt of the touch, about a frame * after the hardware timestamp that a browser stamps. A browser's compositor * shows a value about a frame after its time, so the two offsets cancel. + * Scales are fractions of the view's own size. The lift and dismissal springs + * are `springs.contextMenuLift` and `springs.contextMenuDismiss`. * * Every leaf has one or more `@source`. A GUESS value also has the `@measure` * task that confirms or replaces it. uikit.test.ts enforces both. From 3e17bd2404c3faec3b0e7406944bb3db4d893242 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:12:34 -0800 Subject: [PATCH 052/151] test(ContextMenu): a growth in a second document times its onset A ContextMenu in a same-origin iframe or a Picture-in-Picture window gets its touches on that window's clock. Its growth must start in the first frame at or after that clock's onset, 150 ms after the landing. --- .../ContextMenuTouchGrowth.test.tsx | 67 ++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index 93c371a050b04..82bfc21c40ed5 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -10,7 +10,8 @@ * packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx */ -import {act, render, screen} from '@testing-library/react'; +import {act, cleanup, render, screen, within} from '@testing-library/react'; +import {createPortal} from 'react-dom'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; import {ContextMenu} from './ContextMenu'; @@ -194,6 +195,70 @@ describe('ContextMenu’s growth under a finger', () => { expectGrowthFromOnsetFrame(trigger, landedAt); }); + it('times a finger’s growth on a second document’s own clock: it starts at that clock’s onset, 150 ms after the landing', async () => { + // An app can render a ContextMenu into a same-origin iframe or a Document + // Picture-in-Picture window through a portal. + const frame = document.createElement('iframe'); + document.body.appendChild(frame); + const secondDocument = frame.contentDocument as Document; + const view = secondDocument.defaultView as Window & typeof globalThis; + // The frame opened after the page, so its clock reads 5 s less. Its + // events come stamped on that clock. + const frameNow = vi + .spyOn(view.performance, 'now') + .mockImplementation(() => performance.now() - 5000); + // Its animation frames come with the page's fake ones. + const frameRequest = vi + .spyOn(view, 'requestAnimationFrame') + .mockImplementation(callback => requestAnimationFrame(callback)); + const frameCancel = vi + .spyOn(view, 'cancelAnimationFrame') + .mockImplementation(handle => cancelAnimationFrame(handle)); + Object.defineProperty(view, 'matchMedia', { + value: window.matchMedia, + configurable: true, + }); + try { + render( + createPortal( + +
Hold me
+
, + secondDocument.body, + ), + ); + const trigger = within(secondDocument.body).getByTestId('ctx'); + const contact = { + identifier: 1, + clientX: 20, + clientY: 20, + target: trigger, + }; + const event = new view.Event('touchstart', { + bubbles: true, + cancelable: true, + }); + Object.defineProperty(event, 'changedTouches', {value: [contact]}); + Object.defineProperty(event, 'touches', {value: [contact]}); + const landedAt = view.performance.now(); + Object.defineProperty(event, 'timeStamp', {value: landedAt}); + trigger.dispatchEvent(event); + // Its nodes come from another window, so the checks read numbers. + advance(149); + expect(growths(trigger).map(startOf)).toEqual([]); + advance(1 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); + } finally { + // Unmount before the frame goes, or React removes nodes from a + // document that no longer exists. + cleanup(); + frame.remove(); + frameNow.mockRestore(); + frameRequest.mockRestore(); + frameCancel.mockRestore(); + } + }); + it('grows the trigger at the onset when the press machine marks the press before the recognizer has the finger', async () => { const trigger = renderMenu(); const contact = {id: 1, x: 20, y: 20}; From 69a6851b31d057847738d87cb552c6431c1fce45 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:15:25 -0800 Subject: [PATCH 053/151] fix(ContextMenu): a growth runs on its trigger window's clock The gesture host times each document's touches on its own window's clock, so a trigger in a same-origin iframe or a Picture-in-Picture window reports its landing on that clock. The press feedback still watched the page's frames and clock, so the growth started in the first frame, dated on the page's clock. It now reads the trigger's window for its frames and clock. For another window, its animator runs on that window's clock and frames; the page's own document keeps the defaults. A comment that only restated a name goes. --- .../ContextMenu/contextMenuPressFeedback.ts | 46 ++++++++++++++----- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index f05de1af2fc0c..53898c0c2727f 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -75,28 +75,38 @@ const NO_LANDING: RefObject<() => number | null> = {current: () => null}; const NO_FINGER: RefObject<() => boolean> = {current: () => false}; /** - * Calls `onDue` in the first animation frame that runs at or after `dueAt`, on - * the event clock, with the time its callback runs. `onWait` runs in each frame - * before it. It reads only the clock. A frame comes on time where a timer does - * not: Chromium holds the page's timers for about 100 ms after it handles a - * touchstart. Returns the function that stops it. + * The window that shows `element`. A trigger in a same-origin iframe or a + * Picture-in-Picture window gets its touches, frames and timeline from that + * window, whose clock starts later than the page's. + */ +function windowOf(element: Element): Window { + return element.ownerDocument.defaultView ?? window; +} + +/** + * Calls `onDue` in the first animation frame of `view` that runs at or after + * `dueAt`, on that window's clock, with the time its callback runs. `onWait` + * runs in each frame before it. It reads only the clock. A frame comes on time + * where a timer does not: Chromium holds the page's timers for about 100 ms + * after it handles a touchstart. Returns the function that stops it. */ function watchFramesFrom( + view: Window, dueAt: number, onWait: () => void, onDue: (time: number) => void, ): () => void { - let frame = requestAnimationFrame(function look() { - const time = performance.now(); + let frame = view.requestAnimationFrame(function look() { + const time = view.performance.now(); if (time >= dueAt) { onDue(time); return; } onWait(); - frame = requestAnimationFrame(look); + frame = view.requestAnimationFrame(look); }); return () => { - cancelAnimationFrame(frame); + view.cancelAnimationFrame(frame); }; } @@ -132,7 +142,6 @@ export function useContextMenuPressFeedback( const fingerOnsetRef = useRef< ((landedAt: number, target: Element | null) => void) | null >(null); - // Stops the frame watch of a growth still to come. const stopOnsetRef = useRef<(() => void) | null>(null); const stopOnset = useCallback(() => { stopOnsetRef.current?.(); @@ -160,7 +169,19 @@ export function useContextMenuPressFeedback( if (element == null) { return null; } - animatorRef.current ??= createMotionEngine(element); + // Another window's timeline runs on its own clock and frames. + const view = windowOf(element); + animatorRef.current ??= createMotionEngine( + element, + view === window + ? {} + : { + now: () => view.performance.now(), + requestFrame: callback => { + view.requestAnimationFrame(frame => callback(frame)); + }, + }, + ); return animatorRef.current; }, [visualRef]); @@ -281,6 +302,7 @@ export function useContextMenuPressFeedback( const startAt = (onsetAt: number) => { stopOnset(); stopOnsetRef.current = watchFramesFrom( + windowOf(element), onsetAt, // The engine is built in a frame, not in the handler of the touch, // so the frame that starts the growth only creates its animation. @@ -322,7 +344,7 @@ export function useContextMenuPressFeedback( if (next) { if (!followsFinger.current()) { stopOnset(); - markedAt = performance.now(); + markedAt = windowOf(element).performance.now(); growAtMark(); } } else if (!isFollowed.current()) { From 1d6ec3721c6ccb60f9a331c6f46378492be694e7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:15:31 -0800 Subject: [PATCH 054/151] docs(ContextMenu): the End-user impact row states no build status The touch grow and the trigger lift are a gap that Current-state impact states against FR5. So the End-user impact row drops its "does not yet" sentence. Records only. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 810aa02115950..ec36bddcf7b20 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -48,7 +48,7 @@ system_specs: [spec:AST-094, spec:AST-107] | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Public contract | One default moves: under a coarse primary pointer, an omitted `presentation` means the touch model (`spec:AST-094` FR25), and `presentation="popover"` keeps the released surface. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | | Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | -| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger; mouse and keyboard opens keep today's look. | +| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. Mouse and keyboard opens keep today's look. | | Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | | Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow and trigger lift (FR5) are listed under Current-state impact. | | Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | From 8fb305f8b0ea0e4bdffa613bb273dd9816782c01 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:26:16 -0800 Subject: [PATCH 055/151] docs(ContextMenu): the press feedback's file comment keeps one line The block repeated what the hook's and the touch layer's JSDoc say. One line stays: only the recognizer's failure or cancel returns the growth. Comment only. --- .../core/src/ContextMenu/contextMenuPressFeedback.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index 53898c0c2727f..e59218002be1b 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -15,16 +15,7 @@ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx */ -// The growth starts in the first frame at or after the onset, 150 ms after a -// finger lands, while the recognizer follows that finger. It plays its whole -// spring from rest, from that frame, as Core Animation starts an animation at -// its commit. The recognizer reports the landing; a pointer-only pen's press -// waits for the press machine's "on". Only the recognizer's failure or cancel -// returns it. A long press is a gesture, so the -// growth plays UIKit's lift spring and each return its dismissal spring. The -// compositor plays them, so a busy main thread does not stall them. Once the -// menu opens, the trigger holds its size until the menu closes. Then it returns -// on the dismissal spring. An inline trigger and Reduce Motion show no growth. +// Only the recognizer's failure or cancel returns the growth. import {useCallback, useRef, type RefObject} from 'react'; import {useAttachment} from '../hooks/useAttachment'; From 13758676df8e37da537b8d8ac1bdf9ba7986012c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 19:06:49 -0800 Subject: [PATCH 056/151] docs(layer-runtime): name the layer's prepare and releasePrepared The record names the context mode's internal prepare() and releasePrepared(): what they do, and why ContextMenu prepares its menu at a held press's commit. Records only. --- docs/architecture/layer-runtime.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index e9ad1dbccfcec..aa19d2af94bdc 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -803,6 +803,13 @@ it on the surface inside the layer and run no layout while it plays. - `Layer/useLayer.tsx` owns Popover API lifecycle, state reconciliation, anchor/fixed/custom rendering, trigger source, and current same-gesture memory. + It also owns two internal members of a context-mode layer, which + `useLayerInternal` returns and `useLayer` does not. With `lazyMount`, + `prepare()` mounts the layer's content without showing it. The popover stays + closed, with no pixel and no accessibility node, and a later `show()` only + shows it. `releasePrepared()` unmounts that content unless the layer has + shown since. ContextMenu prepares its menu at a held press's commit, so its + first render does not fall inside the show at the hold's display moment. - `Layer/layerHost.ts` owns safe inline versus nearest corrective portal placement. - `Layer/anchorName.ts` owns composition of anchor names on one trigger. - `Layer/layerTextReset.stylex.ts` owns the text baseline and From f7ff7eaf3d07b8c0410821d0e62895ef5d966a39 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 23:23:53 -0800 Subject: [PATCH 057/151] feat(useMenuPress): continueGesture and its type are public useMenuPress's continueGesture and its MenuPressContinuation type lose their internal tag. The hooks entry exports the type, the hook's docs list the member with its usage, and a changeset notes it. No behavior changes. --- .changeset/menu-press-continue-gesture.md | 7 +++++++ packages/core/src/hooks/index.ts | 6 +++++- packages/core/src/hooks/useMenuPress.doc.mjs | 8 ++++++++ packages/core/src/hooks/useMenuPress.ts | 10 ++++------ 4 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 .changeset/menu-press-continue-gesture.md diff --git a/.changeset/menu-press-continue-gesture.md b/.changeset/menu-press-continue-gesture.md new file mode 100644 index 0000000000000..83b6fe8638363 --- /dev/null +++ b/.changeset/menu-press-continue-gesture.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `useMenuPress` returns `continueGesture(pointer)`, and `@astryxdesign/core/hooks` exports its `MenuPressContinuation` type. A menu that opens under a pointer that went down elsewhere, such as a long press on another element, hands that pointer to the menu: the same finger can then slide onto a row and pick it on release (`module:DropdownMenu/useMenuPress` FR11). + +@vjeux diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts index 1e338cb75a9ef..5a8597cd6f3fb 100644 --- a/packages/core/src/hooks/index.ts +++ b/packages/core/src/hooks/index.ts @@ -45,7 +45,11 @@ export { MENU_PRESS_MARKER, isMenuPressActivation, } from './useMenuPress'; -export type {UseMenuPressOptions, UseMenuPressReturn} from './useMenuPress'; +export type { + MenuPressContinuation, + UseMenuPressOptions, + UseMenuPressReturn, +} from './useMenuPress'; export {menuPressStep, MENU_PRESS_SETTLE_MS} from './menuPressGesture'; export type { MenuPressEffect, diff --git a/packages/core/src/hooks/useMenuPress.doc.mjs b/packages/core/src/hooks/useMenuPress.doc.mjs index 2c5737b7c8ee8..c077896d92ff0 100644 --- a/packages/core/src/hooks/useMenuPress.doc.mjs +++ b/packages/core/src/hooks/useMenuPress.doc.mjs @@ -113,6 +113,12 @@ export const docs = { description: 'End the gesture in flight with nothing acting, for when the menu closes under it.', }, + { + name: 'continueGesture', + type: '(pointer: MenuPressContinuation) => void', + description: + "Hand a pointer that went down elsewhere, such as a long press on another element, to the menu that just opened under it. It becomes the menu's opening press: a finger or a pen picks a row only after it has moved 10 px in the open menu, and its lift before that leaves the menu open. Call it as the menu opens, with the pointer's pointerId and pointerType and Date.now(). It does nothing while another gesture is live or the model is off.", + }, ], usage: { description: @@ -181,6 +187,8 @@ export const docsDense = { isTriggerClickFromPress: 'true = the trigger click belongs to the press that already opened / closed; ignore it.', cancel: 'end the gesture w/o acting.', + continueGesture: + 'hand a pointer still down from elsewhere (a long press) to the just-opened menu as its opening press; a finger picks after 10 px. Call as it opens: {pointerId, pointerType, time: Date.now()}.', }, usage: { description: diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts index 494978d62357a..38e0e99db07a3 100644 --- a/packages/core/src/hooks/useMenuPress.ts +++ b/packages/core/src/hooks/useMenuPress.ts @@ -244,13 +244,13 @@ interface MenuPressConfig extends UseMenuPressOptions { } /** - * An in-flight pointer handed to - * {@link UseMenuPressReturn.continueGesture}. - * - * @internal + * A pointer that went down elsewhere and is still down as a menu opens under + * it, for {@link UseMenuPressReturn.continueGesture}. */ export interface MenuPressContinuation { + /** The `pointerId` of its pointer events. */ pointerId: number; + /** Whether it is a mouse, a finger or a pen. */ pointerType: MenuPressPointerType; /** `Date.now()` of the moment the menu opened under it. */ time: number; @@ -286,8 +286,6 @@ export interface UseMenuPressReturn { * position the menu sees. Its lift before that acts on nothing and leaves * the menu open. A mouse follows the settle rule. Ignored while another * gesture is live or the model is off. - * - * @internal */ continueGesture: (pointer: MenuPressContinuation) => void; } From f7d5dd02b4b8b4f33dcaeccf6f243b47d7ff6999 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 23:23:53 -0800 Subject: [PATCH 058/151] docs(useMenuPress): the record lists continueGesture useMenuPress's record names continueGesture in its public contract, and its concepts table says what the member does and when ContextMenu calls it. Records only. --- .../specs/components/DropdownMenu/modules/useMenuPress.spec.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md index f48495e165f74..50c87500cdc5e 100644 --- a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md +++ b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md @@ -37,7 +37,7 @@ references: | Area | Contract | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Public contract | New public hook `useMenuPress` and the pure `menuPressStep` machine it drives, exported from `@astryxdesign/core/hooks`; the marker `data-astryx-menu-press` on every menu or listbox root that mounts it; the hook's trigger half (`onTriggerPress`, `triggerProps`, `isTriggerClickFromPress`, `longPressDelayMs`), released in 0.6.6. No consumer prop of DropdownMenu, ContextMenu, DropdownMenuSubMenu or Selector changes. | +| Public contract | New public hook `useMenuPress` and the pure `menuPressStep` machine it drives, exported from `@astryxdesign/core/hooks`; the marker `data-astryx-menu-press` on every menu or listbox root that mounts it; the hook's trigger half (`onTriggerPress`, `triggerProps`, `isTriggerClickFromPress`, `longPressDelayMs`), released in 0.6.6. The continuation `continueGesture(pointer: MenuPressContinuation)` on its return (FR11). No consumer prop of DropdownMenu, ContextMenu, DropdownMenuSubMenu or Selector changes. | | Behavior | The row under the pointer when it is RELEASED is the row that acts; the highlight follows a held mouse; a mouse released outside closes the menu; the browser's stray click for a tracked gesture never acts; the menu root declares `touch-action` by overflow. A finger or pen's press follows `spec:AST-094` FR26–FR30 under every primary pointer. PROPOSED (FR8, DEC-4): a mouse opens a DropdownMenu on press-down, with a settle rule on the opening release. | | End-user impact | A finger that lands on one menu row and lifts on another acts on the second, once, instead of on the first; a drag inside an open menu picks where it lets go; a mouse that lets go outside dismisses, a finger does not. PROPOSED: a mouse can press the trigger, drag into the menu and let go on a row in one gesture. Opening under a finger is `spec:AST-094` FR29's. Keyboard behavior and sub-menu hover are unchanged. | | Builder impact | None for consumers of the five surfaces: they mount the model themselves. A component CAN adopt this model only when it meets the eligibility criteria below, and its component contract MUST explicitly name this module and the governed surfaces before mounting `useMenuPress`. The builder supplies an enabled-row selector and a `touch-action` declaration. | @@ -148,6 +148,7 @@ Consumer migration instructions belong in consumer docs and release notes. | long-press delay | released 500 ms when set; unset, as `spec:AST-094` FR29 states (none in a fixed bar; 150 ms in a scroll view) | how long a held finger waits on a trigger before the menu opens. A caller that sets `longPressDelayMs` gets that wait in a fixed bar and in a scroll view alike, which keeps the released behavior (`spec:AST-094` FR25). | `longPressDelayMs` | `module:DropdownMenu/useMenuPress` | stable | | `data-astryx-menu-press` | present or absent | the root carries this model; a host controller of its own stands aside | present on every mounted root | `module:DropdownMenu/useMenuPress` | stable | | activation click | `click` with `detail: 0`, the release's button and modifiers | how the model acts on a row, marked for the synchronous extent by `isMenuPressActivation()`; `detail === 0` alone therefore no longer means "keyboard" on a menu row | — | `module:DropdownMenu/useMenuPress` | stable | +| continuation | `continueGesture(pointer: MenuPressContinuation)`: `pointerId`, `pointerType`, and `time` as the menu opened | hands a pointer that went down elsewhere to the menu as its opening press (FR11); ContextMenu calls it when its long press opens the menu with the finger or pen still down | — | `module:DropdownMenu/useMenuPress` | stable | ## Behavioral contract From cb9029d8c30a723109f15d199d11d864c41ddcf1 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 23:53:29 -0800 Subject: [PATCH 059/151] test(ContextMenu): a pen the press machine never marks still grows Inside a scroll view, a pen that drifts 11 px before the press machine's 150 ms is never marked, but the recognizer, with its 11.5 px tolerance, still follows it. Its growth must start at the onset, 150 ms after it lands, as a finger's does. --- .../ContextMenuTouchGrowth.test.tsx | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index 82bfc21c40ed5..ea24f377dc897 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -337,6 +337,48 @@ describe('ContextMenu’s growth under a finger', () => { expectGrowthFromOnsetFrame(trigger, landedAt); }); + it('grows a pen that drifts past the press machine’s 10 px inside a scroll view, which the recognizer’s 11.5 px tolerance still follows, at its onset', async () => { + render( +
+ +
Hold me
+
+
, + ); + // A scroller with content past its height: the press machine waits + // 150 ms before it marks a press here, and a travel past 10 px ends it. + const scroller = screen.getByTestId('scroller'); + Object.defineProperty(scroller, 'scrollHeight', {value: 400}); + Object.defineProperty(scroller, 'clientHeight', {value: 200}); + const trigger = screen.getByTestId('ctx'); + const pen = (type: string, x: number) => { + const event = new Event(type, {bubbles: true, cancelable: true}); + Object.assign(event, { + pointerId: 7, + pointerType: 'pen', + isPrimary: true, + button: type === 'pointerdown' ? 0 : -1, + buttons: 1, + clientX: x, + clientY: 20, + }); + Object.defineProperty(event, 'timeStamp', {value: performance.now()}); + trigger.dispatchEvent(event); + }; + const landedAt = performance.now(); + pen('pointerdown', 20); + await act(async () => {}); + advance(60); + // An 11 px drift, before the machine's 150 ms: it never marks the press. + pen('pointermove', 31); + await act(async () => {}); + expect(trigger.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false); + advance(89); + expect(growths(trigger)).toHaveLength(0); + advance(1 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); + }); + it('builds the motion engine in the first frame after the finger lands, not in its touchstart handler', async () => { const trigger = renderMenu(); const contact = {id: 1, x: 20, y: 20}; From 8fc523e470a2cf6664fddb61a3311dc6d0720bdc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 23:58:05 -0800 Subject: [PATCH 060/151] fix(ContextMenu): a pen's growth starts at its onset, as a finger's A pen's growth waited for the press machine's mark, which comes late inside a scroll view and never for a press that travels past 10 px first. The press feedback now times a pen from the landing the recognizer reports, as it times a finger. The mark's observer, the pen branch and the press machine's install go, with the two refs only they read. The trigger stays a pressable surface, so a press on it marks no surface around it. Tests that started the growth with a mark start it with a landing. --- packages/core/src/ContextMenu/ContextMenu.tsx | 4 +- .../ContextMenuTouchGrowth.test.tsx | 4 +- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 23 +--- .../contextMenuPressFeedback.test.tsx | 90 +++++---------- .../ContextMenu/contextMenuPressFeedback.ts | 107 ++++-------------- 5 files changed, 58 insertions(+), 170 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 39e3b7e796790..1a8b9b393fb86 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -1005,8 +1005,8 @@ export function ContextMenu({ ref={useMergedRefs(ref, triggerRef)} {...triggerProps} // Under the touch model, an enabled trigger is a pressable surface of - // core's one press machine. The touch layer installs the machine. Its - // press feedback follows a pen's pressed state and a finger's landing. + // core's one press machine, so a press on it marks no surface around + // it. Its press feedback follows a finger's or a pen's landing. {...(touchModes && !isDisabled ? pressableProps : null)} onContextMenu={handleTriggerContextMenu} onTouchStart={handleTriggerTouchStart} diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index ea24f377dc897..197912f6b7a45 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -313,7 +313,7 @@ describe('ContextMenu’s growth under a finger', () => { expect(growths(trigger)).toHaveLength(1); }); - it('grows a pen’s press at the onset from the press machine’s mark, which finds the recognizer following the pen', async () => { + it('times a pen’s growth from its landing, as a finger’s: it starts at the onset, 150 ms after the pen lands', async () => { const trigger = renderMenu(); const landedAt = performance.now(); const down = new Event('pointerdown', {bubbles: true, cancelable: true}); @@ -327,10 +327,8 @@ describe('ContextMenu’s growth under a finger', () => { clientY: 20, }); Object.defineProperty(down, 'timeStamp', {value: landedAt}); - // The press machine marks the pen's press from the same pointerdown. trigger.dispatchEvent(down); await act(async () => {}); - expect(trigger.getAttribute(PRESSED_ATTRIBUTE)).toBe('on'); advance(149); expect(growths(trigger)).toHaveLength(0); advance(1 + FRAME_MS); diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 8c2104fbd880e..cbb533cb7d3aa 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -75,16 +75,11 @@ export function ContextMenuTouchLayer({ // Whether the recognizer follows a finger or a pen now. It is set below, // where the recognizer exists. const isFollowedRef = useRef<() => boolean>(() => false); - // When the finger the recognizer follows landed, for the growth's onset. - const landedAtRef = useRef<() => number | null>(() => null); - const followsFingerRef = useRef<() => boolean>(() => false); const feedback = useContextMenuPressFeedback( triggerRef, visualRef, isShown, isFollowedRef, - landedAtRef, - followsFingerRef, ); const feedbackRef = useRef(feedback); feedbackRef.current = feedback; @@ -111,15 +106,13 @@ export function ContextMenuTouchLayer({ onCancelRef.current?.(); } }); - // A finger's growth counts from the landing the recognizer records as - // it takes the touch. A pen's press waits for the press machine's mark. + // A finger's or a pen's growth counts from the landing the recognizer + // records as it takes the contact. recognizer.onPressBegan = (touch, time) => { - if (touch.pointerType === 'touch') { - feedbackRef.current.begin( - time, - isElement(touch.target) ? touch.target : null, - ); - } + feedbackRef.current.begin( + time, + isElement(touch.target) ? touch.target : null, + ); }; return recognizer; }, @@ -164,10 +157,6 @@ export function ContextMenuTouchLayer({ isFollowedRef.current = () => recognizer.numberOfTouches > 0 && !isTerminal(recognizer.state); - landedAtRef.current = () => recognizer.press?.time ?? null; - followsFingerRef.current = () => - isFollowedRef.current() && - recognizer.trackedTouches[0]?.pointerType === 'touch'; useImperativeHandle( ref, diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx index fb41fd869b446..c366d8f91b391 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -17,6 +17,7 @@ import {afterEach, describe, expect, it, vi} from 'vitest'; import {contextMenu} from '../motion/uikit/contextMenu'; import {springs} from '../motion/uikit/springs'; import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; +import {PRESS_ONSET_MS} from '../utils/pressGesture'; import { useContextMenuPressFeedback, type ContextMenuPressFeedback, @@ -61,22 +62,11 @@ function Trigger() { } /** What the recognizer follows now, as ContextMenu's refs report it. */ -const recognizer = {isFollowing: true, isFinger: false}; +const recognizer = {isFollowing: true}; function TriggerWithRecognizer() { const ref = useRef(null); const isFollowedRef = useRef(() => recognizer.isFollowing); - const landedAtRef = useRef((): number | null => null); - const followsFingerRef = useRef( - () => recognizer.isFollowing && recognizer.isFinger, - ); - feedback = useContextMenuPressFeedback( - ref, - ref, - true, - isFollowedRef, - landedAtRef, - followsFingerRef, - ); + feedback = useContextMenuPressFeedback(ref, ref, true, isFollowedRef); return
; } @@ -139,7 +129,6 @@ const growths = () => ([to]) => ((to as {scale?: number}).scale ?? 1) > 1, ); -/** Lets the shared mutation observer deliver its records. */ // The growth starts in the next animation frame. const flush = async () => new Promise(resolve => { @@ -161,6 +150,9 @@ const FAKE_TIMERS = { }; const startsOf = () => growths().map(call => (call[2] as {at: number}).at); // One growth, started from rest in the first frame at or after the onset. +/** The recognizer took a contact on `target` whose onset is now. */ +const landNow = (target: Element) => + feedback?.begin(performance.now() - PRESS_ONSET_MS, target); const expectGrowthFromOnsetFrame = (onsetAt: number) => { const starts = startsOf(); expect(starts).toHaveLength(1); @@ -176,13 +168,13 @@ describe('useContextMenuPressFeedback', () => { feedback = null; }); - it('keeps growing when the press machine lets the press go, and springs back when the recognizer ends it', async () => { + it('ignores the press machine’s mark: it grows from the landing, and springs back when the recognizer ends the press', async () => { const {getByTestId} = render(); const trigger = getByTestId('trigger'); - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + landNow(trigger); await flush(); expect(animator.animate).toHaveBeenCalledOnce(); - // The press machine's slop is shorter than the recognizer's tolerance. + trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); trigger.removeAttribute(PRESSED_ATTRIBUTE); await flush(); expect(animator.animate).toHaveBeenCalledOnce(); @@ -190,34 +182,29 @@ describe('useContextMenuPressFeedback', () => { expect(animator.animate).toHaveBeenCalledTimes(2); }); - it('grows when the press machine marks a pressable control inside the trigger, the innermost surface it marks', async () => { + it('grows for a landing on a control inside the trigger', async () => { const {getByTestId} = render(); - getByTestId('control').setAttribute(PRESSED_ATTRIBUTE, 'on'); - await flush(); - expect(animator.animate).toHaveBeenCalledOnce(); - getByTestId('control').removeAttribute(PRESSED_ATTRIBUTE); + landNow(getByTestId('control')); await flush(); expect(animator.animate).toHaveBeenCalledOnce(); }); - it('grows only the innermost trigger when one trigger sits inside another', async () => { + it('grows only the outer trigger for a landing on its own control beside a nested trigger', async () => { const {getByTestId} = render(); - getByTestId('inner').setAttribute(PRESSED_ATTRIBUTE, 'on'); - await flush(); - expect(animator.animated).toEqual([getByTestId('inner')]); - getByTestId('inner').removeAttribute(PRESSED_ATTRIBUTE); + const control = getByTestId('outer-control'); + const landedAt = performance.now() - PRESS_ONSET_MS; + nested.outer?.begin(landedAt, control); + nested.inner?.begin(landedAt, control); await flush(); - getByTestId('outer-control').setAttribute(PRESSED_ATTRIBUTE, 'on'); - await flush(); - expect(animator.animated).toEqual([ - getByTestId('inner'), - getByTestId('outer'), - ]); + expect(animator.animated).toEqual([getByTestId('outer')]); }); - it('grows no outer trigger for a press on a nested trigger that shows no growth', async () => { + it('grows no outer trigger for a landing on a nested trigger that shows no growth', async () => { const {getByTestId} = render(); - getByTestId('inner').setAttribute(PRESSED_ATTRIBUTE, 'on'); + const inner = getByTestId('inner'); + const landedAt = performance.now() - PRESS_ONSET_MS; + nested.outer?.begin(landedAt, inner); + nested.inner?.begin(landedAt, inner); await flush(); expect(animator.animated).toEqual([]); }); @@ -225,7 +212,7 @@ describe('useContextMenuPressFeedback', () => { it('gives the trigger back its size when its feedback goes while the menu it opened is up', async () => { const {getByTestId, rerender} = render(); const trigger = getByTestId('trigger'); - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + landNow(trigger); await flush(); expect(animator.animate).toHaveBeenCalledOnce(); // The menu opened: the animator froze the growth on the element. @@ -239,7 +226,7 @@ describe('useContextMenuPressFeedback', () => { it('grows toward the held scale on springs.contextMenuLift, from the onset', async () => { const {getByTestId} = render(); const trigger = getByTestId('trigger'); - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + landNow(trigger); await flush(); const [to, transition, options] = animator.animate.mock .lastCall as unknown as [ @@ -256,7 +243,7 @@ describe('useContextMenuPressFeedback', () => { it('returns on springs.contextMenuDismiss, at the time the recognizer ended the press', async () => { const {getByTestId} = render(); const trigger = getByTestId('trigger'); - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + landNow(trigger); await flush(); feedback?.end(1000); expect(animator.animate.mock.lastCall).toEqual([ @@ -284,10 +271,9 @@ describe('useContextMenuPressFeedback', () => { } }); - it('keeps a finger’s onset when the press machine marks the press later', async () => { + it('keeps a landing’s onset when the press machine marks the press later', async () => { vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); try { - recognizer.isFinger = true; const {getByTestId} = render(); vi.advanceTimersByTime(1000); const landedAt = performance.now(); @@ -297,28 +283,6 @@ describe('useContextMenuPressFeedback', () => { await vi.advanceTimersByTimeAsync(200); expectGrowthFromOnsetFrame(landedAt + 150); } finally { - recognizer.isFinger = false; - vi.useRealTimers(); - } - }); - - it('starts a pen’s growth at its mark after a finger’s press ended', async () => { - vi.useFakeTimers({toFake: [...FAKE_TIMERS.toFake]}); - try { - recognizer.isFinger = true; - const {getByTestId} = render(); - const trigger = getByTestId('trigger'); - feedback?.begin(performance.now(), trigger); - await vi.advanceTimersByTimeAsync(150 + FRAME_MS); - expect(growths()).toHaveLength(1); - feedback?.end(performance.now()); - // A pen's press: the press machine's mark starts its growth. - recognizer.isFinger = false; - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); - await vi.advanceTimersByTimeAsync(FRAME_MS); - expect(growths()).toHaveLength(2); - } finally { - recognizer.isFinger = false; vi.useRealTimers(); } }); @@ -381,7 +345,7 @@ describe('useContextMenuPressFeedback', () => { it('returns on springs.contextMenuDismiss when the menu the press opened closes', async () => { const {getByTestId} = render(); const trigger = getByTestId('trigger'); - trigger.setAttribute(PRESSED_ATTRIBUTE, 'on'); + landNow(trigger); await flush(); feedback?.hold(); feedback?.release(); diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index e59218002be1b..bdb80aa091ebd 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -5,11 +5,10 @@ /** * @file contextMenuPressFeedback.ts * @input UIKit's context-menu springs, the context-menu constants, the - * compositor animator, the presses ContextMenu's recognizer takes, the - * press state core's press machine writes, and the context-menu-trigger - * mark (privateAttributes/contextMenuTrigger.stylex.ts) + * compositor animator, the presses ContextMenu's recognizer takes, and the + * context-menu-trigger mark (privateAttributes/contextMenuTrigger.stylex.ts) * @output useContextMenuPressFeedback: hold and release, from ContextMenu's - * menu; the growth follows the recognizer's finger, or a pen's press mark + * menu; the growth follows the recognizer's finger or pen * @position The press feedback of ContextMenu's touch invocation * * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx @@ -19,14 +18,11 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useAttachment} from '../hooks/useAttachment'; -import {usePressFeedback} from '../hooks/usePressFeedback'; import { closestContextMenuTrigger, markContextMenuTrigger, } from '../privateAttributes/contextMenuTrigger.stylex'; -import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; import {PRESS_ONSET_MS} from '../utils/pressGesture'; -import {observeMutations} from '../utils/sharedMutationObserver'; import {createMotionEngine, type Animator} from '../motion/animator'; import {contextMenu} from '../motion/uikit/contextMenu'; import { @@ -38,8 +34,8 @@ const {heldScale} = contextMenu.press; export interface ContextMenuPressFeedback { /** - * The recognizer took a finger that landed at `landedAt` on `target`: grow - * from the first frame at or after its onset, 150 ms later. + * The recognizer took a finger or a pen that landed at `landedAt` on + * `target`: grow from the first frame at or after its onset, 150 ms later. */ begin(landedAt: number, target: Element | null): void; /** The menu the press opened closed: return on the dismissal spring. */ @@ -56,15 +52,9 @@ export interface ContextMenuPressFeedback { hold(): void; } -/** A press feedback with no recognizer to ask grows at every "on". */ +/** A press feedback with no recognizer to ask grows at every `begin`. */ const ALWAYS_FOLLOWED: RefObject<() => boolean> = {current: () => true}; -/** With no recognizer to ask, the onset is the "on" itself. */ -const NO_LANDING: RefObject<() => number | null> = {current: () => null}; - -/** With no recognizer to ask, every "on" is a pen's. */ -const NO_FINGER: RefObject<() => boolean> = {current: () => false}; - /** * The window that shows `element`. A trigger in a same-origin iframe or a * Picture-in-Picture window gets its touches, frames and timeline from that @@ -103,25 +93,19 @@ function watchFramesFrom( /** * The press feedback of a ContextMenu trigger. `isShown` is read at each - * press: false for an inline trigger. It follows the press mark on the - * element behind `triggerRef`, so a replaced trigger (`triggerAs`) is - * followed too. It grows the element behind `visualRef`, the trigger's own - * visual, so a layer anchored in the trigger never takes the scale. The - * `isFollowed` ref says whether ContextMenu's recognizer follows a finger or - * a pen now: the growth starts only then. The `landedAt` ref gives the time - * that finger landed, so the growth starts at its onset. The `followsFinger` - * ref says whether that contact is a finger, whose onset `begin` sets. + * press: false for an inline trigger. It marks the element behind + * `triggerRef`, so a replaced trigger (`triggerAs`) is followed too. It grows + * the element behind `visualRef`, the trigger's own visual, so a layer + * anchored in the trigger never takes the scale. The `isFollowed` ref says + * whether ContextMenu's recognizer follows a finger or a pen now: the growth + * starts only then. */ export function useContextMenuPressFeedback( triggerRef: RefObject, visualRef: RefObject, isShown: boolean, isFollowed: RefObject<() => boolean> = ALWAYS_FOLLOWED, - landedAt: RefObject<() => number | null> = NO_LANDING, - followsFinger: RefObject<() => boolean> = NO_FINGER, ): ContextMenuPressFeedback { - // The press machine's document listener, while this feedback is mounted. - usePressFeedback(); const animatorRef = useRef(null); const isShownRef = useRef(isShown); isShownRef.current = isShown; @@ -130,7 +114,7 @@ export function useContextMenuPressFeedback( // The menu the press opened is up: the growth holds until it closes. const isHeldRef = useRef(false); // Null while no shown trigger is attached, so `begin` grows nothing. - const fingerOnsetRef = useRef< + const onsetRef = useRef< ((landedAt: number, target: Element | null) => void) | null >(null); const stopOnsetRef = useRef<(() => void) | null>(null); @@ -255,7 +239,7 @@ export function useContextMenuPressFeedback( }, [settleBack]); const begin = useCallback((landed: number, target: Element | null) => { - fingerOnsetRef.current?.(landed, target); + onsetRef.current?.(landed, target); }, []); const hold = useCallback(() => { @@ -266,30 +250,20 @@ export function useContextMenuPressFeedback( } }, [stopOnset]); - // Grow from the onset, 150 ms after the finger lands. The recognizer reports - // the landing as it takes the finger, whether or not the press machine - // marks the press. Inside a scroll view the machine marks late, and it never - // marks a press that travels past 10 px first. A pen's onset waits for the - // mark. The machine marks the innermost pressable surface, so a control - // inside the trigger can carry the mark. Only the recognizer ends the growth + // Grow from the onset, 150 ms after a finger or a pen lands. The recognizer + // reports the landing as it takes the contact. The press machine's mark is + // not waited for: inside a scroll view it comes late, and never for a press + // that travels past 10 px first. Only the recognizer ends the growth // (`end`). useAttachment( triggerRef, element => { - // Every mounted trigger is marked, whether it shows growth or not. A - // press mark belongs to the nearest trigger at or above it, so a press - // on a nested trigger grows no outer trigger. + // Every mounted trigger is marked, whether it shows growth or not, so a + // landing on a nested trigger grows no outer trigger. const unmark = markContextMenuTrigger(element); if (!isShown) { return unmark; } - const isMarkedOn = () => - element.getAttribute(PRESSED_ATTRIBUTE) === 'on' || - [...element.querySelectorAll(`[${PRESSED_ATTRIBUTE}="on"]`)].some( - marked => closestContextMenuTrigger(marked) === element, - ); - let isPressed = isMarkedOn(); - let markedAt = 0; const startAt = (onsetAt: number) => { stopOnset(); stopOnsetRef.current = watchFramesFrom( @@ -304,52 +278,15 @@ export function useContextMenuPressFeedback( }, ); }; - // A pen's mark: the gesture host took that pen from the same input - // before the mark's record comes, so the recognizer follows it already. - const growAtMark = () => { - // The recognizer times a finger's onset from its landing. - if (followsFinger.current() || !isFollowed.current()) { - return; - } - const landed = landedAt.current(); - startAt( - landed == null - ? markedAt - : Math.max(markedAt, landed + PRESS_ONSET_MS), - ); - }; - fingerOnsetRef.current = (landed, target) => { - // A finger on a nested trigger grows only that trigger. + onsetRef.current = (landed, target) => { if (target != null && closestContextMenuTrigger(target) !== element) { return; } startAt(landed + PRESS_ONSET_MS); }; - const stopObserving = observeMutations( - element, - {attributes: true, attributeFilter: [PRESSED_ATTRIBUTE], subtree: true}, - () => { - const next = isMarkedOn(); - if (next !== isPressed) { - isPressed = next; - if (next) { - if (!followsFinger.current()) { - stopOnset(); - markedAt = windowOf(element).performance.now(); - growAtMark(); - } - } else if (!isFollowed.current()) { - // A finger the recognizer still follows keeps its onset, past - // the machine's shorter travel. - stopOnset(); - } - } - }, - ); return () => { stopOnset(); - stopObserving(); - fingerOnsetRef.current = null; + onsetRef.current = null; unmark(); }; }, From f0b00178dbd3606b267e0313257585819e0f038f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:55:27 -0800 Subject: [PATCH 061/151] test(ContextMenu): a dropped render leaves the commit's mount alone A transition whose render suspends never commits. When that render asks for a bottom sheet, the press still mounts the menu at the commit from the props that committed. --- .../core/src/ContextMenu/ContextMenu.test.tsx | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index aeb0c1705db1b..2c14407a13189 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -8,7 +8,7 @@ * SYNC: When ContextMenu.tsx changes, update tests to match new behavior */ -import {useRef, useState} from 'react'; +import {Suspense, startTransition, use, useRef, useState} from 'react'; import {createPortal} from 'react-dom'; import { describe, @@ -885,6 +885,43 @@ describe.each([ press.up(); }); + it('mounts the menu at the commit from the committed render, when React drops a later render', async () => { + // A transition whose render suspends never commits. Its render asks for + // a bottom sheet, which mounts nothing at the commit. + const never = new Promise(() => {}); + function Suspends({isSuspended}: {isSuspended: boolean}) { + if (isSuspended) { + use(never); + } + return null; + } + let setIsSheet: (isSheet: boolean) => void = () => {}; + function App() { + const [isSheet, set] = useState(false); + setIsSheet = set; + return ( + + +
Long-press me
+
+ +
+ ); + } + render(); + await act(async () => { + startTransition(() => setIsSheet(true)); + }); + const press = finger(screen.getByTestId('ctx')); + press.down(); + advance(contextMenu.press.commitMs); + expect(screen.getByRole('menu', {hidden: true})).toBeTruthy(); + press.up(); + }); + it('shows the menu mounted at the commit at the lift that comes before 735 ms', () => { const trigger = renderMenu(); const press = finger(trigger); From e5a2bc97c464b72b3a7ba701b5d23b49da5811f9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:19:49 -0800 Subject: [PATCH 062/151] refactor(ContextMenu): no ref is written during render The touch layer wrote its open, commit and cancel callbacks into refs during render. The gesture handler now calls onOpen and onCommit itself, since the gesture hook keeps the newest handler, and the transition listener reads onCancel through useCommittedRef. ContextMenu builds its outside-press watch and its menu focus as callbacks and writes them with useCommittedRefInto into the refs the layer's onShow reads. No behavior changes. --- packages/core/src/ContextMenu/ContextMenu.tsx | 12 +++++++++--- .../core/src/ContextMenu/ContextMenuTouchLayer.tsx | 12 ++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 85e569735845d..d40e5a787d0c3 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -81,6 +81,7 @@ import { } from '../DropdownMenu/menuItemRoles'; import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow'; import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn'; +import {useCommittedRefInto} from '../hooks/useCommittedRef'; import {useInternalListFocus} from '../hooks/useListFocus'; import {useLongPress} from '../hooks/useLongPress'; import {useMenuPress} from '../hooks/useMenuPress'; @@ -528,7 +529,11 @@ export function ContextMenu({ focusFollowsLastInput: true, }); focusFirstRef.current = focusFirst; - focusMenuRef.current = () => listRef.current?.focus({preventScroll: true}); + const focusMenu = useCallback( + () => listRef.current?.focus({preventScroll: true}), + [listRef], + ); + useCommittedRefInto(focusMenuRef, focusMenu); // Join the shared stack so an Escape press dismisses exactly one top-most // surface. BottomSheet owns its own dismissal path. @@ -558,7 +563,7 @@ export function ContextMenu({ // closes it as it begins to pan, or at its lift, and the page stays free to // scroll. Otherwise a touch closes it at its compatibility mousedown. The // press that opened the menu keeps it open. - watchOutsideRef.current = () => { + const watchOutside = useCallback(() => { const trigger = triggerRef.current; if (trigger == null) { return; @@ -581,7 +586,8 @@ export function ContextMenu({ root: shadowHostOf(root) != null ? root : null, }, ); - }; + }, [closeMenu, listRef, outsidePress, touchModes]); + useCommittedRefInto(watchOutsideRef, watchOutside); const listKeyDown = useCallback( (e: React.KeyboardEvent) => { diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 8b8814f6e0800..37abb46eee94e 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -17,6 +17,7 @@ import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; import {flushSync} from 'react-dom'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; +import {useCommittedRef} from '../hooks/useCommittedRef'; import {contextMenu} from '../motion/uikit/contextMenu'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -58,12 +59,7 @@ export function ContextMenuTouchLayer({ onCommit, onCancel, }: ContextMenuTouchLayerProps): null { - const onOpenRef = useRef(onOpen); - onOpenRef.current = onOpen; - const onCommitRef = useRef(onCommit); - onCommitRef.current = onCommit; - const onCancelRef = useRef(onCancel); - onCancelRef.current = onCancel; + const onCancelRef = useCommittedRef(onCancel); const hasPressOpenedRef = useRef(false); // The gesture hook follows the element behind the ref, so a `triggerAs` @@ -86,7 +82,7 @@ export function ContextMenuTouchLayer({ hasPressOpenedRef.current = true; // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the menu shows in the task that decides it, as UIKit shows it at its moment, not a scheduled task later flushSync(() => { - onOpenRef.current(press.press ?? press.location()); + onOpen(press.press ?? press.location()); }); }; switch (press.state) { @@ -97,7 +93,7 @@ export function ContextMenuTouchLayer({ playHaptic(contextMenu.commitHaptic); // The menu shows at its moment or at the lift. Mounted now, its // content costs that show nothing. - onCommitRef.current?.(); + onCommit?.(); break; case 'changed': if (press.isMenuDue && !hasPressOpenedRef.current) { From 3ea914d66b5f0ff946965c20b5784a618ec5f32d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:25:36 -0800 Subject: [PATCH 063/151] docs(layer-runtime): the outside-press line names a touch's press too Under a fine pointer, ContextMenu also judges a touch at its compatibility mousedown. Records only. --- docs/architecture/layer-runtime.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 5291e03cc77e9..4adac141d9991 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -861,8 +861,9 @@ it on the surface inside the layer and run no layout while it plays. - `Layer/outsidePress.ts` owns the outside-press watch for a text field's manual layer, used by BaseTypeahead, DateInput, DateTimeInput and ChatComposerInput's trigger menu, and for ContextMenu's menu, which judges - a mouse's or a pen's press as it goes down (`pressTypes`). It also owns the - per-document count of outside closes that a modal backdrop press reads + a mouse's or a pen's press as it goes down, and a touch's too under a fine + pointer (`pressTypes`). It also owns the per-document count of outside + closes that a modal backdrop press reads (`family:overlay-dismissal` FR11). - `DropdownMenuContext` and `DropdownMenuSubMenu` own the current local menu-cascade parent-close chain. From 86f89fdd84502a6b35a0092835648e01b0ad7367 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Nov 2026 08:38:57 -0800 Subject: [PATCH 064/151] docs(ContextMenu): two more comments match what this code does The long-press spec's note about a restated onset restated nothing, and the motion README listed a press feedback for the context-menu table, which holds none here. Comments only. --- .../ContextMenuLongPress.interaction.browser.spec.ts | 4 ---- packages/core/src/motion/README.md | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index bdb2a1e64d345..15b0f5c4a6d36 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -35,10 +35,6 @@ import {contextMenu} from '../../motion/uikit/contextMenu'; const storybook = withStorybook(test); const {menuDisplayMs} = contextMenu.press; -// Core's press machine believes a press 150 ms after it lands -// (`utils/pressGesture.ts`). That module loads a StyleX stylesheet, which -// this Node-side spec cannot, so the onset is restated here. - interface TouchStory { driver: TouchDriver; trigger: Locator; diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index a613ae487a6f8..c21a36c3caae6 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -18,7 +18,7 @@ roles through `resolveMotion`. | `uikit/springs.ts` | Interaction springs (navigation, sheets, alerts, menus, controls, keyboard, banners) and the SwiftUI / UIKit presets. | | `uikit/scroll.ts` | UIScrollView: deceleration rates, rubber band, bounce-back spring, `delaysContentTouches`, scroll to top. | | `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. | -| `uikit/contextMenu.ts` | UIContextMenuInteraction: touch timeline (feedback, commit, menu), drift tolerance, commit haptic. | +| `uikit/contextMenu.ts` | UIContextMenuInteraction: touch timeline (commit, menu), drift tolerance, commit haptic. | | `uikit/paging.ts` | A paging UIScrollView: the integrator that settles a release on its page, the page rule, the catch, `setContentOffset(animated:)`. | | `uikit/alert.ts` | UIAlertController: how a finger is tracked across the actions (highlight onset and bounds). | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | From 9cccb470b1c81afd655a77772e9db657dee18348 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:20:17 -0800 Subject: [PATCH 065/151] docs(ContextMenu): the rest of the text matches what ships here The menu's style comment, the popover story, a press test's name and the timeline changeset no longer name a row lit under the finger, a growth or a press feedback, which later pull requests ship. Comments and docs only. --- .changeset/contextmenu-touch-timeline.md | 2 +- apps/storybook/stories/ContextMenu.stories.tsx | 2 +- packages/core/src/ContextMenu/ContextMenu.tsx | 3 +-- packages/core/src/ContextMenu/contextMenuPress.test.ts | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index b8c1a1e95a6c7..4160e64376434 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu takes the focus, and a row lights only under the finger, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 7d8dff9642034..9e35541c56873 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -698,7 +698,7 @@ export const TouchLongPressPopover: Story = { docs: { description: { story: - 'With `presentation="popover"`, ContextMenu keeps today’s menu on every device: a finger held for 500 ms opens it at the finger, with no growth and no iOS timeline. A finger on a device whose primary pointer is fine (a mouse or a trackpad) gets the same long press.', + 'With `presentation="popover"`, ContextMenu keeps today’s menu on every device: a finger held for 500 ms opens it at the finger, with no iOS timeline. A finger on a device whose primary pointer is fine (a mouse or a trackpad) gets the same long press.', }, }, }, diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index d40e5a787d0c3..8d1af6a955186 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -177,8 +177,7 @@ const styles = stylex.create({ transitionTimingFunction: easeVars['--ease-standard'], userSelect: 'none', WebkitTouchCallout: 'none', - // A touch open focuses the menu itself, so no row is lit until the finger - // moves onto one, as with DropdownMenu's held finger. The menu is an + // A touch open focuses the menu itself, so no row is lit. The menu is an // internal focus target, not a control, so it shows no browser ring. // Keyboard focus moves to an item instead. outline: 'none', diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index 324e11d6e7a12..db5a4ff0362f5 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -355,7 +355,7 @@ describe('ContextMenuPressRecognizer', () => { expect(states).toEqual(['failed@90', 'possible@90']); }); - it('keeps the press while it fails, so the feedback knows which one ended', () => { + it('keeps the press while it fails, so a transition listener can tell which one ended', () => { const {harness, press} = setup(); let pressAtFailure: unknown = 'unset'; press.addTransitionListener((recognizer, _from, to) => { From 21f8156d563a82e3ded466042f9d75fbceed069b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:20:28 -0800 Subject: [PATCH 066/151] docs(ContextMenu): the End-user row states the gap, not a status The row said the touch-opened menu "does not yet" grow or lift. It now says the menu keeps the layer's own entrance and lifts no trigger, and points to FR5's recorded gap. Records only. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 709e0037b626a..6e4a8119107ae 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -48,7 +48,7 @@ system_specs: [spec:AST-094, spec:AST-107] | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Public contract | One default moves: under a coarse primary pointer, an omitted `presentation` means the touch model (`spec:AST-094` FR25), and `presentation="popover"` keeps the released surface. ContextMenu takes caller `children` as the Trigger area, data-driven `items` or compound `menuContent`, `label`, `presentation`, `isDisabled`, and `triggerAs`. | | Behavior | Right-click, Shift+F10 or the Menu key, and a touch long press open a menu at the cursor (or the trigger's bottom-left from the keyboard), or a bottom sheet; rows follow DropdownMenu's rows and press model. | -| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu does not yet grow from the finger or lift its trigger; mouse and keyboard opens keep today's look. | +| End-user impact | People reach a region's actions by mouse, keyboard, or a held finger; a sub-menu drills in on a phone. A touch-opened menu keeps the layer's own entrance and lifts no trigger (FR5's recorded gap); mouse and keyboard opens keep today's look. | | Builder impact | Builders wrap any region, including an inline reference in prose (`triggerAs="span"`). | | Compatibility/readiness | Records shipped behavior; no API change; a disabled row gains `tabindex="-1"`; the released behavior under a finger moves as `spec:AST-094` FR25 lists, with `presentation="popover"` keeping it. The touch grow and trigger lift (FR5) are listed under Current-state impact. | | Review checks | Reject a trigger that gains a role or `aria-haspopup`, a menu that bypasses the shared Escape stack, a `context-menu` target moved off the painted surface, or a second open-state owner. | From 2bd6ba2ea1efffdcc5eb7abd91f94619d2a0d33a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 02:02:58 -0800 Subject: [PATCH 067/151] test(ContextMenu): a dropped render leaves the growth alone A transition whose render suspends never commits. When that render makes the trigger inline, which shows no growth, a finger still grows the trigger at its onset from the props that committed. --- .../ContextMenuTouchGrowth.test.tsx | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index 197912f6b7a45..be05828997c8c 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -11,6 +11,7 @@ */ import {act, cleanup, render, screen, within} from '@testing-library/react'; +import {Suspense, startTransition, use, useState} from 'react'; import {createPortal} from 'react-dom'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; @@ -152,6 +153,44 @@ describe('ContextMenu’s growth under a finger', () => { element === visualOf(trigger) && (to as {scale?: number}).scale === 1, ); + it('grows from the committed render, when React drops a later render that shows no growth', async () => { + // A transition whose render suspends never commits. Its render makes the + // trigger inline, which shows no growth. + const never = new Promise(() => {}); + function Suspends({isSuspended}: {isSuspended: boolean}) { + if (isSuspended) { + use(never); + } + return null; + } + let setIsInline: (isInline: boolean) => void = () => {}; + function App() { + const [isInline, set] = useState(false); + setIsInline = set; + return ( + + +
Hold me
+
+ +
+ ); + } + render(); + await act(async () => { + startTransition(() => setIsInline(true)); + }); + const trigger = screen.getByTestId('ctx'); + const contact = {id: 1, x: 20, y: 20}; + const landedAt = performance.now(); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(150 + FRAME_MS); + expectGrowthFromOnsetFrame(trigger, landedAt); + }); + it('springs a grown trigger back when the finger lifts before the commit', async () => { const trigger = renderMenu(); const contact = {id: 1, x: 20, y: 20}; From 4782e33680e235a08715d6f61e1377e8c1ca9e1e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:34:31 -0800 Subject: [PATCH 068/151] refactor(ContextMenu): the press feedback writes no ref during render The touch layer reads its press feedback through useCommittedRef and writes whether the recognizer follows a contact with useCommittedRefInto, into the ref the press feedback was handed. The press feedback reads whether it is shown through useCommittedRef. No behavior changes. --- .../core/src/ContextMenu/ContextMenuTouchLayer.tsx | 13 +++++++------ .../src/ContextMenu/contextMenuPressFeedback.ts | 6 +++--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 761088c8705d6..9722005f5cc09 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -18,7 +18,7 @@ import {flushSync} from 'react-dom'; import {isTerminal} from '../gestures/GestureRecognizer'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; -import {useCommittedRef} from '../hooks/useCommittedRef'; +import {useCommittedRef, useCommittedRefInto} from '../hooks/useCommittedRef'; import {contextMenu} from '../motion/uikit/contextMenu'; import {isElement} from '../utils/nodeType'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -82,8 +82,7 @@ export function ContextMenuTouchLayer({ isShown, isFollowedRef, ); - const feedbackRef = useRef(feedback); - feedbackRef.current = feedback; + const feedbackRef = useCommittedRef(feedback); const onCancelRef = useCommittedRef(onCancel); const hasPressOpenedRef = useRef(false); @@ -151,8 +150,10 @@ export function ContextMenuTouchLayer({ }, ); - isFollowedRef.current = () => - recognizer.numberOfTouches > 0 && !isTerminal(recognizer.state); + useCommittedRefInto( + isFollowedRef, + () => recognizer.numberOfTouches > 0 && !isTerminal(recognizer.state), + ); useImperativeHandle( ref, @@ -160,7 +161,7 @@ export function ContextMenuTouchLayer({ release: () => feedbackRef.current.release(), isTracking: () => recognizer.numberOfTouches > 0, }), - [recognizer], + [feedbackRef, recognizer], ); return null; diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index bdb80aa091ebd..ac64be308c7d6 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -18,6 +18,7 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useAttachment} from '../hooks/useAttachment'; +import {useCommittedRef} from '../hooks/useCommittedRef'; import { closestContextMenuTrigger, markContextMenuTrigger, @@ -107,8 +108,7 @@ export function useContextMenuPressFeedback( isFollowed: RefObject<() => boolean> = ALWAYS_FOLLOWED, ): ContextMenuPressFeedback { const animatorRef = useRef(null); - const isShownRef = useRef(isShown); - isShownRef.current = isShown; + const isShownRef = useCommittedRef(isShown); // Whether the visual carries a scale of ours (to put back and clear). const isGrownRef = useRef(false); // The menu the press opened is up: the growth holds until it closes. @@ -198,7 +198,7 @@ export function useContextMenuPressFeedback( {at: time}, ); }, - [animatorFor, isFollowed], + [animatorFor, isFollowed, isShownRef], ); const end = useCallback( From 01f5f222fa9c5f48043d33806411b26d11164149 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:35:53 -0800 Subject: [PATCH 069/151] docs(ContextMenu): the press feedback's text matches the pen change Since a pen's growth starts at its landing, nothing in ContextMenu reads the press machine's mark. The pressable coverage test drops its rule for a file that only reads the mark, and its header sentence, which matched nothing. A file comment that contradicted release() goes. The two test headers and one test comment say the growth follows a finger or a pen and ignores the mark. The popover story again names the growth it lacks, which this pull request ships. --- apps/storybook/stories/ContextMenu.stories.tsx | 2 +- .../ContextMenu/ContextMenuTouchGrowth.test.tsx | 7 ++++--- .../contextMenuPressFeedback.test.tsx | 6 +++--- .../src/ContextMenu/contextMenuPressFeedback.ts | 2 -- .../core/src/utils/pressableCoverage.test.ts | 16 +++------------- 5 files changed, 11 insertions(+), 22 deletions(-) diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index a86350bbc85de..665e2d620e5ea 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -816,7 +816,7 @@ export const TouchLongPressPopover: Story = { docs: { description: { story: - 'With `presentation="popover"`, ContextMenu keeps today’s menu on every device: a finger held for 500 ms opens it at the finger, with no iOS timeline. A finger on a device whose primary pointer is fine (a mouse or a trackpad) gets the same long press.', + 'With `presentation="popover"`, ContextMenu keeps today’s menu on every device: a finger held for 500 ms opens it at the finger, with no growth and no iOS timeline. A finger on a device whose primary pointer is fine (a mouse or a trackpad) gets the same long press.', }, }, }, diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index be05828997c8c..e345da679ccad 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -5,7 +5,8 @@ * @input ContextMenu under a finger in jsdom, with the compositor animator * replaced * @output Checks that the trigger's visual grows only while ContextMenu's - * recognizer follows a finger, and springs back when the recognizer fails + * recognizer follows a finger or a pen, and springs back when the + * recognizer fails * @position Unit tests of the press feedback's start and end in * packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx */ @@ -301,8 +302,8 @@ describe('ContextMenu’s growth under a finger', () => { it('grows the trigger at the onset when the press machine marks the press before the recognizer has the finger', async () => { const trigger = renderMenu(); const contact = {id: 1, x: 20, y: 20}; - // In a browser the press machine's mark comes first: its listener runs - // before the recognizer's, and the mark is read between the two. + // In a browser the press machine's mark can come first: its listener + // runs before the recognizer's. await pressMachineOn(trigger); const landedAt = performance.now(); dispatchTouch('touchstart', trigger, [contact], [contact]); diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx index c366d8f91b391..799d2b70f217d 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -3,9 +3,9 @@ /** * @file contextMenuPressFeedback.test.tsx * @input useContextMenuPressFeedback on a trigger, with the animator replaced - * @output Checks that the growth starts at the press machine's "on" and - * keeps going when the machine lets the press go. It returns when - * ContextMenu's recognizer ends the press with no menu. The growth plays + * @output Checks that the growth starts at the onset of the landing the + * recognizer reports, and ignores the press machine's mark. It returns + * when ContextMenu's recognizer ends the press with no menu. The growth plays * `springs.contextMenuLift`, and each return, then or as the menu closes, * `springs.contextMenuDismiss` * @position Unit tests of packages/core/src/ContextMenu/contextMenuPressFeedback.ts diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts index ac64be308c7d6..cf62e02963f60 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts @@ -14,8 +14,6 @@ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx */ -// Only the recognizer's failure or cancel returns the growth. - import {useCallback, useRef, type RefObject} from 'react'; import {useAttachment} from '../hooks/useAttachment'; import {useCommittedRef} from '../hooks/useCommittedRef'; diff --git a/packages/core/src/utils/pressableCoverage.test.ts b/packages/core/src/utils/pressableCoverage.test.ts index f8b21b40e3446..6aec0ff52c6d3 100644 --- a/packages/core/src/utils/pressableCoverage.test.ts +++ b/packages/core/src/utils/pressableCoverage.test.ts @@ -17,10 +17,7 @@ * - A file paints a press when its StyleX carries an `':active` key, a * `[data-astryx-press` arm, or composes `interactionOverlayStyles` or the * press owner's ready-made paint (`indicatorPressPaintStyles`, - * `rowPressPaintStyles`). It also paints one when its script follows the - * pressed state that a controller writes, as ContextMenu's growth does. A - * script that also writes that state is a press controller, so it is part - * of the model. + * `rowPressPaintStyles`). * - A file is marked when it calls `usePressFeedback(`. * - A file whose press arms are read off an ancestor scope marker * (`stylex.when.ancestor(':active', someScope)`, the way an indicator @@ -79,13 +76,6 @@ const source = new Map( // module writes some arms for a component, which composes them ready-made. const PRESS_ARM = /':active|'(?::is\()?\[data-astryx-press=|interactionOverlayStyles\.|indicatorPressPaintStyles\.|rowPressPaintStyles\./; -function paintsPress(text: string): boolean { - return ( - PRESS_ARM.test(text) || - (text.includes('getAttribute(PRESSED_ATTRIBUTE)') && - !text.includes('setAttribute(PRESSED_ATTRIBUTE')) - ); -} const ANCESTOR_ARM = /stylex\.when\.ancestor\(\s*'(?::active|\[data-astryx-press=[^)]*)',\s*(\w+)\s*,?\s*\)/g; @@ -158,7 +148,7 @@ function importers(file: string): string[] { } const pressArmFiles = [...source.entries()] - .filter(([file, text]) => !MODEL_FILES.has(file) && paintsPress(text)) + .filter(([file, text]) => !MODEL_FILES.has(file) && PRESS_ARM.test(text)) .map(([file]) => file) .sort(); @@ -242,7 +232,7 @@ describe('every surface that paints a press is reachable by the touch press cont ); const unexplained = marked.filter(file => { const text = source.get(file) ?? ''; - if (paintsPress(text)) { + if (PRESS_ARM.test(text)) { return false; } return ![...scopeNames].some(scope => From a1cc3023aca5f664062686279e94ea2e31ce5a9e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 02:55:26 -0800 Subject: [PATCH 070/151] test(ContextMenu): the stays-put case reads the menu after its entrance The case read the menu's box at its show and again after its entrance. The entrance animates a transform on the layer, from 8 px above, so a read that lands on a slow first frame looked like an 8 px move. The first read now waits for the entrance to end, and the later one for the trigger's growth to hold. Both read the box on screen, so a later move, by layout or by transform, still fails. A positive control moves the open menu's layer by a transform and checks that the read sees it. Tests only. --- ...tMenuLongPress.interaction.browser.spec.ts | 63 ++++++++++++++++--- 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index f1268d10f5499..83780059d29ae 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -664,6 +664,15 @@ async function untilMenuSettled(page: Page) { .toBe(0); } +/** The open menu's box on screen, with any transform on its layer. */ +const menuBox = async (page: Page) => + page.evaluate(() => { + const list = document + .querySelector('[role="menu"]') + ?.getBoundingClientRect(); + return list == null ? null : {x: list.x, y: list.y}; + }); + /** * The open menu's box and computed transform. Also every element from the * cursor anchor up that carries a transform, and the anchor's inline @@ -839,7 +848,7 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil } const menu = page.getByRole('menu', {name: 'Photo actions'}); // The cursor anchor (the trigger's last child), on screen and as laid out - // (engines differ on which one anchor positioning reads), and the menu. + // (engines differ on which one anchor positioning reads). const read = async () => trigger.evaluate(el => { const anchor = el.lastElementChild as HTMLElement | null; @@ -848,9 +857,6 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil const left = box.left + (box.width - host.offsetWidth) / 2; const top = box.top + (box.height - host.offsetHeight) / 2; const onScreen = anchor?.getBoundingClientRect(); - const list = document - .querySelector('[role="menu"]') - ?.getBoundingClientRect(); return { onScreen: onScreen == null ? null : {x: onScreen.x, y: onScreen.y}, laidOut: @@ -860,7 +866,6 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil x: left + host.clientLeft + anchor.offsetLeft, y: top + host.clientTop + anchor.offsetTop, }, - menu: list == null ? null : {x: list.x, y: list.y}, }; }); // The middle of the card and near its far corner, where an anchor placed @@ -875,23 +880,63 @@ test('the menu’s anchor sits under the finger, on screen and as laid out, whil }; await driver.play(hold(p, menuDisplayMs + 100)); await expect(menu).toBeVisible(); - const first = await read(); + // The entrance plays as a transform on the menu's layer, and a slow first + // frame (a cold shader cache) can hold it at its start: read once it ends. await untilMenuSettled(page); + const first = await read(); + const firstMenu = await menuBox(page); + // Later, once the trigger's growth holds at its full size. + await expect + .poll(async () => presentedScale(trigger)) + .toBeCloseTo(heldScale, 3); const later = await read(); + const laterMenu = await menuBox(page); await page.keyboard.press('Escape'); await expect(menu).toBeHidden(); // The trigger returns to its size before the next press. await expect .poll(async () => presentedScale(trigger), {timeout: 3000}) .toBe(1); - const detail = JSON.stringify({p, first, later}); + const detail = JSON.stringify({p, first, firstMenu, later, laterMenu}); expect(first.onScreen?.x, detail).toBeCloseTo(p.x, 0); expect(first.onScreen?.y, detail).toBeCloseTo(p.y, 0); expect(first.laidOut?.x, detail).toBeCloseTo(p.x, 0); expect(first.laidOut?.y, detail).toBeCloseTo(p.y, 0); - expect(later.menu?.x, detail).toBeCloseTo(first.menu?.x ?? NaN, 0); - expect(later.menu?.y, detail).toBeCloseTo(first.menu?.y ?? NaN, 0); + expect(laterMenu?.x, detail).toBeCloseTo(firstMenu?.x ?? NaN, 0); + expect(laterMenu?.y, detail).toBeCloseTo(firstMenu?.y ?? NaN, 0); + } +}); + +test('the stays-put check sees a menu that a transform moves after its show', async ({ + page, +}) => { + const {driver, trigger} = await openTouchStory(page); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger'); } + await driver.play( + hold( + { + x: Math.round(box.x + box.width / 2), + y: Math.round(box.y + box.height / 2), + }, + menuDisplayMs + 100, + ), + ); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); + await untilMenuSettled(page); + const before = await menuBox(page); + await page.evaluate(() => { + const layer = document + .querySelector('[role="menu"]') + ?.closest('[popover]'); + if (layer != null) { + layer.style.translate = '0 8px'; + } + }); + const after = await menuBox(page); + expect((after?.y ?? NaN) - (before?.y ?? NaN)).toBeCloseTo(8, 0); }); test('a drag past the tolerance after the commit opens nothing', async ({ From 01f789a4dbbf8503a6a4a65af164c359c9fbfd53 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 01:37:44 -0800 Subject: [PATCH 071/151] docs(ContextMenu): FR13 names the touch model's hold The docs call the popover's 500 ms path "the long press", and that path hands no finger to the menu. FR13 now says the touch model's hold opens the menu at the finger. Records only. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 48c146236f124..7f9d2308d6f4a 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -131,7 +131,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | | FR12 | Under a finger, a block trigger whose menu opens at the finger grows during a hold toward 1.0735 times its size on `springs.contextMenuLift`, from the onset, 150 ms after the finger lands, and it returns after a lift before the commit on `springs.contextMenuDismiss`, as FR5 names them. The hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured on iOS 26.2 (`motion/uikit/contextMenu.ts`): UIKit commits at 400 ms, shows the menu at 735 ms, and grows the view on a linear ramp chased by a spring. `spec:AST-094` FR4, FR45: the two moments are measured input, and the long-press presentation is a gesture component (FR5), so the growth and its return play their spring roles | -| FR13 | After a long press opens the menu at the finger, the same finger may slide onto an item without lifting; lifting over an item selects it, and lifting over no item leaves the menu open. A lift before the finger has moved UIMenu's handoff distance selects nothing (`spec:AST-094` FR33). | `module:DropdownMenu/useMenuPress` FR11; `spec:AST-094` FR33 | +| FR13 | After the touch model's hold opens the menu at the finger, the same finger may slide onto an item without lifting; lifting over an item selects it, and lifting over no item leaves the menu open. A lift before the finger has moved UIMenu's handoff distance selects nothing (`spec:AST-094` FR33). | `module:DropdownMenu/useMenuPress` FR11; `spec:AST-094` FR33 | ### Allowed variation From 469ef887b874f107af4a9b65928b6675a0636e32 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 10:12:05 -0800 Subject: [PATCH 072/151] fix(useMenuPress): continueGesture lists optionsRef in its deps Main now holds optionsRef through useCommittedRef, which the exhaustive-deps rule does not know is stable, so the continuation's callback lists it. The ref is the same object on every render, so nothing changes. --- packages/core/src/hooks/useMenuPress.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts index 1813c0ee8ec38..1a7f3a9247628 100644 --- a/packages/core/src/hooks/useMenuPress.ts +++ b/packages/core/src/hooks/useMenuPress.ts @@ -1050,7 +1050,7 @@ export function useMenuPress(input: UseMenuPressOptions): UseMenuPressReturn { installTouchMovePreventer(); } }, - [attach, installTouchMovePreventer], + [attach, installTouchMovePreventer, optionsRef], ); // Syncs the document listeners of the menu gesture counter with this mount. From 5adbafbaaeb8b5f9fb5fac8d8427a37e2c095233 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 12:15:26 -0800 Subject: [PATCH 073/151] test(ContextMenu): the shift cases set how late the page gets the move The case for a slight shift just before the menu's moment assumed the page got the move within 33 ms of its own time. In Chromium the page reads the timestamp the protocol hands over, and a test machine took up to two frames to deliver it, so the press waited 50 ms for a late move. In Chromium the case now sends the shift at 688 ms, 25 ms ahead of its stamp, and it checks that the move came on time and inside the press's wait. A new Chromium case sends the shift 60 ms after its stamp and checks that the menu waits 50 ms. WebKit stamps a touch as it arrives, so there the shift leaves at 688 ms. Tests only. --- ...tMenuLongPress.interaction.browser.spec.ts | 165 ++++++++++++++++-- 1 file changed, 148 insertions(+), 17 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 15b0f5c4a6d36..4c92e5683bf67 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -241,35 +241,166 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); -test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms when its move reaches the page on time (AST-094 FR12)', async ({ - page, -}) => { +/** The press counts a move as late when it reaches the page this long after its own time. */ +const LATE_INPUT_MS = 33; +/** How long the press waits after a late move that reached the page just before the menu's moment. */ +const LATE_MOVE_GAP_MS = 50; + +/** A hold that shifts 3 px once, as the page read it, on the page clock. */ +interface ShiftedHold { + start: number; + /** The shift's own time and when the page got it. */ + shift: [number, number]; + frames: number[]; + shown: number | null; + decided: number | null; +} + +/** + * A finger held still that shifts 3 px once, then lifts at 1000 ms. In + * Chromium the page reads the timestamp the protocol hands over, so the shift + * leaves at `sentMs` stamped `stampMs`, and the case sets how late the page + * gets it. WebKit stamps a touch as it arrives, so there the shift leaves at + * `sentMs`. + */ +async function holdWithShift( + page: Page, + browserName: string, + {sentMs, stampMs}: {sentMs: number; stampMs: number}, +): Promise { + await page.addInitScript(() => { + const w = window as unknown as {__shifts: [number, number][]}; + w.__shifts = []; + window.addEventListener( + 'pointermove', + event => { + w.__shifts.push([event.timeStamp, performance.now()]); + }, + {capture: true, passive: true}, + ); + }); const {driver, center} = await openTouchStory(page); await startFrameLog(page); - // One 3 px move at 700 ms, then still. An idle page gets the move at once. - await driver.play( - drag( - center, - {x: center.x + 3, y: center.y}, - {holdMs: 699, durationMs: 1, restMs: 300}, - ), - ); + if (browserName === 'chromium') { + const cdp = await page.context().newCDPSession(page); + const origin = Date.now(); + const at = async (ms: number) => + new Promise(resolve => { + setTimeout(resolve, Math.max(0, origin + ms - Date.now())); + }); + const touch = async ( + type: 'touchStart' | 'touchMove' | 'touchEnd', + ms: number, + dx: number | null, + ) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: dx == null ? [] : [{x: center.x + dx, y: center.y}], + timestamp: (origin + ms) / 1000, + }); + await touch('touchStart', 0, 0); + await at(sentMs); + await touch('touchMove', stampMs, 3); + await at(1000); + await touch('touchEnd', 1000, null); + } else { + await driver.play( + drag( + center, + {x: center.x + 3, y: center.y}, + {holdMs: sentMs - 1, durationMs: 1, restMs: 1000 - sentMs}, + ), + ); + } const frames = await readFrameLog(page); const start = await touchStartedAt(page); - const shown = await menuShownAt(page); - const decided = await menuShownTimerAt(page); - expect(shown, 'the menu never showed').not.toBeNull(); + const shifts = await page.evaluate( + () => (window as unknown as {__shifts: [number, number][]}).__shifts, + ); + expect(shifts.length, 'the shift reached the page').toBeGreaterThan(0); + return { + start, + shift: shifts[shifts.length - 1], + frames, + shown: await menuShownAt(page), + decided: await menuShownTimerAt(page), + }; +} + +/** The shift reached the page before the menu's moment, inside the press's wait. */ +function expectShiftInsideWait( + [, receivedAt]: [number, number], + moment: number, +) { + expect( + receivedAt, + 'the shift reached the page before the menu’s moment', + ).toBeLessThan(moment); + expect( + moment - receivedAt, + 'the shift reached the page inside the press’s wait before the moment', + ).toBeLessThan(LATE_MOVE_GAP_MS); +} + +test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms when its move reaches the page on time (AST-094 FR12)', async ({ + page, + browserName, +}) => { + // A phone gets a move within a frame. The protocol's own path can take two + // frames on a test machine, so the shift leaves 25 ms ahead of its stamp. + // A faster path brings it before its stamp: the press counts that negative + // lag as on time, as any lag up to 33 ms. Leaving at 688 ms, it reaches the + // page less than 50 ms before the moment, and before it on any path under + // 47 ms. + const run = await holdWithShift(page, browserName, { + sentMs: 688, + stampMs: 713, + }); + const moment = run.start + menuDisplayMs; + expectShiftInsideWait(run.shift, moment); + expect( + run.shift[1] - run.shift[0], + 'the shift reached the page on time', + ).toBeLessThanOrEqual(LATE_INPUT_MS); + expect(run.shown, 'the menu never showed').not.toBeNull(); // The moment's own timer task shows the menu: nothing waits. expect( - decided, + run.decided, 'the menu showed after the task that decided it', ).not.toBeNull(); - expectDecidedOnTime(frames, start + menuDisplayMs, decided as number); - const after = (shown as number) - start; + expectDecidedOnTime(run.frames, moment, run.decided as number); + const after = (run.shown as number) - run.start; expect(after).toBeGreaterThanOrEqual(menuDisplayMs); expect(after).toBeLessThan(menuDisplayMs + 20); }); +test('a finger that shifts slightly just before 735 ms gets the menu 50 ms later when its move reaches the page late (AST-094 FR12)', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'a touch stamped before it is sent needs Chromium’s protocol', + ); + // The shift leaves 60 ms after its stamp, so the page gets it late. + const run = await holdWithShift(page, browserName, { + sentMs: 688, + stampMs: 628, + }); + const moment = run.start + menuDisplayMs; + expectShiftInsideWait(run.shift, moment); + expect( + run.shift[1] - run.shift[0], + 'the shift reached the page late', + ).toBeGreaterThan(LATE_INPUT_MS); + expect(run.decided, 'the menu never showed').not.toBeNull(); + expect( + (run.decided as number) - moment, + 'the menu waited for moves still coming late', + ).toBeGreaterThanOrEqual(LATE_MOVE_GAP_MS - 1); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + test('the menu mounts at the commit, closed and out of the accessibility tree, and shows at 735 ms', async ({ page, }) => { From 44ab75552936ee37b250ebcbe2f1f8cccaa9bc0c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 13:44:32 -0800 Subject: [PATCH 074/151] test(ContextMenu): the late-touch growth case reads the curve's start The press feedback starts the growth in the first frame whose callback runs at or after the onset, and the curve starts when that callback runs. The case checked the frame's own time instead. When the onset fell between a frame's start and its callbacks, the growth was on time but the case failed. The case now reads the growth animation's own start time and checks that it is at or after the onset. The bound that the first grown frame comes within two frames of the onset stays. Tests only. --- ...tMenuLongPress.interaction.browser.spec.ts | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 4a018edc74cd4..6d3091c45cb9d 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1174,16 +1174,24 @@ test('a touch that reaches the page late grows from the first frame at its onset const record = { touchedAt: 0, handledAt: 0, - frames: [] as {t: number; scale: number}[], + frames: [] as {t: number; scale: number; start: number | null}[], }; (window as unknown as {__lateTouch: typeof record}).__lateTouch = record; const sample = (t: number) => { - const scale = getComputedStyle( - trigger?.firstElementChild as HTMLElement, - ).scale; + const visual = trigger?.firstElementChild as HTMLElement; + const scale = getComputedStyle(visual).scale; + // The growth's own curve and its start on the document timeline. + const growth = visual + .getAnimations() + .find(animation => + (animation.effect as KeyframeEffect | null) + ?.getKeyframes() + .some(keyframe => 'scale' in keyframe), + ); record.frames.push({ t, scale: scale === 'none' ? 1 : Number.parseFloat(scale), + start: growth?.startTime == null ? null : Number(growth.startTime), }); if (t - record.touchedAt < 320) { requestAnimationFrame(sample); @@ -1231,7 +1239,7 @@ test('a touch that reaches the page late grows from the first frame at its onset __lateTouch: { touchedAt: number; handledAt: number; - frames: {t: number; scale: number}[]; + frames: {t: number; scale: number; start: number | null}[]; }; } ).__lateTouch, @@ -1246,9 +1254,14 @@ test('a touch that reaches the page late grows from the first frame at its onset // further along than the spring one frame in. expect(before.scale).toBe(1); expect(first.scale).toBeLessThanOrEqual(played.at(frameMs / 1000) + 0.0005); - // On time: the curve starts in the first frame at or after the onset. So - // its first grown frame comes within two frames of the onset. - expect(before.t - touchedAt).toBeGreaterThanOrEqual(feedbackOnsetMs); + // On time: the curve starts at or after the onset, in the first frame whose + // callback runs at or after it. It starts when that callback runs, which + // can come after the frame's own time, so the curve's start is read. Its + // first grown frame comes within two frames of the onset. + expect(first.start, 'the growth has a start on the timeline').not.toBeNull(); + expect((first.start as number) - touchedAt).toBeGreaterThanOrEqual( + feedbackOnsetMs, + ); expect(first.t - touchedAt).toBeLessThanOrEqual( feedbackOnsetMs + 2 * frameMs + 1, ); From 42d9d3f7de73e929a166949d81b7a9fddd978ffc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 10:35:30 -0800 Subject: [PATCH 075/151] test(useMenuPress): a handed finger's lift cancels its own touchend A context menu's long press hands its finger to the menu with continueGesture. When another finger lands while the handed one slides, the guard at the handed finger's lift must still cancel that finger's touchend. Main now names the lifted touch from the touchstart after a pointerdown, and a handed finger has none in the menu. --- packages/core/src/hooks/useMenuPress.test.tsx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx index 4201843b9b0dc..7837fa966524e 100644 --- a/packages/core/src/hooks/useMenuPress.test.tsx +++ b/packages/core/src/hooks/useMenuPress.test.tsx @@ -1614,6 +1614,21 @@ describe('useMenuPress — a pointer that went down elsewhere is the opening pre expect(onSelect).toHaveBeenCalledWith('B'); }); + it("cancels a handed finger's own touchend at its lift, though another finger landed while it slid", () => { + const onSelect = vi.fn(); + const press: {current: UseMenuPressReturn | null} = {current: null}; + render(); + continueAt(press, 'touch'); + // A second finger lands while the handed one slides. The handed finger's + // touchstart came before the menu, so this one names another touch. + fireTouch(row('C'), 'touchstart', 9); + fireEvent.pointerMove(row('B'), {...handed, clientX: 0, clientY: 4}); + fireEvent.pointerMove(row('B'), {...handed, clientX: 0, clientY: 20}); + fireEvent.pointerUp(row('B'), {...handed, clientX: 0, clientY: 20}); + expect(onSelect).toHaveBeenCalledWith('B'); + expect(fireTouch(row('B'), 'touchend', 4).defaultPrevented).toBe(true); + }); + it('counts the distance from the first position the menu sees, not from where the finger was as it opened', () => { const press: {current: UseMenuPressReturn | null} = {current: null}; render(); From e165a7b5b4f1a6b60442e9fd9932e0c7ce65b74d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 10:35:30 -0800 Subject: [PATCH 076/151] fix(useMenuPress): a handed finger's touch stays unnamed The touchstart after a pointerdown names the touch the click guard cancels at the lift. A handed finger's touchstart came before the menu, so the next one is another finger's. continueGesture now attaches without naming a touch, and the guard takes the next touchend, which follows the handed finger's pointerup. --- packages/core/src/hooks/useMenuPress.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts index 8b42f30056bbb..a48c0bb17e127 100644 --- a/packages/core/src/hooks/useMenuPress.ts +++ b/packages/core/src/hooks/useMenuPress.ts @@ -820,7 +820,7 @@ export function useMenuPress(input: UseMenuPressOptions): UseMenuPressReturn { ); const attach = useCallback( - (pointerId: number) => { + (pointerId: number, namesTouch = true) => { detachRef.current?.(); const doc = getDocument(); const view = doc.defaultView; @@ -830,7 +830,7 @@ export function useMenuPress(input: UseMenuPressOptions): UseMenuPressReturn { // The touchstart after this pointerdown names the touch, so the guard // at the lift cancels only that touch's touchend. let stopTouchStart: (() => void) | null = null; - if (view != null) { + if (view != null && namesTouch) { stopTouchStart = subscribeInput(view, 'touchstart', event => { stopTouchStart?.(); stopTouchStart = null; @@ -1077,7 +1077,10 @@ export function useMenuPress(input: UseMenuPressOptions): UseMenuPressReturn { if (!isEnabled || gestureRef.current.phase !== 'idle') { return; } - attach(pointer.pointerId); + // This finger's touchstart came before the menu, so the next one is + // another finger's. Unnamed, the guard takes the next touchend, which + // follows this finger's pointerup. + attach(pointer.pointerId, false); // The menu opened under this pointer, so it is the opening press. isContinuedFingerRef.current = pointer.pointerType !== 'mouse'; gestureRef.current = { From 3632bb3c933dc8d182886a48405e745eb82ea35e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 14:34:03 -0800 Subject: [PATCH 077/151] docs(layer-runtime): ContextMenu's menu uses the outside-press watch The outside-interaction list still named a local outside mousedown listener for ContextMenu, and the close count named its mousedown close. ContextMenu's menu closes through Layer's outside-press watch, as the record's Owning code says. The list now puts it on the watch, judging the press types it names at their mousedown, and the count drops the old listener. Records only. --- docs/architecture/layer-runtime.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md index 4c94fb14225c8..53fa495217383 100644 --- a/docs/architecture/layer-runtime.md +++ b/docs/architecture/layer-runtime.md @@ -378,14 +378,13 @@ Outside interaction is not coordinated by the shared stack. Current paths close their own layers independently: - auto popovers use native light dismiss; -- BaseTypeahead's list, DateInput's calendar, DateTimeInput's time list and - ChatComposerInput's trigger menu, manual popovers, use Layer's outside-press - watch, +- BaseTypeahead's list, DateInput's calendar, DateTimeInput's time list, + ChatComposerInput's trigger menu and ContextMenu's menu, manual popovers, + use Layer's outside-press watch, which closes on a press that starts and ends outside the field and the list - and forgets a cancelled press (a scroll); + and forgets a cancelled press (a scroll); ContextMenu's menu judges the + press types it names at their `mousedown` (`pressTypes`); - native dialogs handle backdrop clicks locally; -- ContextMenu uses a local outside `mousedown` listener, which skips the - compatibility mouse events of the finger press that opened the menu; - Tooltip and HoverCard use hover/focus loss plus a touch-only outside listener; - sheets own scrim and swipe behavior; and - dropdown submenus encode their root-close relationship locally through @@ -393,7 +392,7 @@ close their own layers independently: One fact joins these paths, for a modal host's backdrop press (`family:overlay-dismissal` FR11). The outside-press watch, the touch-only -outside listener, the text fields' blur closes, ContextMenu's `mousedown` close, +outside listener, the text fields' blur closes, and a held Tooltip's focus-out release each record their close in a per-document count. A Dialog or Drawer backdrop press that sees the count change, or an auto popover close, between its pointer-down and its click leaves From 26f36d320f03be82c6bd53ee81d36966b7ee59f2 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 14:37:36 -0800 Subject: [PATCH 078/151] docs(ContextMenu): FR10's gap names the hold ContextMenu times itself FR10's implementation gap now says what ContextMenu owns until the headless context menu ships: its touch model's hold, which the shared context request's plain long press does not time, its right click and its menu keys. It closes on an outside press through Layer's watch. AST-094's shared-request paragraph points to that gap. Records only. --- docs/specs/AST-094-touch-presentations/spec.md | 3 ++- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 75c80df12ee41..1342682036810 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -877,7 +877,8 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and browser's own menu closed. A hold loses to a claim another recognizer made first. The headless context menu (`spec:AST-107` FR8) makes its request through it, and ContextMenu through that menu (`component:ContextMenu` - FR10). One module keeps these rules the same in every menu. The + FR10). FR10's implementation gap records that ContextMenu times its touch + model's hold itself. One module keeps these rules the same in every menu. The press model has a fine-pointer profile with no delay (FR11); and with a mouse, a trackpad, or a pen where the primary pointer is fine a reorder starts on a drag from its handle without a hold, while a pen where the diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 6e4a8119107ae..a05e51af01b9f 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -123,7 +123,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | | FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. | Current source and tests | | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | -| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | +| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships. ContextMenu owns its invocation: its touch model's hold (the 400 ms commit, the 735 ms display and the drift rule, which `gestures/contextRequest.ts`'s plain long press does not time), its right click and its menu keys. It owns its open state and cleanup, and closes on an outside press through Layer's outside-press watch. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | | FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | From 68be391f34e85271b79cb5fdbec6b6211db8c9fe Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 14:40:23 -0800 Subject: [PATCH 079/151] test(ContextMenu): the late-move case bounds the wait from above The case for a move that reaches the page late checked only that the menu waited at least 49 ms, so a wait far past the 50 ms the press allows passed. It now also checks that the wait stays under 70 ms, the on-time case's 20 ms of slack. Tests only. --- .../ContextMenuLongPress.interaction.browser.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 4c92e5683bf67..8f49aea52f68c 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -398,6 +398,10 @@ test('a finger that shifts slightly just before 735 ms gets the menu 50 ms later (run.decided as number) - moment, 'the menu waited for moves still coming late', ).toBeGreaterThanOrEqual(LATE_MOVE_GAP_MS - 1); + expect( + (run.decided as number) - moment, + 'the menu waited no longer than the press allows', + ).toBeLessThan(LATE_MOVE_GAP_MS + 20); await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); From a4b918186ecaed92a9f1f49ef114509338a61df1 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 12 Nov 2026 14:53:03 -0800 Subject: [PATCH 080/151] test(useMenuPress): name the handed-finger case for what it proves The case lands a touchstart alone while a handed finger slides. A real second finger's pointerdown ends the gesture first, so the case does not show a second finger's slide. It shows that a touchstart the handed finger did not send leaves the guard on the next touchend, and it is named for that. Tests only. --- packages/core/src/hooks/useMenuPress.test.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx index 7837fa966524e..79ec4058308d8 100644 --- a/packages/core/src/hooks/useMenuPress.test.tsx +++ b/packages/core/src/hooks/useMenuPress.test.tsx @@ -1614,13 +1614,14 @@ describe('useMenuPress — a pointer that went down elsewhere is the opening pre expect(onSelect).toHaveBeenCalledWith('B'); }); - it("cancels a handed finger's own touchend at its lift, though another finger landed while it slid", () => { + it("leaves a handed finger's guard on the next touchend after a touchstart the finger did not send", () => { const onSelect = vi.fn(); const press: {current: UseMenuPressReturn | null} = {current: null}; render(); continueAt(press, 'touch'); - // A second finger lands while the handed one slides. The handed finger's - // touchstart came before the menu, so this one names another touch. + // The handed finger's touchstart came before the menu, so a touchstart + // after the handoff is not its own. A real second finger's pointerdown + // ends the gesture first, so this one comes alone. fireTouch(row('C'), 'touchstart', 9); fireEvent.pointerMove(row('B'), {...handed, clientX: 0, clientY: 4}); fireEvent.pointerMove(row('B'), {...handed, clientX: 0, clientY: 20}); From 9710f276acfc26d50d18170f8974a5a0a7fb04e9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 09:48:11 -0800 Subject: [PATCH 081/151] test(ContextMenu): a held finger on a Table header gets its menu there A Table's sortable header leaves its ContextMenu trigger unpositioned, so the cell holds the cursor anchor. A right click there opens the menu at the pointer. The new case holds a finger on the same header under the touch model and checks the anchor sits at the finger too. It fails at the merge: the anchor lands one cell padding short. --- ...tMenuLongPress.interaction.browser.spec.ts | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 8f49aea52f68c..6641961be9e3d 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -241,6 +241,36 @@ test('a finger still down gets the menu at 735 ms (iOS 26.2), not before', async await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); +test('a finger held on a Table’s sortable header gets the menu where it landed', async ({ + page, +}) => { + // The header leaves its trigger unpositioned, so the cell holds the cursor + // anchor. A finger's point is measured from that cell, as a pointer's is. + await openStory( + page, + storybook(), + 'core-tablecolumnresize--with-sortable-columns', + ); + const driver = await touchDriver(page); + const header = page.getByRole('columnheader', {name: /Name/}); + const box = await header.boundingBox(); + if (box == null) { + throw new Error('no Name header'); + } + const point = { + x: Math.round(box.x + box.width / 2), + y: Math.round(box.y + box.height / 2), + }; + await driver.play(hold(point, menuDisplayMs + 200)); + await expect(page.getByRole('menu')).toBeVisible(); + const anchor = await page + .locator('span[aria-hidden="true"][style*="anchor-name"]') + .boundingBox(); + // The menu hangs from a 1px anchor placed at the finger. + expect(anchor?.x).toBeCloseTo(point.x, 0); + expect(anchor?.y).toBeCloseTo(point.y, 0); +}); + /** The press counts a move as late when it reaches the page this long after its own time. */ const LATE_INPUT_MS = 33; /** How long the press waits after a late move that reached the page just before the menu's moment. */ From 85d7a36c910d18bcb799d4fb0220ddfea6f65428 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 09:48:24 -0800 Subject: [PATCH 082/151] fix(ContextMenu): a finger's point is measured from the anchor's box Main now places the cursor anchor relative to its containing block, which is the cell when a Table leaves the trigger unpositioned. The touch path still measured the finger from the trigger, so a held finger on a Table header got its menu one cell padding short. It now measures from the same box as openAtLocalPoint. --- packages/core/src/ContextMenu/ContextMenu.tsx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index c164f3048fe9f..b467cff6d4636 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -709,11 +709,12 @@ export function ContextMenu({ } }, [layer, usesBottomSheet]); - // A client point in the trigger's own coordinates, where the cursor anchor - // lives. It stays inside the trigger's box. + // A client point in the cursor anchor's coordinates: measured from its + // containing block, as `openAtLocalPoint` reads them. It stays inside that + // box. const toTriggerLocal = useCallback( (point: {x: number; y: number}): {x: number; y: number} => { - const rect = triggerRef.current?.getBoundingClientRect(); + const rect = getAnchorBaseRect(); if (rect == null) { return point; } @@ -722,7 +723,7 @@ export function ContextMenu({ y: Math.min(Math.max(point.y - rect.top, 0), rect.height), }; }, - [], + [getAnchorBaseRect], ); const handleContextMenu = useCallback( From bb998bec806a5a1d7b977fd4c8ceb0cfd6e5e1b3 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 13:55:30 -0800 Subject: [PATCH 083/151] test(ContextMenu): a finger before the touch layer loads waits for it ContextMenu's touch layer brings the gesture host and the long-press recognizer into every page that renders a ContextMenu, Table's included, through a static import. Three red-first checks: - a boundary test: neither ContextMenu's entry nor Table's context-menu module reaches the layer, its recognizer or the gesture host statically, and only a loader imports the layer, through import(); - gesture-host cases: a finger whose touchstart went by before its recognizer attached begins from that touchstart at the host's time now, and its later moves and lift reach the recognizer; - browser cases: with the layer's chunk held back, a finger that landed first gets the menu 735 ms after the load, not after the landing. A finger that lifts first is a plain tap, and a right click opens at once. --- ...tMenuLongPress.interaction.browser.spec.ts | 81 ++++++++++++ .../contextMenuTouchLoader.boundary.test.ts | 122 ++++++++++++++++++ .../gestures/__tests__/GestureHost.test.ts | 56 ++++++++ 3 files changed, 259 insertions(+) create mode 100644 packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 6641961be9e3d..7d3d96b7ea0be 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -271,6 +271,87 @@ test('a finger held on a Table’s sortable header gets the menu where it landed expect(anchor?.y).toBeCloseTo(point.y, 0); }); +/** The touch layer's own chunk, which loads after the page's first paint. */ +const TOUCH_LAYER_CHUNK = /\/ContextMenuTouchLayer-[\w-]+\.js(?:\?.*)?$/; + +/** + * Holds back the touch layer's chunk. The call it returns releases the chunk + * and returns when, on the page clock. + */ +async function holdTouchLayer(page: Page): Promise<() => Promise> { + let release = () => {}; + const held = new Promise(resolve => { + release = resolve; + }); + await page.route(TOUCH_LAYER_CHUNK, async route => { + await held; + await route.continue(); + }); + return async () => { + const releasedAt = await page.evaluate(() => performance.now()); + release(); + return releasedAt; + }; +} + +/** How long a finger stays down before the held chunk is released, ms. */ +const BEFORE_LOAD_MS = 300; + +test('a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load', async ({ + page, +}) => { + const releaseLayer = await holdTouchLayer(page); + const {driver, center} = await openTouchStory(page); + const finger = await driver.press(center); + const start = await touchStartedAt(page); + await page.waitForFunction( + dueAt => performance.now() > dueAt, + start + BEFORE_LOAD_MS, + ); + const released = await releaseLayer(); + await expect + .poll(async () => menuShownAt(page), {timeout: 5000}) + .not.toBeNull(); + const shown = (await menuShownAt(page)) as number; + expect( + shown - start, + 'the menu showed before its touch layer loaded', + ).toBeGreaterThanOrEqual(BEFORE_LOAD_MS + menuDisplayMs); + expect(shown - released).toBeGreaterThanOrEqual(menuDisplayMs); + // The chunk, its imports and the layer's mount fit in this. + expect(shown - released).toBeLessThan(menuDisplayMs + 500); + await finger.lift(); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + +test('a finger that lifts before the touch layer loads makes a plain tap: one click, and no menu once the layer loads', async ({ + page, +}) => { + const releaseLayer = await holdTouchLayer(page); + const {driver, center} = await openTouchStory(page); + test.skip(!driver.drivesNativeGestures, CLICK_FROM_SCRIPT_SKIP); + const clicks = await countTriggerClicks(page); + await driver.play(hold(center, 250)); + await expect.poll(clicks).toBe(1); + const released = await releaseLayer(); + await page.waitForFunction( + dueAt => performance.now() > dueAt, + released + menuDisplayMs + 300, + ); + expect(await menuShownAt(page)).toBeNull(); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); + expect(await clicks()).toBe(1); +}); + +test('a right click opens the menu at once while the touch layer has not loaded', async ({ + page, +}) => { + await holdTouchLayer(page); + const {trigger} = await openTouchStory(page); + await trigger.click({button: 'right'}); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); +}); + /** The press counts a move as late when it reaches the page this long after its own time. */ const LATE_INPUT_MS = 33; /** How long the press waits after a late move that reached the page just before the menu's moment. */ diff --git a/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts b/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts new file mode 100644 index 0000000000000..de2cd5889b08e --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts @@ -0,0 +1,122 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file contextMenuTouchLoader.boundary.test.ts + * @input The static import graphs of the ContextMenu entry and of Table's + * context-menu module, and every core source file + * @output The source boundary check for ContextMenu's touch layer: no entry's + * static graph reaches the layer, its recognizer or the gesture code under + * it, and only the loader imports the layer, through `import()` + * @position Testing; the before-load behavior is in ContextMenu.test.tsx + */ + +import {existsSync, readFileSync, readdirSync, statSync} from 'node:fs'; +import {dirname, join, relative, resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {describe, expect, it} from 'vitest'; + +const here = dirname(fileURLToPath(import.meta.url)); +const coreSrc = join(here, '..'); + +/** The touch modules no ContextMenu entry may import statically. */ +const TOUCH_MODULES = [ + 'ContextMenu/ContextMenuTouchLayer.tsx', + 'ContextMenu/contextMenuPress.ts', + 'gestures/GestureHost.ts', + 'gestures/GestureArena.ts', +]; + +/** The source with its comments removed, so prose cannot pass or fail it. */ +function code(source: string): string { + return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); +} + +/** The relative modules a file imports statically, types left out. */ +function staticImports(file: string): string[] { + const body = code(readFileSync(file, 'utf8')); + const specifiers = [ + ...body.matchAll( + /^\s*(?:import|export)\s+(?!type\b)(?:[^'";]*?\sfrom\s+)?['"]([^'"]+)['"]/gm, + ), + ].map(match => match[1]); + return specifiers.flatMap(specifier => { + if (!specifier.startsWith('.')) { + return []; + } + const base = resolve(dirname(file), specifier); + const found = [ + base, + `${base}.ts`, + `${base}.tsx`, + join(base, 'index.ts'), + join(base, 'index.tsx'), + ].find(path => existsSync(path) && statSync(path).isFile()); + return found == null ? [] : [found]; + }); +} + +/** Each touch module the entry reaches, with the chain that brings it. */ +function touchChains(entry: string): string[] { + const start = join(coreSrc, entry); + const parent = new Map([[start, null]]); + const queue = [start]; + const chains: string[] = []; + while (queue.length > 0) { + const file = queue.shift()!; + const name = relative(coreSrc, file); + if (TOUCH_MODULES.includes(name)) { + const chain: string[] = []; + for (let at: string | null = file; at != null; at = parent.get(at)!) { + chain.unshift(relative(coreSrc, at)); + } + chains.push(chain.join(' → ')); + continue; + } + for (const next of staticImports(file)) { + if (!parent.has(next)) { + parent.set(next, file); + queue.push(next); + } + } + } + return chains; +} + +function sourceFiles(dir: string): string[] { + const out: string[] = []; + for (const name of readdirSync(dir)) { + const path = join(dir, name); + if (statSync(path).isDirectory()) { + if (name !== '__tests__' && name !== 'node_modules') { + out.push(...sourceFiles(path)); + } + } else if ( + /\.(ts|tsx)$/.test(name) && + !/\.(test|spec)\.(ts|tsx)$/.test(name) + ) { + out.push(path); + } + } + return out; +} + +describe('ContextMenu loads its touch layer after first paint', () => { + it.each(['ContextMenu/index.ts', 'Table/tableContextMenu.tsx'])( + '%s reaches no touch module statically', + entry => { + expect(touchChains(entry)).toEqual([]); + }, + ); + + it('imports the touch layer only from its loader, through import()', () => { + const layer = join(coreSrc, 'ContextMenu/ContextMenuTouchLayer.tsx'); + const importers = sourceFiles(coreSrc) + .filter(file => staticImports(file).includes(layer)) + .map(file => relative(coreSrc, file)); + expect(importers).toEqual([]); + const loaderPath = join(here, 'contextMenuTouchLoader.ts'); + expect(existsSync(loaderPath)).toBe(true); + const loader = code(readFileSync(loaderPath, 'utf8')); + expect(loader).toMatch(/import\(\s*'\.\/ContextMenuTouchLayer'\s*\)/); + }); +}); diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts index 7f15746796097..8a031777402f5 100644 --- a/packages/core/src/gestures/__tests__/GestureHost.test.ts +++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts @@ -4480,6 +4480,62 @@ describe('GestureHost.fingersDown', () => { }); }); +describe('a late begin: a finger that landed before its recognizer attached', () => { + it('begins the finger from its own touchstart at the host’s time now, so a hold counts from then', () => { + const {handle} = mount('
'); + const press = new LongPressGestureRecognizer({minimumPressDuration: 500}); + const states: string[] = []; + press.addListener(recognizer => states.push(recognizer.state)); + const finger = {id: 1, x: 10, y: 10, target: handle}; + // Nothing on the page listens as the finger lands. + const landed = touch('touchstart', handle, [finger], [finger], 0); + clock.time = 300; + detachers.push(host.attach(handle, press)); + host.beginLateTouches(landed as TouchEvent); + expect(press.numberOfTouches).toBe(1); + clock.runDue(799); + expect(states).not.toContain('began'); + clock.runDue(800); + expect(states).toContain('began'); + touch('touchend', handle, [finger], [], 900); + expect(press.numberOfTouches).toBe(0); + }); + + it('follows the late finger’s moves: a drift past the press’s limit fails it', () => { + const {handle} = mount('
'); + const press = new LongPressGestureRecognizer({minimumPressDuration: 500}); + const states: string[] = []; + press.addListener(recognizer => states.push(recognizer.state)); + const finger = {id: 1, x: 10, y: 10, target: handle}; + const landed = touch('touchstart', handle, [finger], [finger], 0); + clock.time = 300; + detachers.push(host.attach(handle, press)); + host.beginLateTouches(landed as TouchEvent); + const moved = {...finger, x: 60}; + touch('touchmove', handle, [moved], [moved], 350); + clock.runDue(1000); + expect(states).not.toContain('began'); + touch('touchend', handle, [moved], [], 1000); + }); + + it('begins nothing again from a touchstart it already heard', () => { + const {handle} = mount('
'); + const press = new LongPressGestureRecognizer({minimumPressDuration: 500}); + const states: string[] = []; + press.addListener(recognizer => states.push(recognizer.state)); + detachers.push(host.attach(handle, press)); + const finger = {id: 1, x: 10, y: 10, target: handle}; + const landed = touch('touchstart', handle, [finger], [finger], 0); + clock.time = 300; + host.beginLateTouches(landed as TouchEvent); + expect(press.numberOfTouches).toBe(1); + // The hold still counts from the touchstart the host heard. + clock.runDue(500); + expect(states).toContain('began'); + touch('touchend', handle, [finger], [], 600); + }); +}); + describe('where the primary pointer is fine (spec:AST-094 FR43, FR24)', () => { /** Quiets the development warning, and returns its spy. */ function quietWarning() { From 30b6b1e74ee13ec7fc213b3f2100e86f6679dcf4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 14:12:07 -0800 Subject: [PATCH 084/151] feat(ContextMenu): the touch layer loads after first paint ContextMenu imported its touch layer statically, so every page that renders a ContextMenu, Table's cells included, carried the gesture host, the arena and the long-press recognizer in its first load. A loader now brings the layer in once per page: after first paint, at idle within 2,000 ms, and only while the touch model applies. An input never starts or hurries the load. A finger that lands before the load keeps its touchstart on the trigger. As the layer mounts, it hands that touchstart to the gesture host's new late begin, so the hold starts then. The browser's own long-press menu waits for that hold. A right click and the menu keys never wait. Records: component:ContextMenu FR12 and spec:AST-094 FR43 gain the matching lines, and the touch-timeline changeset says when the code loads. --- .changeset/contextmenu-touch-timeline.md | 2 +- .../specs/AST-094-touch-presentations/spec.md | 6 +- .../ContextMenu/ContextMenu.spec.md | 4 +- .../core/src/ContextMenu/ContextMenu.test.tsx | 82 +++++++++++++ packages/core/src/ContextMenu/ContextMenu.tsx | 48 ++++++-- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 32 ++++- ...tMenuLongPress.interaction.browser.spec.ts | 47 ++++++- .../src/ContextMenu/contextMenuTouchLoader.ts | 116 ++++++++++++++++++ packages/core/src/gestures/GestureHost.ts | 19 ++- 9 files changed, 333 insertions(+), 23 deletions(-) create mode 100644 packages/core/src/ContextMenu/contextMenuTouchLoader.ts diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index 4160e64376434..59b0d7495714d 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A touch open lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it; a finger held before then starts the hold once it loads. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 0f104a0db6826..080497c83d68b 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -831,7 +831,10 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and component or module record sets on purpose, such as `component:Thumbnail` AR4's, is unaffected. Mobile size increases belong to theme adaptations (DEC-20). - **FR43 — Gestures work on the web.** Gestures attach for every pointer, a - mouse, a pen, and a finger, not only a coarse primary pointer. A part that + mouse, a pen, and a finger, not only a coarse primary pointer. A recognizer + that attaches while a finger is down on its element may begin that finger + from the finger's own touchstart, at attach time; the host still begins + fingers only from Touch Events. A part that follows a pointer's drag, such as a switch's or a slider's thumb, a sheet, a pager, a picker wheel or a row, follows a mouse, a pen, a trackpad and a finger alike, with the same rubber band past its ends, wherever its record @@ -1160,6 +1163,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li | FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails | | FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails | | FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails | +| FR43 late begin | Gesture host unit tests on a finger that lands before its recognizer attaches | a finger begun at the attach from its own touchstart; its later drift past the press's limit; a touchstart the host already heard | a late finger whose hold counts from its touchstart rather than the attach, a late finger whose later moves or lift miss its recognizer, or a touchstart begun twice fails | | FR44 | Unit tests of a pen press a window blur ends, on a Switch, a Slider and the host, under a coarse and a fine pointer | a pen press on a Switch and on a Slider, blur mid-press: nothing toggles or commits; a pen whose contact ends in `pointercancel` | with the host keeping no note of a blur-cancelled pen, the Switch toggles at the pen's click | | all | iOS simulator: the UIKit reference capture and the same gesture in Safari; real iOS Safari devices; Android Chrome in the Android emulator (DEC-27) | per component | an unmatched curve or timing is a parity defect | | all (DEC-31) | The evidence-carry check, before device or emulator evidence from an earlier head counts at a later head | a later head that only merges `main`; the pull request's own changes byte-identical or changed; a merge that changes a file the pull request changes, a direct import of those changes, a shared motion or layer module, or none of them; a generated file among the pull request's own files that CI proves regenerates identically, or does not prove; a commit, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, or knowledge records, or not | the evidence-carry check compares the PR's own diff between the two heads, and the merge's changed files against the files the PR changes, the changes' direct imports and the shared motion and layer modules (currently `motion/transientCopy`, `motion/inertClone`, `motion/animator`, `motion/carryAnimations`, `Layer/useLayer`, `hooks/usePager`); any overlap fails, except a generated file among the pull request's own files that CI proves regenerates identically at the new head; a changed own diff, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, knowledge records or `.changeset/` release notes, passes | diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index a05e51af01b9f..6d712825d82e5 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -125,7 +125,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships. ContextMenu owns its invocation: its touch model's hold (the 400 ms commit, the 735 ms display and the drift rule, which `gestures/contextRequest.ts`'s plain long press does not time), its right click and its menu keys. It owns its open state and cleanup, and closes on an outside press through Layer's outside-press watch. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | -| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | +| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | ### Allowed variation @@ -276,7 +276,7 @@ anchor is positioning infrastructure rather than consumer anatomy. | FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | | FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | | FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | -| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does"; `contextMenuPress.test.ts` | A held finger: the commit and the menu's display | A commit or a display off UIKit's moments fails. | `audit:ContextMenu/behavior` | +| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" | A held finger: the commit and the menu's display; a finger down before the touch layer loads | A commit or a display off UIKit's moments fails. A hold that starts before the touch layer loads fails. | `audit:ContextMenu/behavior` | | Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | | RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index 2c14407a13189..b90b42d0cd9ea 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -32,6 +32,10 @@ import { import userEvent from '@testing-library/user-event'; import {readFileSync} from 'node:fs'; import {ContextMenu} from './ContextMenu'; +import { + __loadContextMenuTouchLayerForTest, + __resetContextMenuTouchLayerForTest, +} from './contextMenuTouchLoader'; import {ContextMenuGroup} from './index'; import { ContextMenuItem, @@ -53,6 +57,9 @@ import {contextMenu} from '../motion/uikit/contextMenu'; // The touch sheet is loaded lazily; resolve its modules once up front, so // ContextMenu's own lazy sheet renders within the cases' waitFor. beforeAll(warmMenuBottomSheet, 20000); +// The touch layer loads after first paint. These cases hold a finger once the +// page has settled, so they load it up front; the before-load cases reset it. +beforeAll(__loadContextMenuTouchLayerForTest, 20000); function NestedDismissibleLayer({onDismiss}: {onDismiss: () => void}) { const [isOpen, setIsOpen] = useState(true); @@ -870,6 +877,81 @@ describe.each([ press.up(); }); + describe('before its touch layer loads', () => { + // The page's one load waits for a frame these cases never run, so each + // case loads the layer when it chooses. + beforeEach(() => { + __resetContextMenuTouchLayerForTest(); + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0); + }); + afterEach(async () => { + vi.mocked(window.requestAnimationFrame).mockRestore(); + await __loadContextMenuTouchLayerForTest(); + }); + const loadLayer = async () => + act(async () => { + await __loadContextMenuTouchLayerForTest(); + }); + + it('starts the hold of a finger that landed before the load once the layer loads', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(1000); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs - 1); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('opens nothing for a finger lifted before the load', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(200); + press.up(); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs * 2); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + }); + + it('keeps the browser’s own long-press menu from opening it for a finger held through the load', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(500); + const opened = fireEvent( + trigger, + new MouseEvent('contextmenu', {bubbles: true, cancelable: true}), + ); + expect(opened).toBe(false); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('opens at once for a right click or the menu key, with no finger down', () => { + const trigger = renderMenu(); + fireEvent.contextMenu(trigger, {clientX: 10, clientY: 10}); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + }); + + it('schedules the load at the first ContextMenu under the touch model, for after a frame, and a finger does not start it', () => { + const trigger = renderMenu(); + expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1); + const press = finger(trigger); + press.down(); + advance(1000); + press.up(); + expect(window.requestAnimationFrame).toHaveBeenCalledTimes(1); + }); + }); + it('mounts the menu, closed, at the commit, and shows that element at 735 ms', () => { const trigger = renderMenu(); const press = finger(trigger); diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index b467cff6d4636..1cb65e2ff1a1b 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -5,7 +5,7 @@ * @file ContextMenu.tsx * @input Uses React, StyleX, useLayer, shared layer dismissal, BottomSheet, * useListFocus, the presentation resolver (usePresentation), useLongPress, - * and the touch layer (ContextMenuTouchLayer) + * and the touch layer (ContextMenuTouchLayer), which loads after first paint * @output Exports ContextMenu with cursor-popover and touch-sheet presentations * @position Core implementation; consumed by index.ts * @@ -39,6 +39,7 @@ * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs * - /packages/core/src/ContextMenu/ContextMenu.test.tsx * - /packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx (the touch layer) + * - /packages/core/src/ContextMenu/contextMenuTouchLoader.ts (its load) * - /packages/core/src/ContextMenu/contextMenuPress.ts (touch timeline) * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx @@ -88,10 +89,8 @@ import {useMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; import {shadowHostOf} from '../utils/flatTree'; import {usePresentation} from '../utils/presentation'; -import { - ContextMenuTouchLayer, - type ContextMenuTouchHandle, -} from './ContextMenuTouchLayer'; +import type {ContextMenuTouchHandle} from './ContextMenuTouchLayer'; +import {useContextMenuTouchLayer} from './contextMenuTouchLoader'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import { @@ -443,6 +442,17 @@ export function ContextMenu({ // The mounted touch layer, which says whether it times a finger. const touchHandleRef = useRef(null); + // The touch layer loads after the page's first paint, and only while the + // touch model applies. + const TouchLayer = useContextMenuTouchLayer(touchModes && !isDisabled); + // A finger that lands before the touch layer has loaded. The layer begins + // it as it mounts, if the finger is still down. + const lateTouchRef = useRef(null); + const takeLateTouch = useCallback(() => { + const touchStart = lateTouchRef.current; + lateTouchRef.current = null; + return touchStart; + }, []); const updateOpenState = useCallback( (nextIsOpen: boolean) => { @@ -809,9 +819,20 @@ export function ContextMenu({ const handleTriggerTouchStart = useCallback( (event: React.TouchEvent) => { handleLongPressTouchStart(event); + if (touchModes && !isDisabled && TouchLayer == null) { + // Kept while the touch layer loads: one finger, until it lifts. + lateTouchRef.current = + event.touches.length === 1 ? event.nativeEvent : null; + } onTouchStartProp?.(event); }, - [handleLongPressTouchStart, onTouchStartProp], + [ + handleLongPressTouchStart, + onTouchStartProp, + touchModes, + isDisabled, + TouchLayer, + ], ); const handleTriggerTouchMove = useCallback( (event: React.TouchEvent) => { @@ -822,6 +843,7 @@ export function ContextMenu({ ); const handleTriggerTouchEnd = useCallback( (event: React.TouchEvent) => { + lateTouchRef.current = null; handleLongPressTouchEnd(event); onTouchEndProp?.(event); }, @@ -829,6 +851,7 @@ export function ContextMenu({ ); const handleTriggerTouchCancel = useCallback( (event: React.TouchEvent) => { + lateTouchRef.current = null; handleLongPressTouchCancel(event); onTouchCancelProp?.(event); }, @@ -840,9 +863,13 @@ export function ContextMenu({ // the public API does not promise as cancelable. const handleTriggerContextMenu = useCallback( (event: React.MouseEvent) => { - if (touchHandleRef.current?.isTracking() === true) { + if ( + touchHandleRef.current?.isTracking() === true || + lateTouchRef.current != null + ) { // The browser's own long-press menu (Android Chrome) for a finger the - // recognizer is timing: the recognizer decides, not this event. + // recognizer is timing, or will time once the touch layer loads: the + // recognizer decides, not this event. event.preventDefault(); } else { handleContextMenu(event); @@ -1017,13 +1044,14 @@ export function ContextMenu({ })} /> - {touchModes && !isDisabled ? ( - ) : null} diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 37abb46eee94e..53ef82953155b 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -8,13 +8,21 @@ * foundation and the UIKit context-menu constants * @output ContextMenuTouchLayer: renders nothing; runs the trigger's press * recognizer while ContextMenu is under the touch model - * @position Rendered by ContextMenu while the touch model applies + * @position Loaded after the page's first paint (contextMenuTouchLoader.ts); + * rendered by ContextMenu while the touch model applies * * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx */ -import {useImperativeHandle, useRef, type Ref, type RefObject} from 'react'; +import { + useEffect, + useImperativeHandle, + useRef, + type Ref, + type RefObject, +} from 'react'; import {flushSync} from 'react-dom'; +import {getGestureHost} from '../gestures/GestureHost'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {useCommittedRef} from '../hooks/useCommittedRef'; @@ -40,6 +48,11 @@ export interface ContextMenuTouchLayerProps { onCommit?: () => void; /** The press ended with no menu: what mounted at the commit can go. */ onCancel?: () => void; + /** + * The `touchstart` of a finger that landed before this layer loaded and is + * still down, else null. Read once, as the layer mounts. + */ + takeLateTouch?: () => TouchEvent | null; } /** @@ -50,7 +63,8 @@ export interface ContextMenuTouchLayerProps { * lift sends no click and no compatibility mouse events. The menu opens where * the finger landed: at `menuDisplayMs` if it is still down, or at the lift. * Before the commit, a lift, a second finger or a scroll gets no menu. So - * does a drift past the tolerance before the menu shows. + * does a drift past the tolerance before the menu shows. A finger that landed + * before the layer loaded starts its hold as the layer mounts. */ export function ContextMenuTouchLayer({ triggerRef, @@ -58,6 +72,7 @@ export function ContextMenuTouchLayer({ onOpen, onCommit, onCancel, + takeLateTouch, }: ContextMenuTouchLayerProps): null { const onCancelRef = useCommittedRef(onCancel); const hasPressOpenedRef = useRef(false); @@ -121,5 +136,16 @@ export function ContextMenuTouchLayer({ [recognizer], ); + // Syncs a finger that landed before this layer loaded with the gesture + // host. It runs after the recognizer attaches, so the host begins that + // finger now and the hold starts at this mount. + useEffect(() => { + const touchStart = takeLateTouch?.() ?? null; + const trigger = triggerRef.current; + if (touchStart != null && trigger != null) { + getGestureHost(trigger.ownerDocument).beginLateTouches(touchStart); + } + }, [takeLateTouch, triggerRef]); + return null; } diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 7d3d96b7ea0be..37c27fd597dcb 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -45,7 +45,9 @@ interface TouchStory { async function openTouchStory( page: Page, story = 'core-contextmenu--touch-long-press', + {waitsForTouchLayer = true}: {waitsForTouchLayer?: boolean} = {}, ): Promise { + const touchLayerChunk = waitsForTouchLayer ? watchTouchLayer(page) : null; await installInputLog(page); // Note when the menu is asked to show, on the page clock (no per-frame // work: rendering proofs share this page). @@ -101,6 +103,9 @@ async function openTouchStory( }; }); await openStory(page, storybook(), story); + if (touchLayerChunk != null) { + await waitForTouchLayer(page, touchLayerChunk); + } const driver = await touchDriver(page); const trigger = page.getByTestId('touch-context-menu'); const box = await trigger.boundingBox(); @@ -246,11 +251,13 @@ test('a finger held on a Table’s sortable header gets the menu where it landed }) => { // The header leaves its trigger unpositioned, so the cell holds the cursor // anchor. A finger's point is measured from that cell, as a pointer's is. + const touchLayerChunk = watchTouchLayer(page); await openStory( page, storybook(), 'core-tablecolumnresize--with-sortable-columns', ); + await waitForTouchLayer(page, touchLayerChunk); const driver = await touchDriver(page); const header = page.getByRole('columnheader', {name: /Name/}); const box = await header.boundingBox(); @@ -274,6 +281,34 @@ test('a finger held on a Table’s sortable header gets the menu where it landed /** The touch layer's own chunk, which loads after the page's first paint. */ const TOUCH_LAYER_CHUNK = /\/ContextMenuTouchLayer-[\w-]+\.js(?:\?.*)?$/; +type ChunkResponse = Awaited>; + +/** The touch layer chunk's response, watched from before the story opens. */ +async function watchTouchLayer(page: Page): Promise { + return page.waitForResponse(response => + TOUCH_LAYER_CHUNK.test(response.url()), + ); +} + +/** + * Waits for the touch layer, which loads after the page's first paint: its + * chunk's response, then the module itself (an import of the same URL + * resolves once it and its imports have run), then two frames for the layer + * to mount. A finger that lands sooner starts its hold only at that mount. + */ +async function waitForTouchLayer( + page: Page, + chunk: Promise, +): Promise { + const url = (await chunk).url(); + await page.evaluate(async layerUrl => { + await import(layerUrl); + await new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }); + }, url); +} + /** * Holds back the touch layer's chunk. The call it returns releases the chunk * and returns when, on the page clock. @@ -301,7 +336,9 @@ test('a finger that lands before the touch layer loads starts the hold once it l page, }) => { const releaseLayer = await holdTouchLayer(page); - const {driver, center} = await openTouchStory(page); + const {driver, center} = await openTouchStory(page, undefined, { + waitsForTouchLayer: false, + }); const finger = await driver.press(center); const start = await touchStartedAt(page); await page.waitForFunction( @@ -328,7 +365,9 @@ test('a finger that lifts before the touch layer loads makes a plain tap: one cl page, }) => { const releaseLayer = await holdTouchLayer(page); - const {driver, center} = await openTouchStory(page); + const {driver, center} = await openTouchStory(page, undefined, { + waitsForTouchLayer: false, + }); test.skip(!driver.drivesNativeGestures, CLICK_FROM_SCRIPT_SKIP); const clicks = await countTriggerClicks(page); await driver.play(hold(center, 250)); @@ -347,7 +386,9 @@ test('a right click opens the menu at once while the touch layer has not loaded' page, }) => { await holdTouchLayer(page); - const {trigger} = await openTouchStory(page); + const {trigger} = await openTouchStory(page, undefined, { + waitsForTouchLayer: false, + }); await trigger.click({button: 'right'}); await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); diff --git a/packages/core/src/ContextMenu/contextMenuTouchLoader.ts b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts new file mode 100644 index 0000000000000..f913091fad569 --- /dev/null +++ b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts @@ -0,0 +1,116 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file contextMenuTouchLoader.ts + * @input Nothing from the caller: ContextMenu calls `useContextMenuTouchLayer` + * while its touch model applies + * @output The touch layer once the page has loaded it, else `null` + * @position ContextMenu's one load of its touch layer, after first paint + * + * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx + */ + +import {useEffect, useSyncExternalStore} from 'react'; +import {createModuleLoader} from '../utils/moduleLoader'; +import type {ContextMenuTouchLayer as TouchLayer} from './ContextMenuTouchLayer'; + +// The touch layer brings the gesture host, the arena and the long-press +// recognizer. A page that never holds a finger on a ContextMenu must not pay +// for them in its first load. So the first ContextMenu under the touch model +// schedules one load: after the page's first paint, when the main thread is +// idle, and no later than LOAD_CAP_MS after that paint. An input never starts +// or hurries the load. A finger that lands before the load is the layer's to +// take when it mounts. + +/** + * The latest the load starts after first paint, in ms, when the main thread + * never goes idle. + */ +export const LOAD_CAP_MS = 2000; + +let layer: typeof TouchLayer | null = null; +let isScheduled = false; +const listeners = new Set<() => void>(); + +const layerModule = createModuleLoader( + async () => import('./ContextMenuTouchLayer'), +); + +function getLayer(): typeof TouchLayer | null { + return layer; +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function publish(loaded: typeof TouchLayer | null): void { + layer = loaded; + for (const listener of [...listeners]) { + listener(); + } +} + +function load(): void { + layerModule.load().then( + loaded => publish(loaded.ContextMenuTouchLayer), + // A chunk that fails to load leaves the menu on right clicks and keys. + () => {}, + ); +} + +function scheduleLoad(): void { + if (isScheduled) { + return; + } + isScheduled = true; + // The timers belong to this window, so they end with its document. + const view = window; + // A frame callback runs before the frame paints. The task it queues runs + // after that paint. + view.requestAnimationFrame(() => { + view.setTimeout(() => { + if (typeof view.requestIdleCallback === 'function') { + view.requestIdleCallback(load, {timeout: LOAD_CAP_MS}); + } else { + load(); + } + }, 0); + }); +} + +/** + * The touch layer once the page has loaded it, else `null`. A ContextMenu + * that wants it schedules the page's one load. The server and the hydration + * render read `null`, so the markup matches. + */ +export function useContextMenuTouchLayer( + isWanted: boolean, +): typeof TouchLayer | null { + const current = useSyncExternalStore(subscribe, getLayer, () => null); + // Syncs the page's one load of the touch layer with the first ContextMenu + // under the touch model. + useEffect(() => { + if (isWanted) { + scheduleLoad(); + } + }, [isWanted]); + return isWanted ? current : null; +} + +/** Test only: loads the layer now and makes every reader see it. */ +export async function __loadContextMenuTouchLayerForTest(): Promise { + publish((await layerModule.load()).ContextMenuTouchLayer); + isScheduled = true; +} + +/** Test only: forgets the loaded layer and any scheduled load. */ +export function __resetContextMenuTouchLayerForTest(): void { + isScheduled = false; + publish(null); +} diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts index d0ae705bf777e..fda6619d1f0eb 100644 --- a/packages/core/src/gestures/GestureHost.ts +++ b/packages/core/src/gestures/GestureHost.ts @@ -3077,7 +3077,21 @@ export class GestureHost { } private readonly onTouchStart = (event: TouchEvent): void => { - this.endWheel(eventTime(event, this.timing)); + this.beginTouches(event, eventTime(event, this.timing)); + }; + + /** + * Begins, now, the fingers of a `touchstart` this host did not hear: a + * recognizer that attaches while a finger is down on its element hands + * over that finger's own touchstart. The caller passes only a touchstart + * whose fingers are still down. + */ + beginLateTouches(event: TouchEvent): void { + this.beginTouches(event, this.arena.pageTime()); + } + + private beginTouches(event: TouchEvent, time: number): void { + this.endWheel(time); this.noteFingersDown(event); // Where the host reads a finger from its pointer events (no ontouchstart, // as after touch emulation turns on), its Touch Events would track it twice. @@ -3087,7 +3101,6 @@ export class GestureHost { if (this.fingerTargets.length > 1) { this.failUnclaimedLoneFingerPans(); } - const time = eventTime(event, this.timing); const inputs: ArenaBeganInput[] = []; const untracked: TouchBeganInput[] = []; const stale: number[] = []; @@ -3198,7 +3211,7 @@ export class GestureHost { if (isNode(landed)) { this.lastTouch = {target: landed, time}; } - }; + } private readonly onTouchMove = (event: TouchEvent): void => { this.noteFingersDown(event); From 556b4ff8a8af9c5948956350312c9c0d8480e657 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 14:21:55 -0800 Subject: [PATCH 085/151] test(ContextMenu): the growth cases load the touch layer first The touch layer, with the press feedback, now loads after first paint (#8125). The growth cases hold a finger once the page has settled, so they load the layer up front, as the long-press cases do. The animator now comes with that layer, not with ContextMenu's first load, so the lazy-sheet bundle test drops ContextMenu's eager-animator row and reads as on main. --- .../ContextMenuTouchGrowth.test.tsx | 15 ++++++++- scripts/lazy-sheet-bundle.test.mjs | 33 +++++++------------ 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx index e345da679ccad..7a8dd238074b2 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchGrowth.test.tsx @@ -14,9 +14,22 @@ import {act, cleanup, render, screen, within} from '@testing-library/react'; import {Suspense, startTransition, use, useState} from 'react'; import {createPortal} from 'react-dom'; -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vitest'; import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback'; import {ContextMenu} from './ContextMenu'; +import {__loadContextMenuTouchLayerForTest} from './contextMenuTouchLoader'; + +// The touch layer loads after first paint. These cases hold a finger once the +// page has settled, so they load it up front. +beforeAll(__loadContextMenuTouchLayerForTest, 20000); const animator = vi.hoisted(() => ({ elements: [] as HTMLElement[], diff --git a/scripts/lazy-sheet-bundle.test.mjs b/scripts/lazy-sheet-bundle.test.mjs index 807fb86c36323..d0f74abb83cb5 100644 --- a/scripts/lazy-sheet-bundle.test.mjs +++ b/scripts/lazy-sheet-bundle.test.mjs @@ -7,9 +7,8 @@ * @output Pins that a menu's static import keeps its on-demand bottom sheet's * keyboard code on demand. The sheet's keyboard ride (the animator and * `rideKeyboard`) stays in the chunks the import loads only when the sheet - * opens. A menu that uses the animator at once loads it with the menu. This - * holds though the layer runtime's keyboard cap imports the keyboard module - * statically. + * opens. This holds though the layer runtime's keyboard cap imports the + * keyboard module statically. * @position Node test over source, so it needs no build */ @@ -111,28 +110,20 @@ function rideIn(bytes) { describe('a menu with an on-demand bottom sheet', () => { it.each([ - ['DropdownMenu', 'packages/core/src/DropdownMenu/index.ts', []], - // ContextMenu's touch growth plays on the animator, so the animator loads - // with the menu. The sheet's own ride is then `rideKeyboard` alone. - [ - 'ContextMenu', - 'packages/core/src/ContextMenu/index.ts', - ['packages/core/src/motion/animator.ts'], - ], - ['Selector', 'packages/core/src/Selector/index.ts', []], - ['MultiSelector', 'packages/core/src/MultiSelector/index.ts', []], + ['DropdownMenu', 'packages/core/src/DropdownMenu/index.ts'], + ['ContextMenu', 'packages/core/src/ContextMenu/index.ts'], + ['Selector', 'packages/core/src/Selector/index.ts'], + ['MultiSelector', 'packages/core/src/MultiSelector/index.ts'], ])( "%s loads the sheet's keyboard ride only with the sheet", - (name, entry, eagerRide) => { + (name, entry) => { const {eager, onDemand} = importOf(entry, name); // The sheet still rides the keyboard, on demand. - expect(rideIn(onDemand)).toEqual( - [ - 'packages/core/src/keyboard/rideKeyboard.ts', - 'packages/core/src/motion/animator.ts', - ].filter(input => !eagerRide.includes(input)), - ); - expect(rideIn(eager)).toEqual(eagerRide); + expect(rideIn(onDemand)).toEqual([ + 'packages/core/src/keyboard/rideKeyboard.ts', + 'packages/core/src/motion/animator.ts', + ]); + expect(rideIn(eager)).toEqual([]); }, ); }); From 779d979a2ff4a8a437ab5064c8a42f8420877aa4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 16:26:22 -0800 Subject: [PATCH 086/151] test(ContextMenu): a drift before the touch layer loads ends the press A finger kept while the touch layer loads begins at its touchstart once the layer mounts. The press judges drift only on the moves it sees after that, so a finger that drifted past the tolerance before the load, then held still, would still get the menu. These cases drift a finger past the tolerance on one axis before the load, then bring it back, and expect no menu after the load. One case sends the drift as a touch pointer move only: before the layer loads, Chromium sends a small drift's pointermove but not its touchmove. A drift within the tolerance, and another pointer's move, keep the hold. --- .../core/src/ContextMenu/ContextMenu.test.tsx | 82 +++++++++++++++++++ ...tMenuLongPress.interaction.browser.spec.ts | 25 ++++++ 2 files changed, 107 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index b90b42d0cd9ea..f186ed1781916 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -918,6 +918,88 @@ describe.each([ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); }); + it('opens nothing for a finger that drifted past the tolerance before the load', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(100); + // Past the tolerance on one axis, then back to where it landed. + press.moveTo(20 + contextMenu.press.allowableMovement + 0.5, 20); + press.moveTo(20, 20); + advance(400); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs * 2); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + press.up(); + }); + + it('starts the hold of a finger that drifted within the tolerance before the load', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(100); + press.moveTo( + 20 + contextMenu.press.allowableMovement, + 20 - contextMenu.press.allowableMovement, + ); + advance(400); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('opens nothing for a finger whose drift past the tolerance comes only as a pointer move', async () => { + // Before the layer loads, Chromium sends a small drift's pointermove + // but not its touchmove. + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(100); + const primaryTouch = { + pointerType: 'touch', + pointerId: 1, + isPrimary: true, + clientY: 20, + }; + fireEvent.pointerMove(trigger, { + ...primaryTouch, + clientX: 20 + contextMenu.press.allowableMovement + 0.5, + }); + fireEvent.pointerMove(trigger, {...primaryTouch, clientX: 20}); + advance(400); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs * 2); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + press.up(); + }); + + it('starts the hold of a finger while a mouse or a second touch pointer moves far before the load', async () => { + const trigger = renderMenu(); + const press = finger(trigger); + press.down(); + advance(100); + fireEvent.pointerMove(trigger, { + pointerType: 'mouse', + pointerId: 2, + isPrimary: true, + clientX: 90, + clientY: 20, + }); + fireEvent.pointerMove(trigger, { + pointerType: 'touch', + pointerId: 3, + isPrimary: false, + clientX: 90, + clientY: 20, + }); + advance(400); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + it('keeps the browser’s own long-press menu from opening it for a finger held through the load', async () => { const trigger = renderMenu(); const press = finger(trigger); diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 37c27fd597dcb..cc43ec9e1e799 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -382,6 +382,31 @@ test('a finger that lifts before the touch layer loads makes a plain tap: one cl expect(await clicks()).toBe(1); }); +test('a finger that drifts past the tolerance before the touch layer loads gets no menu once it loads', async ({ + page, +}) => { + const releaseLayer = await holdTouchLayer(page); + const {driver, center} = await openTouchStory(page, undefined, { + waitsForTouchLayer: false, + }); + const finger = await driver.press(center); + // Past the tolerance on one axis, then back to where it landed. Before the + // layer loads, Chromium sends this drift as a pointermove only. + await finger.move({ + x: center.x + contextMenu.press.allowableMovement + 1, + y: center.y, + }); + await finger.move(center); + const released = await releaseLayer(); + await page.waitForFunction( + dueAt => performance.now() > dueAt, + released + menuDisplayMs + 300, + ); + expect(await menuShownAt(page)).toBeNull(); + await finger.lift(); + await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden(); +}); + test('a right click opens the menu at once while the touch layer has not loaded', async ({ page, }) => { From ffa095051da4e20d77d8686af1b16cfb8b775a3c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 16:26:22 -0800 Subject: [PATCH 087/151] fix(ContextMenu): a drift before the touch layer loads ends the press While the touch layer loads, the trigger keeps the touchstart of one finger. Each of that finger's moves is now judged by the press's own rule: past `contextMenu.press.allowableMovement` on either axis from where it landed, the trigger drops the touchstart, so the layer does not begin it and no menu shows. The trigger reads the finger's moves from its touch moves and from the primary touch pointer's moves: before the layer loads, Chromium sends a small drift as a pointermove only. The layer judges every move after it loads, as before. component:ContextMenu FR12's evidence names the drift case. --- .../ContextMenu/ContextMenu.spec.md | 38 +++++++------- packages/core/src/ContextMenu/ContextMenu.tsx | 51 +++++++++++++++++++ 2 files changed, 70 insertions(+), 19 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 6d712825d82e5..e2cf170e7cd87 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -260,25 +260,25 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | -| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | -| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | -| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | -| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | -| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | -| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | -| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | -| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | -| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | -| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | -| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | -| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | -| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | -| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" | A held finger: the commit and the menu's display; a finger down before the touch layer loads | A commit or a display off UIKit's moments fails. A hold that starts before the touch layer loads fails. | `audit:ContextMenu/behavior` | -| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | -| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | +| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | +| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | +| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | +| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | +| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | +| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | +| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | +| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | +| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | +| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | +| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | +| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | +| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold) | Right click, long press, keyboard | A context request that does not open the menu, or a dropped consumer handler, fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | +| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | +| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" and "a finger that drifts past the tolerance before the touch layer loads gets no menu once it loads" | A held finger: the commit and the menu's display; a finger down before the touch layer loads, held still or drifting | A commit or a display off UIKit's moments fails. A hold that starts before the touch layer loads fails. A menu for a finger that drifted past the tolerance before the load fails. | `audit:ContextMenu/behavior` | +| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | +| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | ## Current-state impact diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 1cb65e2ff1a1b..3cefe3a7c61a5 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -89,6 +89,7 @@ import {useMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; import {shadowHostOf} from '../utils/flatTree'; import {usePresentation} from '../utils/presentation'; +import {contextMenu} from '../motion/uikit/contextMenu'; import type {ContextMenuTouchHandle} from './ContextMenuTouchLayer'; import {useContextMenuTouchLayer} from './contextMenuTouchLoader'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; @@ -262,6 +263,27 @@ function keepAnchorInside(offset: number, size: number): number { return offset > size - 1 && offset <= size ? Math.max(size - 1, 0) : offset; } +/** + * Whether a move takes the finger of a kept touchstart past the press's drift + * tolerance on either axis, from where it landed. A touch move names its + * finger by `identifier`; the primary touch pointer's move names none. The + * touch layer judges later moves itself; this judges the moves before it + * loads. + */ +function driftsPastTolerance( + touchStart: TouchEvent, + to: {readonly clientX: number; readonly clientY: number}, + identifier?: number, +): boolean { + const {allowableMovement} = contextMenu.press; + return Array.from(touchStart.changedTouches).some( + landed => + (identifier === undefined || landed.identifier === identifier) && + (Math.abs(to.clientX - landed.clientX) > allowableMovement || + Math.abs(to.clientY - landed.clientY) > allowableMovement), + ); +} + // ============================================================================= // Types // ============================================================================= @@ -384,6 +406,7 @@ export function ContextMenu({ onTouchMove: onTouchMoveProp, onTouchEnd: onTouchEndProp, onTouchCancel: onTouchCancelProp, + onPointerMove: onPointerMoveProp, 'data-testid': testId, ...rest }: ContextMenuProps) { @@ -836,6 +859,16 @@ export function ContextMenu({ ); const handleTriggerTouchMove = useCallback( (event: React.TouchEvent) => { + const touchStart = lateTouchRef.current; + if ( + touchStart != null && + Array.from(event.nativeEvent.changedTouches).some(touch => + driftsPastTolerance(touchStart, touch, touch.identifier), + ) + ) { + // A finger that drifts too far before the layer loads gets no menu. + lateTouchRef.current = null; + } handleLongPressTouchMove(event); onTouchMoveProp?.(event); }, @@ -857,6 +890,23 @@ export function ContextMenu({ }, [handleLongPressTouchCancel, onTouchCancelProp], ); + const handleTriggerPointerMove = useCallback( + (event: React.PointerEvent) => { + const touchStart = lateTouchRef.current; + // Before the touch layer loads, Chromium sends a small drift's + // pointermove but not its touchmove. + if ( + touchStart != null && + event.pointerType === 'touch' && + event.isPrimary && + driftsPastTolerance(touchStart, event) + ) { + lateTouchRef.current = null; + } + onPointerMoveProp?.(event); + }, + [onPointerMoveProp], + ); // ContextMenu owns invocation. Consumer handlers are notified too, but // preventing their default does not cancel component-owned behavior that @@ -1023,6 +1073,7 @@ export function ContextMenu({ onTouchMove={handleTriggerTouchMove} onTouchEnd={handleTriggerTouchEnd} onTouchCancel={handleTriggerTouchCancel} + onPointerMove={handleTriggerPointerMove} data-testid={testId} {...stylex.props( styles.trigger, From c6208ca2f5e77d641c015ece0bcdd429299b17fc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 16:26:22 -0800 Subject: [PATCH 088/151] docs(ContextMenu): the touch loader's comments in short sentences Comments only. The loader's comments say what it does in their own words, and four comments split into sentences of at most 25 words: the loader's, the gesture host's late begin, the browser spec's wait for the layer and the boundary test's header. --- ...tMenuLongPress.interaction.browser.spec.ts | 9 ++-- .../contextMenuTouchLoader.boundary.test.ts | 4 +- .../src/ContextMenu/contextMenuTouchLoader.ts | 52 ++++++++++--------- packages/core/src/gestures/GestureHost.ts | 2 +- 4 files changed, 36 insertions(+), 31 deletions(-) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index cc43ec9e1e799..b0d30676aa71d 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -291,10 +291,11 @@ async function watchTouchLayer(page: Page): Promise { } /** - * Waits for the touch layer, which loads after the page's first paint: its - * chunk's response, then the module itself (an import of the same URL - * resolves once it and its imports have run), then two frames for the layer - * to mount. A finger that lands sooner starts its hold only at that mount. + * Waits for the touch layer, which loads after the page's first paint. It + * waits for the chunk's response, then for the module itself, then two frames + * for the layer to mount. An import of the same URL resolves once it and its + * imports have run. A finger that lands sooner starts its hold only at that + * mount. */ async function waitForTouchLayer( page: Page, diff --git a/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts b/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts index de2cd5889b08e..0656db19644bd 100644 --- a/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts +++ b/packages/core/src/ContextMenu/contextMenuTouchLoader.boundary.test.ts @@ -4,9 +4,9 @@ * @file contextMenuTouchLoader.boundary.test.ts * @input The static import graphs of the ContextMenu entry and of Table's * context-menu module, and every core source file - * @output The source boundary check for ContextMenu's touch layer: no entry's + * @output The source boundary check for ContextMenu's touch layer. No entry's * static graph reaches the layer, its recognizer or the gesture code under - * it, and only the loader imports the layer, through `import()` + * it. Only the loader imports the layer, through `import()`. * @position Testing; the before-load behavior is in ContextMenu.test.tsx */ diff --git a/packages/core/src/ContextMenu/contextMenuTouchLoader.ts b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts index f913091fad569..937a916e80fd6 100644 --- a/packages/core/src/ContextMenu/contextMenuTouchLoader.ts +++ b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts @@ -4,10 +4,11 @@ /** * @file contextMenuTouchLoader.ts - * @input Nothing from the caller: ContextMenu calls `useContextMenuTouchLayer` - * while its touch model applies - * @output The touch layer once the page has loaded it, else `null` - * @position ContextMenu's one load of its touch layer, after first paint + * @input No props: ContextMenu calls `useContextMenuTouchLayer` while its + * touch model applies + * @output The touch layer after the page loads it; `null` until then + * @position Between ContextMenu and its touch layer: loads the layer after + * first paint * * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx */ @@ -16,17 +17,16 @@ import {useEffect, useSyncExternalStore} from 'react'; import {createModuleLoader} from '../utils/moduleLoader'; import type {ContextMenuTouchLayer as TouchLayer} from './ContextMenuTouchLayer'; -// The touch layer brings the gesture host, the arena and the long-press -// recognizer. A page that never holds a finger on a ContextMenu must not pay -// for them in its first load. So the first ContextMenu under the touch model -// schedules one load: after the page's first paint, when the main thread is -// idle, and no later than LOAD_CAP_MS after that paint. An input never starts -// or hurries the load. A finger that lands before the load is the layer's to -// take when it mounts. +// The touch layer imports the long-press recognizer, which brings the arena +// and the gesture host. These modules stay out of the page's first load. The +// first ContextMenu under the touch model asks for them once. The request +// waits until the next frame has painted, then for an idle moment, capped at +// LOAD_CAP_MS. Touches, clicks and keys do not change when the load starts. +// As the layer mounts, it takes a finger that landed before the load. /** - * The latest the load starts after first paint, in ms, when the main thread - * never goes idle. + * How long the load waits for an idle main thread after that paint, in ms. + * Past it, the load starts anyway. */ export const LOAD_CAP_MS = 2000; @@ -59,7 +59,7 @@ function publish(loaded: typeof TouchLayer | null): void { function load(): void { layerModule.load().then( loaded => publish(loaded.ContextMenuTouchLayer), - // A chunk that fails to load leaves the menu on right clicks and keys. + // If the chunk fails, the menu still opens from right clicks and keys. () => {}, ); } @@ -69,10 +69,10 @@ function scheduleLoad(): void { return; } isScheduled = true; - // The timers belong to this window, so they end with its document. + // Timers from this window stop when its document goes away. const view = window; - // A frame callback runs before the frame paints. The task it queues runs - // after that paint. + // The frame callback runs just before that frame paints, so the timeout it + // sets runs just after the paint. view.requestAnimationFrame(() => { view.setTimeout(() => { if (typeof view.requestIdleCallback === 'function') { @@ -85,16 +85,17 @@ function scheduleLoad(): void { } /** - * The touch layer once the page has loaded it, else `null`. A ContextMenu - * that wants it schedules the page's one load. The server and the hydration - * render read `null`, so the markup matches. + * The touch layer after the page loads it, `null` until then. The first + * ContextMenu that wants it asks for the load, and later ones share it. It is + * `null` on the server and while hydrating, so both renders produce the same + * markup. */ export function useContextMenuTouchLayer( isWanted: boolean, ): typeof TouchLayer | null { const current = useSyncExternalStore(subscribe, getLayer, () => null); - // Syncs the page's one load of the touch layer with the first ContextMenu - // under the touch model. + // Syncs with the browser's frame and idle timers, which decide when the + // touch layer loads. useEffect(() => { if (isWanted) { scheduleLoad(); @@ -103,13 +104,16 @@ export function useContextMenuTouchLayer( return isWanted ? current : null; } -/** Test only: loads the layer now and makes every reader see it. */ +/** + * Test only: loads the layer at once and hands it to every hook that reads + * it. + */ export async function __loadContextMenuTouchLayerForTest(): Promise { publish((await layerModule.load()).ContextMenuTouchLayer); isScheduled = true; } -/** Test only: forgets the loaded layer and any scheduled load. */ +/** Test only: drops the loaded layer and clears the scheduled load. */ export function __resetContextMenuTouchLayerForTest(): void { isScheduled = false; publish(null); diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts index fda6619d1f0eb..1bd05ae570f24 100644 --- a/packages/core/src/gestures/GestureHost.ts +++ b/packages/core/src/gestures/GestureHost.ts @@ -3081,7 +3081,7 @@ export class GestureHost { }; /** - * Begins, now, the fingers of a `touchstart` this host did not hear: a + * Begins, now, the fingers of a `touchstart` this host did not hear. A * recognizer that attaches while a finger is down on its element hands * over that finger's own touchstart. The caller passes only a touchstart * whose fingers are still down. From d5a704979ac606b92b0f9cf3c1a1bbbe711dd1c2 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 16:28:15 -0800 Subject: [PATCH 089/151] test(ContextMenu): a popover long press waits for no touch layer With presentation="popover" the touch model does not apply, so the touch layer never loads, and the spec's wait for its chunk timed out. The case now opens its story without that wait, and it checks that the page never requests the touch layer's chunk. --- .../ContextMenuLongPress.interaction.browser.spec.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index ed242db83d9ff..947cd1ecdf33e 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -721,9 +721,17 @@ test('the menu mounts at the commit, closed and out of the accessibility tree, a test('with presentation="popover" a finger keeps today’s long press: the menu at 500 ms, with no growth and no iOS timeline', async ({ page, }) => { + const layerRequests: string[] = []; + page.on('request', request => { + if (TOUCH_LAYER_CHUNK.test(request.url())) { + layerRequests.push(request.url()); + } + }); + // The touch model does not apply, so the touch layer never loads. const {driver, trigger, center} = await openTouchStory( page, 'core-contextmenu--touch-long-press-popover', + {waitsForTouchLayer: false}, ); // A coarse primary pointer: only the caller's choice keeps today's menu. expect( @@ -749,6 +757,10 @@ test('with presentation="popover" a finger keeps today’s long press: the menu expect(after).toBeGreaterThanOrEqual(500); expect(after).toBeLessThan(550); expect(scaleBeforeOpen).toBe(1); + expect( + layerRequests, + 'the popover presentation loaded the touch layer', + ).toEqual([]); }); test('a finger where the primary pointer is fine keeps today’s long press: the menu at 500 ms, with no growth', async ({ From e7c75e4d92d3b6f465cebb9d9505dcff3f65f9e4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:18:16 -0800 Subject: [PATCH 090/151] test(gestures): a late deadline waits for input queued behind a block A gesture's deadline whose timer runs late yields one task, so input queued behind the block can come first. Touch moves can reach the page later than that: Chromium sends them with the next frame. Then a long press whose finger drifted in time still begins. These cases expect the deadline to wait for that input: a drift that reaches the page after the next task fails the press, and an on-time deadline waits while input from before it still comes late. An input stamped at or past the deadline ends the wait at once. --- .../__tests__/arenaTimersAndClaims.test.ts | 44 ++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts index e2aaeaa925a0f..395b582ccc8ba 100644 --- a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts +++ b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts @@ -96,12 +96,52 @@ describe('a timer that fires late', () => { arena.ended([{id: 1, x: 40, y: 0, time: 820}]); }); - it('still fires on its deadline when nothing was queued', () => { + it('still fires on its deadline when nothing was queued, once the wait for queued input ends', () => { const {clock, arena, log} = pressArena(); + // 300 ms late: the deadline waits 50 ms for input still queued. clock.runTask(800); clock.runTask(800); + expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); + clock.runTask(850); + expect(log).toContain('press:began@500'); + arena.ended([{id: 1, x: 0, y: 0, time: 870}]); + }); + + it('waits more than one task for input queued behind the block: a drift that comes after the next task still fails the press', () => { + const {clock, arena, log} = pressArena(); + // The timer task runs at 800, and so does the next task. The finger's + // drift from 300 ms reaches the page at 816, as Chromium sends touch + // moves with the next frame. + clock.runTask(800); + clock.runTask(800); + clock.time = 816; + arena.moved([{id: 1, x: 40, y: 0, time: 300}]); + clock.runTask(850); + expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); + expect(log).toContain('press:failed@300'); + arena.ended([{id: 1, x: 40, y: 0, time: 870}]); + }); + + it('keeps an on-time deadline waiting while input from before it still comes late', () => { + const {clock, arena, log} = pressArena(); + // A move from 400 ms reaches the page at 470, 70 ms late, inside the + // press's tolerance. The deadline at 500 waits 50 ms past that move. + clock.time = 470; + arena.moved([{id: 1, x: 2, y: 0, time: 400}]); + clock.runTask(500); + expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); + clock.runTask(550); + expect(log).toContain('press:began@500'); + arena.ended([{id: 1, x: 2, y: 0, time: 570}]); + }); + + it('ends the wait at the first input stamped at or past the deadline', () => { + const {clock, arena, log} = pressArena(); + clock.runTask(800); + clock.time = 820; + arena.moved([{id: 1, x: 1, y: 0, time: 820}]); expect(log).toContain('press:began@500'); - arena.ended([{id: 1, x: 0, y: 0, time: 820}]); + arena.ended([{id: 1, x: 1, y: 0, time: 840}]); }); }); From b547611b3fc85873c198eb00a9a5a8930f0102cf Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:34:06 -0800 Subject: [PATCH 091/151] fix(gestures): a late deadline waits for input queued behind a block The arena's late timer yielded one task before it ran a deadline, so input queued behind a block could come first. A touch move can reach the page later than that: Chromium sends it with the next frame. So a long press, a List reorder hold or a Pager's catch could begin though its finger drifted or lifted in time. Now a deadline whose timer runs more than 17 ms late waits 50 ms for that input. The arena notes each touch input that reaches the page more than 33 ms after its own time, and such input from before the deadline keeps it waiting. An input stamped at or past the deadline runs the deadline first, which ends the wait. A timer up to 17 ms late keeps the one-task yield. spec:AST-094 FR16 records the wait. The arena's and the Pager's tests that run a deadline late now run the wait too. A comment's citation of FR16 goes, as the source-comment rule asks. --- .changeset/gesture-arena-late-input.md | 7 ++ .../specs/AST-094-touch-presentations/spec.md | 8 +- packages/core/src/gestures/GestureArena.ts | 83 +++++++++++++++++-- .../core/src/gestures/__tests__/arena.test.ts | 6 +- packages/core/src/hooks/usePager.test.ts | 11 ++- 5 files changed, 104 insertions(+), 11 deletions(-) create mode 100644 .changeset/gesture-arena-late-input.md diff --git a/.changeset/gesture-arena-late-input.md b/.changeset/gesture-arena-late-input.md new file mode 100644 index 0000000000000..d0ff3f394959d --- /dev/null +++ b/.changeset/gesture-arena-late-input.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Behind a blocked page, a touch gesture's deadline waits for the input still queued before it. Touch moves can reach the page a frame after other input. A long press, a List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. A deadline whose timer runs more than 17 ms late waits 50 ms, and each input from before it that comes late keeps it waiting. + +@vjeux diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index d49f5993c4abb..945905b448176 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -514,7 +514,11 @@ a measured, sourced difference exists. - **FR16 — Gestures keep the event clock.** Recognizers MUST read time from the input events' timestamps. Durations (a long press, the interval between taps) MUST be deadlines on that clock, so a blocked main thread delays the - report and never the moment reported. + report and never the moment reported. Behind a blocked page, a deadline + waits for input still queued before it. It waits 50 ms when its timer runs + more than 17 ms late. Each input from before it that reaches the page more + than 33 ms late keeps it waiting 50 ms more. An input stamped at or past the + deadline ends the wait. - **FR17 — Native readings.** A recognizer's thresholds MUST follow UIKit's measured values (FR1, FR2). A pan begins at 10 pt of travel on either axis (a screen-edge pan attached to an element within the band at 15 px, FR18), @@ -1133,7 +1137,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li | FR11 theme | `generateThemeRules.test.ts` themed-`:active` cases; real-browser forced `:active` on the Themed press story | a theme `:active` on a base and on a variant with a trailing pseudo; fine pointer; coarse pointer with forced `:active` and with the press attribute | a bare theme `:active` rule a coarse pointer matches, or a coarse arm keyed on `:active`, fails | | FR13 | Resolver unit tests and a server-render test | coarse and fine pointer; narrow, wide and short; server render; hydrating render | a component that answers the conditions differently, or a touch presentation in the server or hydrating render, fails | | FR14 | Browser tests of a sheet over a scrolled list | scrolled and at its top | a midway handoff fails | -| FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a pan at 10 pt per axis | a wrong winner, a late deadline, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails | +| FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a deadline run late behind a block, with a drift that reaches the page after the next task; an on-time deadline while input from before it still comes late; a pan at 10 pt per axis | a wrong winner, a late deadline, a deadline that runs before input queued before it, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails | | FR18–FR22 | Browser tests with real touch input (`spec:AST-013` FR10) | per-axis pans beside native scrolling, page zoom, cancelled touches, clicks after taps, keyboard activation, a modal scroll lock, a control that keeps its press through a drag; a still finger with sub-pixel jitter over a scroll view; a finger moved 9 px and 10 px straight, and (7, 7) and (8, 8) diagonally; a recognizer on an element whose author `touch-action` is narrower, including one without `pinch-zoom`; a screen-edge pan landing at 40 px and at 41 px from the edge, at 14 px and 15 px of travel, and a horizontal scroll that starts outside the band; a screen-edge pan on an element within the band, and on one that reaches beyond it; a sheet's pull from a list at its top, and from a list scrolled away from its top; a long press dragged past its tolerance after it began, which never scrolls the page | a ghost click, a scroll or zoom blocked other than by the author's `touch-action`, or a cancelled unowned touchmove outside FR19's five exceptions, a tap cancelled by sub-pixel movement or by under 10 px of travel, a scroll that does not take the touch at 10 px, or a derived `touch-action` wider than the author's, a screen-edge pan that claims outside its band or before 15 px on an element within the band, or has not claimed at 15 px, or an author scroll outside the band that is blocked, a band claim of `pan-x` on an element that reaches beyond the band, or a 15 px start there, or a scroll-edge pan that cancels a move a scroller could scroll, or begins before 10 pt, fails | | FR19 (DEC-30) | Gesture unit tests on synthetic streams; browser tests with real touch input in WebKit and Chromium | a tap that wobbles 2–4 px toward a scroll edge keeps every move, and a 5 px move is cancelled; a sideways move is never held; NavigationStack's content back swipe on a pushed screen; RefreshControl's pull at its top, whose touch path is not a scroll-edge pan (a guard) | a move under 5 px along the pan's axis cancelled, a move from 5 px left uncancelled while every scroller under the finger sits at its edge, a sideways move held, or a pan that begins before its hysteresis fails | | FR20 | Browser tests with real touch input in Chromium phone emulation (`spec:AST-013` FR10) | a horizontal drag under `pan-y`; a vertical drag under `pan-y` over a scroller with room; a vertical drag where no scroller has room | a horizontal drag under `pan-y` counted as the browser taking the touch, a vertical one over a scroller with room not counted, or a later uncancelable move counted, fails | diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index 62bf6d03374cd..fcd63e4cff7a2 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -36,7 +36,8 @@ * timestamp runs first, at its own deadline. A long press therefore begins at * exactly touch-down + 500 ms even when the main thread was blocked and the * timer callback came late, and a test drives the whole machine with explicit - * timestamps and no real time at all. + * timestamps and no real time at all. A deadline whose timer runs late waits + * while input from before it still reaches the page late. * * SYNC: When modified, update GestureRecognizer.ts and * __tests__/arena.test.ts. @@ -58,6 +59,24 @@ import type { TouchSample, } from './types'; import {DEFAULT_ENVIRONMENT} from './types'; + +/** + * A deadline's timer counts as late when it runs this long after it was due. + * In ms: one frame at 60 Hz. + */ +const LATE_TIMER_MS = 17; + +/** + * An input counts as late when it reaches the page this long after its own + * time. In ms: two frames at 60 Hz. + */ +const LATE_INPUT_MS = 33; + +/** + * How long a late deadline waits for input still queued before it. In ms: + * three frames at 60 Hz. + */ +const LATE_INPUT_WAIT_MS = 50; import {internals} from './recognizerInternals'; export interface GestureClock { @@ -162,6 +181,8 @@ export class GestureArena { private currentTime: number | null = null; /** The latest time processed: input never moves the clock backwards. */ private latestTime = Number.NEGATIVE_INFINITY; + /** The latest input that reached the page late: its own time, and when. */ + private lateInput: {time: number; arrivedAt: number} | null = null; private depth = 0; /** Open `deferResolution` calls: what their stops unblock waits. */ private deferDepth = 0; @@ -222,6 +243,7 @@ export class GestureArena { if (inputs.length === 0) { return; } + this.noteArrival(inputs[0].time); this.run(inputs[0].time, () => { const newTouches = new Map(); const created: TouchRecord[] = []; @@ -316,6 +338,7 @@ export class GestureArena { * gesture hear of it, as of any touch off their hit path. */ untrackedBegan(input: TouchBeganInput): void { + this.noteArrival(input.time); if (!this.active.some(recognizer => recognizer.numberOfTouches > 0)) { return; } @@ -350,6 +373,7 @@ export class GestureArena { if (inputs.length === 0) { return; } + this.noteArrival(inputs[0].time); this.run(inputs[0].time, () => { const changed = this.update(inputs, 'moved'); if (changed.length === 0) { @@ -383,6 +407,7 @@ export class GestureArena { if (inputs.length === 0) { return dispositions; } + this.noteArrival(inputs[0].time); this.run(inputs[0].time, () => { const changed = this.update(inputs, 'ended'); const context = this.context(); @@ -407,6 +432,7 @@ export class GestureArena { /** The system took these contacts (`touchcancel`, a mouse `pointercancel`). */ cancelled(ids: ReadonlyArray, time: number): void { + this.noteArrival(time); this.run(time, () => { const touches = this.liveTouches(ids); for (const touch of touches) { @@ -437,6 +463,7 @@ export class GestureArena { * browser took stays the browser's (FR14). */ browserTookOver(ids: ReadonlyArray, time: number): void { + this.noteArrival(time); this.run(time, () => { const touches = this.liveTouches(ids).filter( touch => !touch.takenByBrowser, @@ -553,7 +580,7 @@ export class GestureArena { /** Cancel an active recognizer, or fail a possible one. */ stop(recognizer: GestureRecognizer): void { // A cancel from code between events happens at the last event's time: - // wall time would run deadlines ahead of input still queued (FR16). + // wall time would run deadlines ahead of input still queued. const time = this.currentTime ?? (Number.isFinite(this.latestTime) ? this.latestTime : this.clock.now()); @@ -1005,6 +1032,27 @@ export class GestureArena { return clamped; } + /** Notes an input that reaches the page late, against its own time. */ + private noteArrival(time: number): void { + const arrivedAt = this.clock.now(); + if (arrivedAt - time > LATE_INPUT_MS) { + this.lateInput = {time, arrivedAt}; + } + } + + /** + * Whether input from before `deadline` reached the page late within the + * last `LATE_INPUT_WAIT_MS`, so more of it may still be queued. + */ + private hasLateInputBefore(deadline: number, now: number): boolean { + const input = this.lateInput; + return ( + input != null && + input.time < deadline && + now - input.arrivedAt < LATE_INPUT_WAIT_MS + ); + } + /** * One external entry: run the timers due by `time`, then `body`, then * settle (release held deliveries, reset finished recognizers, forget @@ -1138,22 +1186,45 @@ export class GestureArena { return; } const delay = Math.max(0, earliest - this.clock.now()); - const fire = (mayYield: boolean): void => { + const fire = ( + after: 'deadline' | 'yield' | 'wait', + dueAt: number, + ): void => { this.realTimer = null; this.realTimerDeadline = Number.POSITIVE_INFINITY; - if (mayYield && this.clock.now() > earliest) { + const now = this.clock.now(); + if ( + after !== 'yield' && + (now - dueAt > LATE_TIMER_MS || this.hasLateInputBefore(earliest, now)) + ) { + // Behind a blocked page, input from before the deadline can still be + // queued, and a touch move can reach the page a frame after other + // input. Wait while that input still comes. An input stamped at or + // past the deadline runs the deadline first, which ends the wait. + this.realTimerDeadline = earliest; + const waitUntil = now + LATE_INPUT_WAIT_MS; + this.realTimer = this.clock.setTimeout( + () => fire('wait', waitUntil), + LATE_INPUT_WAIT_MS, + ); + return; + } + if (after === 'deadline' && now > earliest) { // Late: a long task held the main thread past the deadline, and // input queued behind it may come before the deadline (a lift that // fails a long press). Let that input dispatch first, once. this.realTimerDeadline = earliest; - this.realTimer = this.clock.setTimeout(() => fire(false), 0); + this.realTimer = this.clock.setTimeout(() => fire('yield', now), 0); return; } // The event clock moves to the deadline only, so input still queued // keeps its own timestamps. this.advanceTime(earliest); }; - this.realTimer = this.clock.setTimeout(() => fire(true), delay); + this.realTimer = this.clock.setTimeout( + () => fire('deadline', earliest), + delay, + ); } } diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts index d5a724e20862d..75fd404f41f22 100644 --- a/packages/core/src/gestures/__tests__/arena.test.ts +++ b/packages/core/src/gestures/__tests__/arena.test.ts @@ -472,12 +472,14 @@ describe('arena: a timer that fires late', () => { expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); }); - it('still fires on its deadline when nothing was queued', () => { + it('still fires on its deadline when nothing was queued, once the wait for queued input ends', () => { const {clock, arena, log} = pressArena(); clock.runTask(800); clock.runTask(800); + expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); + clock.runTask(850); expect(log).toContain('press:began@500'); - arena.ended([{id: 1, x: 0, y: 0, time: 820}]); + arena.ended([{id: 1, x: 0, y: 0, time: 870}]); }); }); diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts index 0af4841366c32..2c2a7077f44c5 100644 --- a/packages/core/src/hooks/usePager.test.ts +++ b/packages/core/src/hooks/usePager.test.ts @@ -899,7 +899,10 @@ describe('createPager', () => { // Still moving 40 ms after the touch. expect(f.pager.isSettling).toBe(true); await advance(paging.catchStopMs, f.clock); - // The catch's deadline is on the gesture clock. + // The catch's deadline is on the gesture clock. It ran late, so it waits + // 50 ms for input still queued before it. + f.clock.runDue(now); + await advance(50, f.clock); f.clock.runDue(now); expect(f.pager.isSettling).toBe(false); const held = -f.x(); @@ -2045,6 +2048,9 @@ describe('createPager', () => { expect(pager.isSettling).toBe(true); resize(300); await advance(paging.catchStopMs, f.clock); + // The catch's deadline ran late: it waits 50 ms for queued input. + f.clock.runDue(now); + await advance(50, f.clock); f.clock.runDue(now); expect(pager.isSettling).toBe(false); const held = -f.x(); @@ -3555,6 +3561,9 @@ describe('review fixes', () => { // A mouse waits out UIKit's catch delay, even on a goTo move. expect(f.pager.isSettling).toBe(true); await advance(120, f.clock); + // The catch's deadline ran late: it waits 50 ms for queued input. + f.clock.runDue(now); + await advance(50, f.clock); f.clock.runDue(now); expect(f.pager.isSettling).toBe(false); expect(refuses()).toBe(false); From 7764661b6a1d426d90c458a0b7d9abd0c1717795 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:49:24 -0800 Subject: [PATCH 092/151] test(ContextMenu): late finger's pointer, heard finger, failed load Cases that fail at the touch layer's deferred load today: - The gesture host's late begin returns early for a touchstart it heard while another gesture kept it listening, though nothing took that finger, so the finger never starts its hold. - A late finger has no pointer: its pointerdown came before the host listened. The host's late begin now takes the pointer id from its caller and pairs it. - When the touch layer's chunk fails to load, nothing warns, nothing loads it again, a held finger gets no menu, and the browser's own long-press menu stays cancelled. These cases make the import fail and expect one development warning, the 500 ms long press, the browser's menu, and a new load at the next touch. --- .../ContextMenu.touchLoadFailure.test.tsx | 210 ++++++++++++++++++ .../gestures/__tests__/GestureHost.test.ts | 39 ++++ 2 files changed, 249 insertions(+) create mode 100644 packages/core/src/ContextMenu/ContextMenu.touchLoadFailure.test.tsx diff --git a/packages/core/src/ContextMenu/ContextMenu.touchLoadFailure.test.tsx b/packages/core/src/ContextMenu/ContextMenu.touchLoadFailure.test.tsx new file mode 100644 index 0000000000000..78568e5870ff7 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenu.touchLoadFailure.test.tsx @@ -0,0 +1,210 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenu.touchLoadFailure.test.tsx + * @input Uses vitest, Testing Library and ContextMenu, with the touch layer's + * import failing until a case lets it load + * @output Checks a finger on a ContextMenu whose touch layer failed to load: + * one development warning, the 500 ms long press and the browser's own + * long-press menu open the menu, and the next touch loads the layer again + * @position Testing; the loaded touch layer is in ContextMenu.test.tsx + */ + +import {act, cleanup, fireEvent, render, screen} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {contextMenu} from '../motion/uikit/contextMenu'; +import {__resetDevWarnings} from '../utils/devWarning'; +import {ContextMenu} from './ContextMenu'; +import {__resetContextMenuTouchLayerForTest} from './contextMenuTouchLoader'; + +/** The touch layer's import fails while `attempts` is at most `failUntil`. */ +const layerImport = vi.hoisted(() => ({ + attempts: 0, + failUntil: Number.POSITIVE_INFINITY, +})); + +vi.mock('./ContextMenuTouchLayer', async importOriginal => { + layerImport.attempts += 1; + if (layerImport.attempts <= layerImport.failUntil) { + throw new Error('Failed to fetch dynamically imported module'); + } + return importOriginal(); +}); + +interface Contact { + id: number; + x: number; + y: number; +} + +function dispatchTouch( + type: 'touchstart' | 'touchend', + target: EventTarget, + changed: Contact[], + all: Contact[], +): void { + const event = new Event(type, {bubbles: true, cancelable: true}); + const toTouch = (contact: Contact) => ({ + identifier: contact.id, + clientX: contact.x, + clientY: contact.y, + target, + }); + Object.defineProperty(event, 'changedTouches', {value: changed.map(toTouch)}); + Object.defineProperty(event, 'touches', {value: all.map(toTouch)}); + Object.defineProperty(event, 'timeStamp', {value: performance.now()}); + target.dispatchEvent(event); +} + +function finger(target: EventTarget) { + const contact = {id: 1, x: 20, y: 20}; + return { + down: () => dispatchTouch('touchstart', target, [contact], [contact]), + up: () => dispatchTouch('touchend', target, [contact], []), + }; +} + +const advance = (ms: number) => + act(() => { + vi.advanceTimersByTime(ms); + }); + +/** Runs the page's scheduled load, and what it starts, to its end. */ +async function settleLoad(): Promise { + await act(async () => { + await vi.advanceTimersByTimeAsync(100); + }); +} + +// The gesture host remembers the latest event time, and each install of fake +// timers restarts the faked clock. So every case moves it past the ones +// before it. +let clockEpoch = 0; + +describe('ContextMenu under a finger when its touch layer fails to load', () => { + let warn: ReturnType; + + beforeEach(() => { + vi.stubGlobal( + 'matchMedia', + vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + ); + HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) { + this.setAttribute('popover-open', ''); + }); + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + this.removeAttribute('popover-open'); + }); + vi.useFakeTimers({ + toFake: [ + 'setTimeout', + 'clearTimeout', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'performance', + 'Date', + ], + }); + clockEpoch += 100_000; + vi.advanceTimersByTime(clockEpoch); + __resetContextMenuTouchLayerForTest(); + __resetDevWarnings(); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + cleanup(); + warn.mockRestore(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + function renderMenu(): HTMLElement { + render( + +
Long-press me
+
, + ); + return screen.getByTestId('ctx'); + } + + it('warns once in development, however many loads fail', async () => { + const trigger = renderMenu(); + await settleLoad(); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('ContextMenu'); + const attempts = layerImport.attempts; + // The next touch asks again, and that load fails too. + const press = finger(trigger); + press.down(); + await settleLoad(); + press.up(); + expect(layerImport.attempts).toBe(attempts + 1); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it('gives a held finger the 500 ms long press after a failed load', async () => { + const trigger = renderMenu(); + await settleLoad(); + const press = finger(trigger); + press.down(); + advance(499); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + it('lets the browser’s own long-press menu open it after a failed load', async () => { + const trigger = renderMenu(); + await settleLoad(); + const press = finger(trigger); + press.down(); + advance(300); + fireEvent( + trigger, + new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + clientX: 20, + clientY: 20, + }), + ); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + press.up(); + }); + + // Last: once the layer has loaded, the page keeps it. + it('loads the layer again at the next touch, and a later finger gets the hold', async () => { + const trigger = renderMenu(); + await settleLoad(); + // The next load succeeds. The module loads here first, outside the fake + // timers, so the trigger's new load ends inside this case. + layerImport.failUntil = layerImport.attempts; + await import('./ContextMenuTouchLayer'); + const first = finger(trigger); + first.down(); + await settleLoad(); + first.up(); + await act(async () => { + await vi.advanceTimersByTimeAsync(contextMenu.press.menuDisplayMs * 2); + }); + vi.mocked(HTMLElement.prototype.showPopover).mockClear(); + const second = finger(trigger); + second.down(); + advance(contextMenu.press.menuDisplayMs - 1); + expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled(); + advance(1); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + second.up(); + }); +}); diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts index 8a031777402f5..e00380b8b7d95 100644 --- a/packages/core/src/gestures/__tests__/GestureHost.test.ts +++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts @@ -4534,6 +4534,45 @@ describe('a late begin: a finger that landed before its recognizer attached', () expect(states).toContain('began'); touch('touchend', handle, [finger], [], 600); }); + + it('begins a finger it heard but left untracked, as when another gesture keeps it listening', () => { + const {handle, other} = mount( + '
', + ); + // A gesture elsewhere keeps the host listening on the page. + detachers.push( + host.attach(other, new LongPressGestureRecognizer({name: 'other'})), + ); + const press = new LongPressGestureRecognizer({minimumPressDuration: 500}); + const states: string[] = []; + press.addListener(recognizer => states.push(recognizer.state)); + const finger = {id: 1, x: 10, y: 10, target: handle}; + // The host hears this touchstart, but nothing on the handle takes it. + const landed = touch('touchstart', handle, [finger], [finger], 0); + clock.time = 300; + detachers.push(host.attach(handle, press)); + host.beginLateTouches(landed as TouchEvent); + expect(press.numberOfTouches).toBe(1); + clock.runDue(799); + expect(states).not.toContain('began'); + clock.runDue(800); + expect(states).toContain('began'); + touch('touchend', handle, [finger], [], 900); + }); + + it('pairs a late finger with the pointer its caller hands over', () => { + const {handle} = mount('
'); + const press = new LongPressGestureRecognizer({minimumPressDuration: 500}); + const finger = {id: 1, x: 10, y: 10, target: handle}; + // The finger's pointerdown and touchstart came before any listener. + const landed = touch('touchstart', handle, [finger], [finger], 0); + clock.time = 300; + detachers.push(host.attach(handle, press)); + host.beginLateTouches(landed as TouchEvent, 31); + const [held] = press.trackedTouches; + expect(host.pointerIdOf(held)).toBe(31); + touch('touchend', handle, [finger], [], 900); + }); }); describe('where the primary pointer is fine (spec:AST-094 FR43, FR24)', () => { From b919d673566bb19ad856f2275539e7c157e9f51e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:49:52 -0800 Subject: [PATCH 093/151] fix(ContextMenu): late finger keeps its pointer; failed load recovers - The trigger keeps the touch pointerdown's id with a late finger's touchstart, and the gesture host's late begin pairs that pointer, so code that follows the finger's pointer can take it over. - The late begin now begins a finger the host heard but left untracked, as when another gesture kept it listening. A finger the host tracks stays as it is. - When the touch layer's chunk fails to load, the loader warns once in development, and the next touch on a trigger loads it again. Until then a finger gets today's 500 ms long press, and the browser's own long-press menu opens the menu: the trigger keeps no late touch. component:ContextMenu FR12 names when the touch layer loads and what a finger gets after a failed load; spec:AST-094 FR43's evidence row names the two new late-begin cases. --- .../specs/AST-094-touch-presentations/spec.md | 2 +- .../ContextMenu/ContextMenu.spec.md | 41 +++++----- packages/core/src/ContextMenu/ContextMenu.tsx | 73 +++++++++++++----- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 22 ++++-- .../src/ContextMenu/contextMenuTouchLoader.ts | 77 ++++++++++++++----- packages/core/src/gestures/GestureHost.ts | 39 ++++++++-- 6 files changed, 184 insertions(+), 70 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 080497c83d68b..b9ce237477d99 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -1163,7 +1163,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li | FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails | | FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails | | FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails | -| FR43 late begin | Gesture host unit tests on a finger that lands before its recognizer attaches | a finger begun at the attach from its own touchstart; its later drift past the press's limit; a touchstart the host already heard | a late finger whose hold counts from its touchstart rather than the attach, a late finger whose later moves or lift miss its recognizer, or a touchstart begun twice fails | +| FR43 late begin | Gesture host unit tests on a finger that lands before its recognizer attaches | a finger begun at the attach from its own touchstart; its later drift past the press's limit; a touchstart the host already heard; one it heard but left untracked; the finger's own pointer handed over | a late finger whose hold counts from its touchstart rather than the attach, a late finger whose later moves or lift miss its recognizer, a touchstart begun twice, a heard but untracked finger left unbegun, or a late finger with no pointer fails | | FR44 | Unit tests of a pen press a window blur ends, on a Switch, a Slider and the host, under a coarse and a fine pointer | a pen press on a Switch and on a Slider, blur mid-press: nothing toggles or commits; a pen whose contact ends in `pointercancel` | with the host keeping no note of a blur-cancelled pen, the Switch toggles at the pen's click | | all | iOS simulator: the UIKit reference capture and the same gesture in Safari; real iOS Safari devices; Android Chrome in the Android emulator (DEC-27) | per component | an unmatched curve or timing is a parity defect | | all (DEC-31) | The evidence-carry check, before device or emulator evidence from an earlier head counts at a later head | a later head that only merges `main`; the pull request's own changes byte-identical or changed; a merge that changes a file the pull request changes, a direct import of those changes, a shared motion or layer module, or none of them; a generated file among the pull request's own files that CI proves regenerates identically, or does not prove; a commit, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, or knowledge records, or not | the evidence-carry check compares the PR's own diff between the two heads, and the merge's changed files against the files the PR changes, the changes' direct imports and the shared motion and layer modules (currently `motion/transientCopy`, `motion/inertClone`, `motion/animator`, `motion/carryAnimations`, `Layer/useLayer`, `hooks/usePager`); any overlap fails, except a generated file among the pull request's own files that CI proves regenerates identically at the new head; a changed own diff, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, knowledge records or `.changeset/` release notes, passes | diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 51371c4d078a6..0262007ceebdd 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -15,6 +15,7 @@ verified_by: packages/core/src/ContextMenu/ContextMenu.test.tsx, packages/core/src/ContextMenu/ContextMenu.triggerProps.test.tsx, packages/core/src/ContextMenu/ContextMenu.sheetLoading.test.tsx, + packages/core/src/ContextMenu/ContextMenu.touchLoadFailure.test.tsx, packages/core/src/theme/themingTargets.test.ts, scripts/check-knowledge.mjs, apps/storybook/rtl-audit/targets.json, @@ -126,7 +127,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships. ContextMenu owns its invocation: its touch model's hold (the 400 ms commit, the 735 ms display and the drift rule, which `gestures/contextRequest.ts`'s plain long press does not time), its right click and its menu keys. It owns its open state and cleanup, and closes on an outside press through Layer's outside-press watch. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | -| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | +| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. The touch layer loads after the page's first paint, at the next idle moment, within 2 s. If it fails to load, a finger gets today's 500 ms long press, and the next touch loads it again. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | ### Allowed variation @@ -263,25 +264,25 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | -| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | -| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | -| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | -| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | -| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | -| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | -| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | -| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | -| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | -| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | -| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | -| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold); `ContextMenu.sheetLoading.test.tsx` (a pointer menu loads no sheet action list; a sheet menu opens, drills in and comes back) | Right click, long press, keyboard | A context request that does not open the menu, a dropped consumer handler, or a pointer menu that loads the sheet's action list fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | -| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | -| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" and "a finger that drifts past the tolerance before the touch layer loads gets no menu once it loads" | A held finger: the commit and the menu's display; a finger down before the touch layer loads, held still or drifting | A commit or a display off UIKit's moments fails. A hold that starts before the touch layer loads fails. A menu for a finger that drifted past the tolerance before the load fails. | `audit:ContextMenu/behavior` | -| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | -| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | +| FR1, FR4 | `ContextMenu.test.tsx` rendering, invocation, bottom-sheet, adaptive, compound, and disabled cases ("renders menu with role=\"menu\"", "opens menu on right-click", "opens from a keyboard-invoked contextmenu (Shift+F10 / Menu key)", "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before", "opens the real menu content in a BottomSheet when requested", "uses the BottomSheet for adaptive presentation on compact touch", "renders menuContent as menu items", "does not open when isDisabled is true") | Right-click, keyboard, long press; pointer and sheet; data and compound; disabled | A missing invocation path, menu role, sheet, or compound interior, or a disabled trigger that opens, fails. Evidence gap: no test asserts that a disabled trigger leaves the native context menu alone. | `audit:ContextMenu/anatomy` | +| FR2 | `themingTargets.test.ts` | Rendered targets | A rendered class absent from the documented targets fails. Evidence gap: no test asserts `context-menu` on either painted surface or its absence from the trigger. | `audit:ContextMenu/theming` | +| FR3 | `ContextMenu.test.tsx` destructive-variant, section, divider, selectable, and alias cases | Shared rows through ContextMenu | A row that loses DropdownMenu's semantics or variant fails. Evidence gap: no test asserts the BottomSheet and List delegation beyond rendering. | `audit:ContextMenu/theming` | +| FR5 | `ContextMenu.test.tsx` "acts on the row under a finger release, once, and swallows the stray click" and outside-dismissal cases; `outsidePress.test.ts` pan cases; `ContextMenuLongPress.interaction.browser.spec.ts` "a new finger that pans outside the open menu closes it, and the page scrolls"; `ContextMenuLongPress.a11y.chromium.spec.ts` | Finger release; long press lift; tap, mouse, pen, and pan outside | A row acting on the press row, a stray click that acts, a long press that closes its own menu, a tap or mouse press outside that leaves it open, or a pan outside that leaves it open fails. Evidence gap: no test asserts the FR31 grow, the opening-finger handoff, or the FR33 lift. | `audit:ContextMenu/behavior` | +| FR5, DD1 touch scope | Browser tests on the touch story, the menu opened by a finger under a coarse pointer and by a mouse and by Shift+F10 under a fine pointer | Touch-opened, mouse-opened and keyboard-opened menus on a block trigger | A mouse- or keyboard-opened menu that lifts its trigger, tints the page or grows, or a touch-opened menu that blurs the page, grows a second surface, or animates anything but transform and opacity, fails. Evidence gap: the lift and the grow are unbuilt, so no test asserts either. | `audit:ContextMenu/behavior` | +| FR5 Reduce Motion | Browser tests on the touch story with reduced motion | A touch-opened menu opening and closing under Reduce Motion | A lift, grow or shrink that moves rather than playing an opacity-only cross-fade of 200 ms or less (`spec:AST-094` FR8) fails. Evidence gap: no test exists. | `audit:ContextMenu/behavior` | +| FR5 motion roles | Role registry tests over `spec:AST-094` FR4 | `springs.contextMenuLift`, `springs.contextMenuDismiss` and `springs.contextMenuMorph` at tempo 1 and `'standard'` | A lift, return or grow that plays a curve or a literal instead of its spring role, or a role off its FR4 table value, fails. | `audit:ContextMenu/behavior` | +| DEC-2 | Element-count browser test on the touch story (`spec:AST-017` FR60) | At rest and lifted, fine and coarse pointer | A lift element at rest, a copy of the trigger, or an open count beyond the layer, the shadow, the anchor and the placeholder fails. Evidence gap: the lift is unbuilt, so no test exists. | `audit:ContextMenu/anatomy` | +| FR6, AR1, ORD1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" and cursor-anchor cases; "does not put aria-haspopup on the role-less trigger wrapper (menus-15)"; `ContextMenu.triggerProps.test.tsx`; `ContextMenuCursorAnchor.a11y.browser.spec.ts` | `span` in a paragraph; default `div`; pointer and keyboard anchors | A block trigger in prose, a trigger with a role or `aria-haspopup`, or an anchor outside the trigger fails. | `audit:ContextMenu/behavior` | +| FR7 | `ContextMenu.test.tsx` "drills into nested data items inside the BottomSheet", "renders a submenu from a nested items array and keyboard-reaches an item after it", and "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Sheet drill-in; pointer sub-menu; regions under ContextMenu | A missing sub-menu, an unreachable row after it, or a sub-menu dialog under ContextMenu fails. Evidence gap: no test here asserts the pointer drill-in on a phone. | `audit:ContextMenu/behavior` | +| FR8 | `ContextMenu.test.tsx` "wraps arrow navigation at the ends", typeahead cases, and disabled-row keyboard cases (`component:DropdownMenu` FR17) | Wrap; typeahead; disabled rows | A clamped arrow, a missing typeahead match, a disabled row the keys or typeahead skip, or a disabled row that acts or closes the menu fails. Evidence gap: no test asserts Page keys or auto-repeat. | `audit:ContextMenu/behavior` | +| FR9 | `ContextMenu.test.tsx` "lets a nested layer consume Escape before the context menu", "closes on Escape even when opened without auto-focus", and "ignores Escape during IME composition" | Nested layer; Escape; composition | A context menu that closes with its nested child, or on a composition Escape, fails. | `audit:ContextMenu/behavior` | +| FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold); `ContextMenu.sheetLoading.test.tsx` (a pointer menu loads no sheet action list; a sheet menu opens, drills in and comes back) | Right click, long press, keyboard | A context request that does not open the menu, a dropped consumer handler, or a pointer menu that loads the sheet's action list fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | +| FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | +| FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `ContextMenu.touchLoadFailure.test.tsx` (after a failed load: one development warning, the 500 ms long press, the browser's own long-press menu, and a new load at the next touch); `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" and "a finger that drifts past the tolerance before the touch layer loads gets no menu once it loads" | A held finger: the commit and the menu's display; a finger down before the touch layer loads, held still or drifting; a failed load | A commit or a display off UIKit's moments fails. A hold that starts before the touch layer loads fails. A menu for a finger that drifted past the tolerance before the load fails. A failed load that leaves a finger without a menu, or never loads again, fails. | `audit:ContextMenu/behavior` | +| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | +| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | ## Current-state impact diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 9d6eae34c072b..84867b8736f19 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -94,8 +94,11 @@ import {useTypeahead} from '../hooks/useTypeahead'; import {shadowHostOf} from '../utils/flatTree'; import {usePresentation} from '../utils/presentation'; import {contextMenu} from '../motion/uikit/contextMenu'; -import type {ContextMenuTouchHandle} from './ContextMenuTouchLayer'; -import {useContextMenuTouchLayer} from './contextMenuTouchLoader'; +import type {ContextMenuTouchHandle, LateTouch} from './ContextMenuTouchLayer'; +import { + retryContextMenuTouchLayer, + useContextMenuTouchLayer, +} from './contextMenuTouchLoader'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import { @@ -406,6 +409,7 @@ export function ContextMenu({ onTouchEnd: onTouchEndProp, onTouchCancel: onTouchCancelProp, onPointerMove: onPointerMoveProp, + onPointerDown: onPointerDownProp, 'data-testid': testId, ...rest }: ContextMenuProps) { @@ -476,14 +480,18 @@ export function ContextMenu({ const touchHandleRef = useRef(null); // The touch layer loads after the page's first paint, and only while the // touch model applies. - const TouchLayer = useContextMenuTouchLayer(touchModes && !isDisabled); - // A finger that lands before the touch layer has loaded. The layer begins - // it as it mounts, if the finger is still down. - const lateTouchRef = useRef(null); + const {layer: TouchLayer, hasFailed: hasTouchLayerFailed} = + useContextMenuTouchLayer(touchModes && !isDisabled); + // A finger that lands before the touch layer has loaded, with its pointer. + // The layer begins it as it mounts, if the finger is still down. + const lateTouchRef = useRef(null); + // The latest touch pointer to go down on the trigger. Chromium sends a + // finger's pointerdown before its touchstart. + const touchPointerIdRef = useRef(null); const takeLateTouch = useCallback(() => { - const touchStart = lateTouchRef.current; + const late = lateTouchRef.current; lateTouchRef.current = null; - return touchStart; + return late; }, []); const updateOpenState = useCallback( @@ -832,7 +840,8 @@ export function ContextMenu({ onTouchEnd: handleLongPressTouchEnd, onTouchCancel: handleLongPressTouchCancel, } = useLongPress({ - disabled: isDisabled || touchModes, + // After a failed touch-layer load, a finger gets today's 500 ms long press. + disabled: isDisabled || (touchModes && !hasTouchLayerFailed), onLongPress: useCallback( (point: {x: number; y: number}) => { const rect = getAnchorBaseRect(); @@ -852,9 +861,19 @@ export function ContextMenu({ (event: React.TouchEvent) => { handleLongPressTouchStart(event); if (touchModes && !isDisabled && TouchLayer == null) { - // Kept while the touch layer loads: one finger, until it lifts. - lateTouchRef.current = - event.touches.length === 1 ? event.nativeEvent : null; + if (hasTouchLayerFailed) { + // After a failed load, a touch is the intent that loads it again. + retryContextMenuTouchLayer(); + } else { + // Kept while the touch layer loads: one finger, until it lifts. + lateTouchRef.current = + event.touches.length === 1 + ? { + touchStart: event.nativeEvent, + pointerId: touchPointerIdRef.current, + } + : null; + } } onTouchStartProp?.(event); }, @@ -864,15 +883,16 @@ export function ContextMenu({ touchModes, isDisabled, TouchLayer, + hasTouchLayerFailed, ], ); const handleTriggerTouchMove = useCallback( (event: React.TouchEvent) => { - const touchStart = lateTouchRef.current; + const late = lateTouchRef.current; if ( - touchStart != null && + late != null && Array.from(event.nativeEvent.changedTouches).some(touch => - driftsPastTolerance(touchStart, touch, touch.identifier), + driftsPastTolerance(late.touchStart, touch, touch.identifier), ) ) { // A finger that drifts too far before the layer loads gets no menu. @@ -886,6 +906,7 @@ export function ContextMenu({ const handleTriggerTouchEnd = useCallback( (event: React.TouchEvent) => { lateTouchRef.current = null; + touchPointerIdRef.current = null; handleLongPressTouchEnd(event); onTouchEndProp?.(event); }, @@ -894,21 +915,36 @@ export function ContextMenu({ const handleTriggerTouchCancel = useCallback( (event: React.TouchEvent) => { lateTouchRef.current = null; + touchPointerIdRef.current = null; handleLongPressTouchCancel(event); onTouchCancelProp?.(event); }, [handleLongPressTouchCancel, onTouchCancelProp], ); + const handleTriggerPointerDown = useCallback( + (event: React.PointerEvent) => { + if (event.pointerType === 'touch' && event.isPrimary) { + touchPointerIdRef.current = event.pointerId; + // A finger whose pointerdown follows its touchstart, as in WebKit. + const late = lateTouchRef.current; + if (late != null && late.pointerId == null) { + lateTouchRef.current = {...late, pointerId: event.pointerId}; + } + } + onPointerDownProp?.(event); + }, + [onPointerDownProp], + ); const handleTriggerPointerMove = useCallback( (event: React.PointerEvent) => { - const touchStart = lateTouchRef.current; + const late = lateTouchRef.current; // Before the touch layer loads, Chromium sends a small drift's // pointermove but not its touchmove. if ( - touchStart != null && + late != null && event.pointerType === 'touch' && event.isPrimary && - driftsPastTolerance(touchStart, event) + driftsPastTolerance(late.touchStart, event) ) { lateTouchRef.current = null; } @@ -1083,6 +1119,7 @@ export function ContextMenu({ onTouchEnd={handleTriggerTouchEnd} onTouchCancel={handleTriggerTouchCancel} onPointerMove={handleTriggerPointerMove} + onPointerDown={handleTriggerPointerDown} data-testid={testId} {...stylex.props( styles.trigger, diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 53ef82953155b..e1c9fb2b66a4d 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -35,6 +35,13 @@ export interface ContextMenuTouchHandle { isTracking(): boolean; } +/** A finger that landed before the touch layer loaded and is still down. */ +export interface LateTouch { + readonly touchStart: TouchEvent; + /** The finger's own pointer, when its `pointerdown` reached the trigger. */ + readonly pointerId: number | null; +} + export interface ContextMenuTouchLayerProps { triggerRef: RefObject; /** Receives the layer's handle as it mounts, and null as it unmounts. */ @@ -49,10 +56,10 @@ export interface ContextMenuTouchLayerProps { /** The press ended with no menu: what mounted at the commit can go. */ onCancel?: () => void; /** - * The `touchstart` of a finger that landed before this layer loaded and is - * still down, else null. Read once, as the layer mounts. + * A finger that landed before this layer loaded and is still down, else + * null. Read once, as the layer mounts. */ - takeLateTouch?: () => TouchEvent | null; + takeLateTouch?: () => LateTouch | null; } /** @@ -140,10 +147,13 @@ export function ContextMenuTouchLayer({ // host. It runs after the recognizer attaches, so the host begins that // finger now and the hold starts at this mount. useEffect(() => { - const touchStart = takeLateTouch?.() ?? null; + const late = takeLateTouch?.() ?? null; const trigger = triggerRef.current; - if (touchStart != null && trigger != null) { - getGestureHost(trigger.ownerDocument).beginLateTouches(touchStart); + if (late != null && trigger != null) { + getGestureHost(trigger.ownerDocument).beginLateTouches( + late.touchStart, + late.pointerId, + ); } }, [takeLateTouch, triggerRef]); diff --git a/packages/core/src/ContextMenu/contextMenuTouchLoader.ts b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts index 937a916e80fd6..b3ec946fb066f 100644 --- a/packages/core/src/ContextMenu/contextMenuTouchLoader.ts +++ b/packages/core/src/ContextMenu/contextMenuTouchLoader.ts @@ -6,7 +6,8 @@ * @file contextMenuTouchLoader.ts * @input No props: ContextMenu calls `useContextMenuTouchLayer` while its * touch model applies - * @output The touch layer after the page loads it; `null` until then + * @output The touch layer after the page loads it, `null` until then, and + * whether its latest load failed; a new load after a failure * @position Between ContextMenu and its touch layer: loads the layer after * first paint * @@ -14,6 +15,7 @@ */ import {useEffect, useSyncExternalStore} from 'react'; +import {warnOnce} from '../utils/devWarning'; import {createModuleLoader} from '../utils/moduleLoader'; import type {ContextMenuTouchLayer as TouchLayer} from './ContextMenuTouchLayer'; @@ -30,7 +32,18 @@ import type {ContextMenuTouchLayer as TouchLayer} from './ContextMenuTouchLayer' */ export const LOAD_CAP_MS = 2000; -let layer: typeof TouchLayer | null = null; +/** What a ContextMenu reads of the page's touch layer. */ +export interface ContextMenuTouchLayerState { + /** The touch layer once it has loaded, else `null`. */ + readonly layer: typeof TouchLayer | null; + /** Whether the latest load failed. The next touch on a trigger asks again. */ + readonly hasFailed: boolean; +} + +const NOT_LOADED: ContextMenuTouchLayerState = {layer: null, hasFailed: false}; + +let state: ContextMenuTouchLayerState = NOT_LOADED; +/** Whether a load is scheduled or running. */ let isScheduled = false; const listeners = new Set<() => void>(); @@ -38,8 +51,12 @@ const layerModule = createModuleLoader( async () => import('./ContextMenuTouchLayer'), ); -function getLayer(): typeof TouchLayer | null { - return layer; +function getState(): ContextMenuTouchLayerState { + return state; +} + +function getServerState(): ContextMenuTouchLayerState { + return NOT_LOADED; } function subscribe(listener: () => void): () => void { @@ -49,8 +66,8 @@ function subscribe(listener: () => void): () => void { }; } -function publish(loaded: typeof TouchLayer | null): void { - layer = loaded; +function publish(next: ContextMenuTouchLayerState): void { + state = next; for (const listener of [...listeners]) { listener(); } @@ -58,9 +75,20 @@ function publish(loaded: typeof TouchLayer | null): void { function load(): void { layerModule.load().then( - loaded => publish(loaded.ContextMenuTouchLayer), - // If the chunk fails, the menu still opens from right clicks and keys. - () => {}, + loaded => { + publish({layer: loaded.ContextMenuTouchLayer, hasFailed: false}); + }, + (error: unknown) => { + // Nothing is scheduled now, so the next touch on a trigger asks again. + isScheduled = false; + publish({layer: null, hasFailed: true}); + warnOnce( + 'ContextMenu:touch-layer-load', + 'ContextMenu', + 'the touch layer failed to load. Until a later touch loads it, a held finger opens the menu after 500 ms.', + error, + ); + }, ); } @@ -85,15 +113,27 @@ function scheduleLoad(): void { } /** - * The touch layer after the page loads it, `null` until then. The first - * ContextMenu that wants it asks for the load, and later ones share it. It is - * `null` on the server and while hydrating, so both renders produce the same - * markup. + * Loads the touch layer again after a failed load. A touch on a trigger calls + * it: that touch is the intent that asks. + */ +export function retryContextMenuTouchLayer(): void { + if (!state.hasFailed || isScheduled) { + return; + } + isScheduled = true; + load(); +} + +/** + * The touch layer after the page loads it, `null` until then, and whether its + * latest load failed. The first ContextMenu that wants it asks for the load, + * and later ones share it. It is `null` on the server and while hydrating, so + * both renders produce the same markup. */ export function useContextMenuTouchLayer( isWanted: boolean, -): typeof TouchLayer | null { - const current = useSyncExternalStore(subscribe, getLayer, () => null); +): ContextMenuTouchLayerState { + const current = useSyncExternalStore(subscribe, getState, getServerState); // Syncs with the browser's frame and idle timers, which decide when the // touch layer loads. useEffect(() => { @@ -101,7 +141,7 @@ export function useContextMenuTouchLayer( scheduleLoad(); } }, [isWanted]); - return isWanted ? current : null; + return isWanted ? current : NOT_LOADED; } /** @@ -109,12 +149,13 @@ export function useContextMenuTouchLayer( * it. */ export async function __loadContextMenuTouchLayerForTest(): Promise { - publish((await layerModule.load()).ContextMenuTouchLayer); + const loaded = await layerModule.load(); + publish({layer: loaded.ContextMenuTouchLayer, hasFailed: false}); isScheduled = true; } /** Test only: drops the loaded layer and clears the scheduled load. */ export function __resetContextMenuTouchLayerForTest(): void { isScheduled = false; - publish(null); + publish(NOT_LOADED); } diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts index 1bd05ae570f24..922aada90b94d 100644 --- a/packages/core/src/gestures/GestureHost.ts +++ b/packages/core/src/gestures/GestureHost.ts @@ -3081,21 +3081,42 @@ export class GestureHost { }; /** - * Begins, now, the fingers of a `touchstart` this host did not hear. A + * Begins, now, the fingers of a `touchstart` this host did not track. A * recognizer that attaches while a finger is down on its element hands * over that finger's own touchstart. The caller passes only a touchstart - * whose fingers are still down. + * whose fingers are still down. A finger the host heard but left untracked + * begins too; a finger it tracks stays as it is. `pointerId` is the + * finger's own pointer, whose `pointerdown` came before the host listened. */ - beginLateTouches(event: TouchEvent): void { - this.beginTouches(event, this.arena.pageTime()); + beginLateTouches(event: TouchEvent, pointerId: number | null = null): void { + const [first] = touchesOf(event.changedTouches); + if (pointerId != null && first != null) { + // The finger's touchstart pairs with this pointer as it begins. + this.pendingPointers.set(pointerId, { + x: first.clientX, + y: first.clientY, + target: isNode(first.target) + ? landedOn(event, first.target) + : landedOn(event), + }); + } + this.beginTouches(event, this.arena.pageTime(), true); + if (pointerId != null) { + // A finger that did not begin leaves no pointer waiting for it. + this.pendingPointers.delete(pointerId); + } } - private beginTouches(event: TouchEvent, time: number): void { + private beginTouches(event: TouchEvent, time: number, isLate = false): void { + // A late touchstart the host heard is old news: its fingers are noted. + const isHeard = this.processed.has(event); this.endWheel(time); - this.noteFingersDown(event); + if (!isLate || !isHeard) { + this.noteFingersDown(event); + } // Where the host reads a finger from its pointer events (no ontouchstart, // as after touch emulation turns on), its Touch Events would track it twice. - if (!this.usesTouchEvents || !this.takeEvent(event)) { + if (!this.usesTouchEvents || (!this.takeEvent(event) && !isLate)) { return; } if (this.fingerTargets.length > 1) { @@ -3114,6 +3135,10 @@ export class GestureHost { if ((touch as StylusTouch).touchType === 'stylus') { continue; } + if (isLate && this.touchIds.has(touch.identifier)) { + // Already tracked: the touchstart began it when the host heard it. + continue; + } // A finger number still tracked here began again: the touch it named // ended where no listener of ours could hear it. this.cancelledFingers.delete(touch.identifier); From a45837737daf5f3c9803e3356c831db2d53c3150 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:54:35 -0800 Subject: [PATCH 094/151] test(gestures): a deadline among a coalesced move's samples A coalesced move carries the samples since the previous one. The arena runs every deadline due by the move's last sample before it delivers the move, so a drift sampled before a long press's deadline reaches the press after it began. This case expects the samples stamped before the deadline to come first, so the drift fails the press. A move whose samples stay inside the press's tolerance still lets it begin at its deadline. --- .../__tests__/arenaTimersAndClaims.test.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts index 395b582ccc8ba..374c2ee94279a 100644 --- a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts +++ b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts @@ -145,6 +145,31 @@ describe('a timer that fires late', () => { }); }); +describe('a coalesced move whose samples straddle a deadline', () => { + it('delivers the samples stamped before the deadline first: a drift among them fails the press', () => { + const {clock, arena, log} = pressArena(); + // One move reaches the page at 520 with the sample it coalesced: the + // finger drifted 40 px at 480, before the press's deadline at 500. + clock.time = 520; + arena.moved([ + {id: 1, x: 40, y: 0, time: 520, history: [{x: 40, y: 0, time: 480}]}, + ]); + expect(log.some(entry => entry.startsWith('press:began'))).toBe(false); + expect(log).toContain('press:failed@480'); + arena.ended([{id: 1, x: 40, y: 0, time: 540}]); + }); + + it('runs the deadline before the samples stamped at or after it', () => { + const {clock, arena, log} = pressArena(); + clock.time = 520; + arena.moved([ + {id: 1, x: 1, y: 0, time: 520, history: [{x: 1, y: 0, time: 480}]}, + ]); + expect(log).toContain('press:began@500'); + arena.ended([{id: 1, x: 1, y: 0, time: 540}]); + }); +}); + describe('cancelling an idle recognizer', () => { it('leaves it possible, so its next touch counts', () => { const h = createHarness(); From 6e45960f842dc91e8a9ab9683493c5bcc12ed5d9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 18:57:31 -0800 Subject: [PATCH 095/151] fix(gestures): a deadline among a coalesced move's samples runs between The arena ran every deadline due by a move's last sample before it delivered the move, so a coalesced move's earlier samples reached recognizers after a deadline they came before. A long press began though its finger drifted before its deadline, as when the samples of a blocked page arrive in one pointer move. Now a timer deadline that falls among a move's new samples splits the move: the samples stamped before the deadline go first, the deadline runs at its own time, and the rest follow. spec:AST-094 FR16 records it, beside the late deadline's wait. --- .changeset/gesture-arena-late-input.md | 2 +- .../specs/AST-094-touch-presentations/spec.md | 5 +- packages/core/src/gestures/GestureArena.ts | 93 ++++++++++++++++++- 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/.changeset/gesture-arena-late-input.md b/.changeset/gesture-arena-late-input.md index d0ff3f394959d..593f4d15abf35 100644 --- a/.changeset/gesture-arena-late-input.md +++ b/.changeset/gesture-arena-late-input.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] Behind a blocked page, a touch gesture's deadline waits for the input still queued before it. Touch moves can reach the page a frame after other input. A long press, a List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. A deadline whose timer runs more than 17 ms late waits 50 ms, and each input from before it that comes late keeps it waiting. +[fix] A touch gesture's deadline now runs after the input stamped before it. Behind a blocked page, a deadline whose timer runs more than 17 ms late waits 50 ms for input still queued, and each input from before it that comes late keeps it waiting. A deadline that falls among a coalesced move's samples runs between them. A long press, a List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. @vjeux diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 945905b448176..bebb500f57a7c 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -518,7 +518,8 @@ a measured, sourced difference exists. waits for input still queued before it. It waits 50 ms when its timer runs more than 17 ms late. Each input from before it that reaches the page more than 33 ms late keeps it waiting 50 ms more. An input stamped at or past the - deadline ends the wait. + deadline ends the wait. A deadline among a coalesced move's samples runs + between them: the samples stamped before it come first. - **FR17 — Native readings.** A recognizer's thresholds MUST follow UIKit's measured values (FR1, FR2). A pan begins at 10 pt of travel on either axis (a screen-edge pan attached to an element within the band at 15 px, FR18), @@ -1137,7 +1138,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li | FR11 theme | `generateThemeRules.test.ts` themed-`:active` cases; real-browser forced `:active` on the Themed press story | a theme `:active` on a base and on a variant with a trailing pseudo; fine pointer; coarse pointer with forced `:active` and with the press attribute | a bare theme `:active` rule a coarse pointer matches, or a coarse arm keyed on `:active`, fails | | FR13 | Resolver unit tests and a server-render test | coarse and fine pointer; narrow, wide and short; server render; hydrating render | a component that answers the conditions differently, or a touch presentation in the server or hydrating render, fails | | FR14 | Browser tests of a sheet over a scrolled list | scrolled and at its top | a midway handoff fails | -| FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a deadline run late behind a block, with a drift that reaches the page after the next task; an on-time deadline while input from before it still comes late; a pan at 10 pt per axis | a wrong winner, a late deadline, a deadline that runs before input queued before it, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails | +| FR15–FR17 | Recognizer unit tests on synthetic streams with explicit timestamps | exclusive, simultaneous, require-to-fail, nested; a watcher beside a claiming winner; a blocked main thread; a deadline run late behind a block, with a drift that reaches the page after the next task; an on-time deadline while input from before it still comes late; a coalesced move whose samples straddle a deadline; a pan at 10 pt per axis | a wrong winner, a late deadline, a deadline that runs before input queued before it, or a translation that keeps the hysteresis, or a watcher failed or cancelled by a claiming winner fails | | FR18–FR22 | Browser tests with real touch input (`spec:AST-013` FR10) | per-axis pans beside native scrolling, page zoom, cancelled touches, clicks after taps, keyboard activation, a modal scroll lock, a control that keeps its press through a drag; a still finger with sub-pixel jitter over a scroll view; a finger moved 9 px and 10 px straight, and (7, 7) and (8, 8) diagonally; a recognizer on an element whose author `touch-action` is narrower, including one without `pinch-zoom`; a screen-edge pan landing at 40 px and at 41 px from the edge, at 14 px and 15 px of travel, and a horizontal scroll that starts outside the band; a screen-edge pan on an element within the band, and on one that reaches beyond it; a sheet's pull from a list at its top, and from a list scrolled away from its top; a long press dragged past its tolerance after it began, which never scrolls the page | a ghost click, a scroll or zoom blocked other than by the author's `touch-action`, or a cancelled unowned touchmove outside FR19's five exceptions, a tap cancelled by sub-pixel movement or by under 10 px of travel, a scroll that does not take the touch at 10 px, or a derived `touch-action` wider than the author's, a screen-edge pan that claims outside its band or before 15 px on an element within the band, or has not claimed at 15 px, or an author scroll outside the band that is blocked, a band claim of `pan-x` on an element that reaches beyond the band, or a 15 px start there, or a scroll-edge pan that cancels a move a scroller could scroll, or begins before 10 pt, fails | | FR19 (DEC-30) | Gesture unit tests on synthetic streams; browser tests with real touch input in WebKit and Chromium | a tap that wobbles 2–4 px toward a scroll edge keeps every move, and a 5 px move is cancelled; a sideways move is never held; NavigationStack's content back swipe on a pushed screen; RefreshControl's pull at its top, whose touch path is not a scroll-edge pan (a guard) | a move under 5 px along the pan's axis cancelled, a move from 5 px left uncancelled while every scroller under the finger sits at its edge, a sideways move held, or a pan that begins before its hysteresis fails | | FR20 | Browser tests with real touch input in Chromium phone emulation (`spec:AST-013` FR10) | a horizontal drag under `pan-y`; a vertical drag under `pan-y` over a scroller with room; a vertical drag where no scroller has room | a horizontal drag under `pan-y` counted as the browser taking the touch, a vertical one over a scroller with room not counted, or a later uncancelable move counted, fails | diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index fcd63e4cff7a2..e5468d914cf9b 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -37,7 +37,8 @@ * exactly touch-down + 500 ms even when the main thread was blocked and the * timer callback came late, and a test drives the whole machine with explicit * timestamps and no real time at all. A deadline whose timer runs late waits - * while input from before it still reaches the page late. + * while input from before it still reaches the page late. A deadline among a + * coalesced move's samples runs between them. * * SYNC: When modified, update GestureRecognizer.ts and * __tests__/arena.test.ts. @@ -374,6 +375,27 @@ export class GestureArena { return; } this.noteArrival(inputs[0].time); + // A coalesced move carries the samples since the previous one. A deadline + // among them runs between them: the samples stamped before it come first. + let rest = inputs; + for ( + let deadline = this.deadlineAmong(rest); + deadline != null; + deadline = this.deadlineAmong(rest) + ) { + const before = samplesBefore(rest, deadline); + if (before.length > 0) { + this.deliverMoved(before); + } + this.advanceTime(deadline); + rest = samplesFrom(rest, deadline); + } + if (rest.length > 0) { + this.deliverMoved(rest); + } + } + + private deliverMoved(inputs: ReadonlyArray): void { this.run(inputs[0].time, () => { const changed = this.update(inputs, 'moved'); if (changed.length === 0) { @@ -1040,6 +1062,37 @@ export class GestureArena { } } + /** + * The earliest timer deadline among the new samples of `inputs`: after the + * earliest of them, and at or before the latest. Null when none falls there. + */ + private deadlineAmong(inputs: ReadonlyArray): number | null { + let earliest = Number.POSITIVE_INFINITY; + let latest = Number.NEGATIVE_INFINITY; + for (const input of inputs) { + const known = + this.records.get(input.id)?.touch.time ?? Number.NEGATIVE_INFINITY; + for (const sample of input.history ?? []) { + if (sample.time > known) { + earliest = Math.min(earliest, sample.time); + } + } + earliest = Math.min(earliest, input.time); + latest = Math.max(latest, input.time); + } + let found: number | null = null; + for (const timer of this.timers.values()) { + if ( + timer.deadline > earliest && + timer.deadline <= latest && + (found == null || timer.deadline < found) + ) { + found = timer.deadline; + } + } + return found; + } + /** * Whether input from before `deadline` reached the page late within the * last `LATE_INPUT_WAIT_MS`, so more of it may still be queued. @@ -1228,6 +1281,44 @@ export class GestureArena { } } +/** Each input cut to its samples stamped before `time`; inputs with none go. */ +function samplesBefore( + inputs: ReadonlyArray, + time: number, +): TouchInput[] { + const cut: TouchInput[] = []; + for (const input of inputs) { + const samples = [ + ...(input.history ?? []), + {x: input.x, y: input.y, time: input.time}, + ].filter(sample => sample.time < time); + const last = samples[samples.length - 1]; + if (last != null) { + cut.push({ + id: input.id, + x: last.x, + y: last.y, + time: last.time, + history: samples.slice(0, -1), + }); + } + } + return cut; +} + +/** Each input cut to its samples stamped at or after `time`; inputs with none go. */ +function samplesFrom( + inputs: ReadonlyArray, + time: number, +): TouchInput[] { + return inputs + .filter(input => input.time >= time) + .map(input => ({ + ...input, + history: (input.history ?? []).filter(sample => sample.time >= time), + })); +} + function sharesTouches(a: GestureRecognizer, b: GestureRecognizer): boolean { for (const id of internals(a).seenTouchIds) { if (internals(b).seenTouchIds.has(id)) { From 1f848c94a9c9be2de469e47ea33eaa4651a4caed Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 19:02:41 -0800 Subject: [PATCH 096/151] test(gestures): a deadline due during a late wait runs as it ends Two long presses whose deadlines both ran late behind one block: the first waits 50 ms for queued input, and the second comes due during that wait. Today the second waits 50 ms more, though no input came late. This case expects it to run as the first wait ends. --- .../__tests__/arenaTimersAndClaims.test.ts | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts index 374c2ee94279a..b5cc2d270130d 100644 --- a/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts +++ b/packages/core/src/gestures/__tests__/arenaTimersAndClaims.test.ts @@ -143,6 +143,60 @@ describe('a timer that fires late', () => { expect(log).toContain('press:began@500'); arena.ended([{id: 1, x: 1, y: 0, time: 840}]); }); + + it('runs a deadline that came due during a wait just after it, with no second wait', () => { + const clock = new TaskClock(); + const log: string[] = []; + const arena: GestureArena = new GestureArena({ + clock, + onTransition: (recognizer, _from, to) => + log.push(`${recognizer.name}:${to}@${arena.now()}`), + }); + const first = new LongPressGestureRecognizer({ + name: 'first', + minimumPressDuration: 500, + }); + const second = new LongPressGestureRecognizer({ + name: 'second', + minimumPressDuration: 600, + }); + arena.began([ + { + id: 1, + x: 0, + y: 0, + time: 0, + pointerType: 'touch', + target: null, + scroll: null, + recognizers: [first], + consumer: null, + }, + { + id: 2, + x: 100, + y: 0, + time: 0, + pointerType: 'touch', + target: null, + scroll: null, + recognizers: [second], + consumer: null, + }, + ]); + // Both deadlines ran late behind one block. The first waits 50 ms; the + // second comes due during that wait, so it runs as the wait ends. + clock.runTask(900); + clock.runTask(950); + clock.runTask(950); + clock.runTask(950); + expect(log).toContain('first:began@500'); + expect(log).toContain('second:began@600'); + arena.ended([ + {id: 1, x: 0, y: 0, time: 970}, + {id: 2, x: 100, y: 0, time: 970}, + ]); + }); }); describe('a coalesced move whose samples straddle a deadline', () => { From cf6fa67d943bbc76cc9560eaa560f1ae9d985a8c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 19:04:31 -0800 Subject: [PATCH 097/151] fix(gestures): a deadline due during a late wait runs as it ends A deadline that came due while the arena waited for queued input counted as late on its own and waited 50 ms more, though no input came late. The arena now notes when a wait ends with none still coming late, and counts a deadline's lateness from then. spec:AST-094 FR16 says so. --- docs/specs/AST-094-touch-presentations/spec.md | 5 +++-- packages/core/src/gestures/GestureArena.ts | 12 +++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index bebb500f57a7c..5ff6bba228aa0 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -518,8 +518,9 @@ a measured, sourced difference exists. waits for input still queued before it. It waits 50 ms when its timer runs more than 17 ms late. Each input from before it that reaches the page more than 33 ms late keeps it waiting 50 ms more. An input stamped at or past the - deadline ends the wait. A deadline among a coalesced move's samples runs - between them: the samples stamped before it come first. + deadline ends the wait. A deadline that comes due during the wait runs as it + ends. A deadline among a coalesced move's samples runs between them: the + samples stamped before it come first. - **FR17 — Native readings.** A recognizer's thresholds MUST follow UIKit's measured values (FR1, FR2). A pan begins at 10 pt of travel on either axis (a screen-edge pan attached to an element within the band at 15 px, FR18), diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index e5468d914cf9b..56588c3f12592 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -184,6 +184,11 @@ export class GestureArena { private latestTime = Number.NEGATIVE_INFINITY; /** The latest input that reached the page late: its own time, and when. */ private lateInput: {time: number; arrivedAt: number} | null = null; + /** + * When the latest wait for queued input ended with none still coming late. + * A deadline that came due during that wait is not late on its own. + */ + private quietSince = Number.NEGATIVE_INFINITY; private depth = 0; /** Open `deferResolution` calls: what their stops unblock waits. */ private deferDepth = 0; @@ -1246,9 +1251,11 @@ export class GestureArena { this.realTimer = null; this.realTimerDeadline = Number.POSITIVE_INFINITY; const now = this.clock.now(); + // A deadline that came due during a quiet wait is late only past it. + const lateBy = now - Math.max(dueAt, this.quietSince); if ( after !== 'yield' && - (now - dueAt > LATE_TIMER_MS || this.hasLateInputBefore(earliest, now)) + (lateBy > LATE_TIMER_MS || this.hasLateInputBefore(earliest, now)) ) { // Behind a blocked page, input from before the deadline can still be // queued, and a touch move can reach the page a frame after other @@ -1262,6 +1269,9 @@ export class GestureArena { ); return; } + if (after === 'wait') { + this.quietSince = now; + } if (after === 'deadline' && now > earliest) { // Late: a long task held the main thread past the deadline, and // input queued behind it may come before the deadline (a lift that From 1a404c9a11244b8d7b1ef134801a53086f363788 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 19:18:00 -0800 Subject: [PATCH 098/151] refactor(ContextMenu): leave late input to the gesture arena The arena now holds a late deadline for input still queued, and runs a deadline among a coalesced move's samples between them (spec:AST-094 FR16). So the press drops its own late-move wait: its menu shows at its moment, and until then only the tolerance rule stays. GestureTouch.inputTime goes too: no reader is left. The press's unit cases now drive the arena's clock, so they run the wait as a page does. A drift's cancel is stamped at the time the drift came with, and the menu's change at its moment. --- .../specs/AST-094-touch-presentations/spec.md | 16 ++- ...tMenuLongPress.interaction.browser.spec.ts | 24 ++-- .../src/ContextMenu/contextMenuPress.test.ts | 78 ++++++------- .../core/src/ContextMenu/contextMenuPress.ts | 105 +----------------- packages/core/src/gestures/GestureArena.ts | 3 - .../core/src/gestures/__tests__/arena.test.ts | 8 +- packages/core/src/gestures/types.ts | 11 +- 7 files changed, 72 insertions(+), 173 deletions(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 74c7cb3403405..7af0eaf06ce61 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -1088,15 +1088,13 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and - FR6 gap: a resize during a settle drops its velocity when it leaves the row past its new last page, or when the settle began before the viewport had a width. The row lands on its target at once. -- FR16 gap: ContextMenu's long press keeps its outcome on a blocked main - thread, but its menu can show later. When the menu's timer runs more than a - frame late, the menu waits up to 50 ms for moves still queued. A move from - before the moment that reaches the page more than two frames late holds it - the same way. -- Two waits: the arena's yield covers one task; the press's 50 ms covers moves - Chromium queues past the task and frame (FR16). The press reads when the page - runs from the arena (`pageTime()`), and each touch carries the time and - samples of the input that moved it (`inputTime`, `inputSamples`). +- FR16 gap: on a blocked main thread, a recognizer keeps its outcome, but it + reports it later. A deadline that runs late waits 50 ms or more for input + still queued, so ContextMenu's menu can show that much later. +- One wait: the arena holds a late deadline for input still queued, for every + recognizer (FR16). Each touch carries the samples of the input that moved it + at the times they came with (`inputSamples`). The host begins a late finger + at the time the page runs (`pageTime()`). - Consumer docs: none until a component ships its touch presentation; each component documents its own, including the `presentation` value that keeps the released surface (FR25). diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index b0d30676aa71d..a8da9355af6ba 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -419,10 +419,10 @@ test('a right click opens the menu at once while the touch layer has not loaded' await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); -/** The press counts a move as late when it reaches the page this long after its own time. */ +/** The gesture arena counts a move as late when it reaches the page this long after its own time. */ const LATE_INPUT_MS = 33; -/** How long the press waits after a late move that reached the page just before the menu's moment. */ -const LATE_MOVE_GAP_MS = 50; +/** How long the gesture arena holds the menu's moment after a late move that reached the page just before it. */ +const LATE_INPUT_WAIT_MS = 50; /** A hold that shifts 3 px once, as the page read it, on the page clock. */ interface ShiftedHold { @@ -505,7 +505,7 @@ async function holdWithShift( }; } -/** The shift reached the page before the menu's moment, inside the press's wait. */ +/** The shift reached the page before the menu's moment, inside the arena's wait. */ function expectShiftInsideWait( [, receivedAt]: [number, number], moment: number, @@ -516,8 +516,8 @@ function expectShiftInsideWait( ).toBeLessThan(moment); expect( moment - receivedAt, - 'the shift reached the page inside the press’s wait before the moment', - ).toBeLessThan(LATE_MOVE_GAP_MS); + 'the shift reached the page inside the arena’s wait before the moment', + ).toBeLessThan(LATE_INPUT_WAIT_MS); } test('a finger that shifts slightly just before 735 ms gets the menu at 735 ms when its move reaches the page on time (AST-094 FR12)', async ({ @@ -575,11 +575,11 @@ test('a finger that shifts slightly just before 735 ms gets the menu 50 ms later expect( (run.decided as number) - moment, 'the menu waited for moves still coming late', - ).toBeGreaterThanOrEqual(LATE_MOVE_GAP_MS - 1); + ).toBeGreaterThanOrEqual(LATE_INPUT_WAIT_MS - 1); expect( (run.decided as number) - moment, - 'the menu waited no longer than the press allows', - ).toBeLessThan(LATE_MOVE_GAP_MS + 20); + 'the menu waited no longer than the arena allows', + ).toBeLessThan(LATE_INPUT_WAIT_MS + 20); await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible(); }); @@ -800,11 +800,11 @@ test('a drift from before 735 ms that reaches the page behind a block still canc receivedAt, 'the move reached the page after the block', ).toBeGreaterThanOrEqual(blockEnd); - // The press waits 50 ms for moves still queued. + // The arena waits 50 ms for moves still queued. expect( receivedAt - blockEnd, - 'the move reached the page within the press’s wait', - ).toBeLessThan(50); + 'the move reached the page within the arena’s wait', + ).toBeLessThan(LATE_INPUT_WAIT_MS); } expect( await menuShownAt(page), diff --git a/packages/core/src/ContextMenu/contextMenuPress.test.ts b/packages/core/src/ContextMenu/contextMenuPress.test.ts index db5a4ff0362f5..92ee020122ee2 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.test.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.test.ts @@ -48,14 +48,15 @@ describe('ContextMenuPressRecognizer', () => { it('commits at the deadline even when the main thread runs the timer late', () => { const {harness, press, states} = setup(); harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - // Nothing ran until 900 ms (a blocked main thread): the press still - // began at 400. The menu's timer ran late, so it waits 50 ms for moves - // queued behind the block, and none came. - harness.advance(900); - expect(states).toEqual([`began@${COMMIT}`]); + // Nothing ran until 900 ms (a blocked main thread). The arena waits 50 ms + // for input queued behind the block. None came, so the commit and the + // menu's moment then run, each at its own time. + harness.clock.time = 900; + harness.clock.runDue(900); + expect(states).toEqual([]); + harness.clock.runDue(950); + expect(states).toEqual([`began@${COMMIT}`, `changed@${DISPLAY}`]); expect(press.beganAt).toBe(COMMIT); - harness.advance(950); - expect(states).toEqual([`began@${COMMIT}`, 'changed@950']); }); it('claims the finger at the commit and drops the lift’s click', () => { @@ -103,19 +104,15 @@ describe('ContextMenuPressRecognizer', () => { it('waits at the menu’s moment for moves that came before it but reach the page late, and a drift in them cancels', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); // The page gets a move from 450 ms only at 700 ms: it is behind. finger.move(3, 0, 450, undefined, 700); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); expect(press.isMenuDue).toBe(false); - // A late move that came at 600 ms, 14 px over. The arena holds its time - // at the clock, and the recognizer reads the time it came with. + // A late move that came at 600 ms, 14 px over. It reaches the page after + // the moment, and the hold ends at the time it came with. finger.move(14, 0, 600, undefined, DISPLAY + 10); - expect(states).toEqual([ - `began@${COMMIT}`, - 'changed@450', - `cancelled@${DISPLAY}`, - ]); + expect(states).toEqual([`began@${COMMIT}`, 'changed@450', 'cancelled@600']); expect(press.isMenuDue).toBe(false); finger.up(DISPLAY + 300); }); @@ -123,9 +120,9 @@ describe('ContextMenuPressRecognizer', () => { it('shows the menu for a move stamped from its moment on, even past the tolerance, and lets the finger move freely after', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); finger.move(3, 0, 450, undefined, 700); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); expect(press.isMenuDue).toBe(false); // Inside the tolerance at the moment, 14 px over 15 ms after it. finger.move(14, 0, DISPLAY + 15, undefined, DISPLAY + 20); @@ -133,7 +130,7 @@ describe('ContextMenuPressRecognizer', () => { expect(states).toEqual([ `began@${COMMIT}`, 'changed@450', - `changed@${DISPLAY + 15}`, + `changed@${DISPLAY}`, `changed@${DISPLAY + 15}`, ]); finger.up(DISPLAY + 300); @@ -142,9 +139,9 @@ describe('ContextMenuPressRecognizer', () => { it('judges each coalesced sample of a late move at its own time while the menu waits', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); finger.move(3, 0, 450, undefined, 700); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); // One late move with two samples: 13 px at 725 ms, before the moment, // then 14 px at 740 ms. Two separate moves would end the hold at the // first, so this one does too. @@ -159,16 +156,17 @@ describe('ContextMenuPressRecognizer', () => { expect(states).toEqual([ `began@${COMMIT}`, 'changed@450', - `cancelled@${DISPLAY + 5}`, + `cancelled@${DISPLAY - 10}`, ]); }); it('shows the waiting menu for a coalesced move whose samples before the moment stay inside the tolerance', () => { const {harness, press} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); finger.move(3, 0, 450, undefined, 700); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); + expect(press.isMenuDue).toBe(false); finger.move( 14, 0, @@ -184,11 +182,12 @@ describe('ContextMenuPressRecognizer', () => { it(`judges a coalesced move from behind a block until ${blockedUntil} ms before the menu shows`, () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); // On time until 640 ms. Then the page is blocked past the moment. finger.move(3, 0, 640); // The finger crossed 11.5 px at 650 ms. Its moves wait behind the block - // and come as one coalesced move. + // and come as one coalesced move. Its samples before the moment come + // first, in one move at the last of them. finger.move( 14, 0, @@ -203,7 +202,7 @@ describe('ContextMenuPressRecognizer', () => { expect(states).toEqual([ `began@${COMMIT}`, 'changed@640', - `cancelled@${blockedUntil - 5}`, + 'cancelled@700', ]); }); } @@ -211,10 +210,12 @@ describe('ContextMenuPressRecognizer', () => { it('shows a still finger’s menu after a block, once no move comes from behind it', () => { const {harness, press} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); + harness.clock.runDue(COMMIT); // The moment's timer runs 65 ms late behind a block. - harness.advance(DISPLAY, DISPLAY + 65); + harness.clock.time = DISPLAY + 65; + harness.clock.runDue(DISPLAY + 65); expect(press.isMenuDue).toBe(false); - harness.advance(DISPLAY + 115); + harness.clock.runDue(DISPLAY + 115); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); @@ -222,14 +223,14 @@ describe('ContextMenuPressRecognizer', () => { it('shows the menu once the late moves pause for 50 ms', () => { const {harness, press} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); finger.move(3, 0, 450, undefined, 700); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); expect(press.isMenuDue).toBe(false); // The wait runs on the arena's clock. - harness.advance(DISPLAY + 49); + harness.clock.runDue(DISPLAY + 49); expect(press.isMenuDue).toBe(false); - harness.advance(DISPLAY + 50); + harness.clock.runDue(DISPLAY + 50); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); @@ -237,10 +238,10 @@ describe('ContextMenuPressRecognizer', () => { it('shows the menu at its moment after a move that reached the page on time, with no wait', () => { const {harness, press, states} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); // A 3 px shift at 720 ms that the page gets at once: it is not behind. finger.move(3, 0, 720); - harness.advance(DISPLAY); + harness.clock.runDue(DISPLAY); expect(press.isMenuDue).toBe(true); expect(states).toEqual([ `began@${COMMIT}`, @@ -252,14 +253,15 @@ describe('ContextMenuPressRecognizer', () => { it('waits at the menu’s moment when its own timer runs late after a recent move', () => { const {harness, press} = setup(); const finger = harness.finger(1).down(0, 0, 0, {recognizers: [press]}); - harness.advance(COMMIT); + harness.clock.runDue(COMMIT); finger.move(3, 0, 730); // The page is busy: the moment's timer runs 40 ms late, so later moves // may still be queued. - harness.advance(DISPLAY, DISPLAY + 40); + harness.clock.time = DISPLAY + 40; + harness.clock.runDue(DISPLAY + 40); expect(press.isMenuDue).toBe(false); // No more moves came: the wait ends 50 ms after the late timer ran. - harness.advance(DISPLAY + 90); + harness.clock.runDue(DISPLAY + 90); expect(press.isMenuDue).toBe(true); finger.up(DISPLAY + 300); }); diff --git a/packages/core/src/ContextMenu/contextMenuPress.ts b/packages/core/src/ContextMenu/contextMenuPress.ts index f62761fd92bc0..592bb480f33dd 100644 --- a/packages/core/src/ContextMenu/contextMenuPress.ts +++ b/packages/core/src/ContextMenu/contextMenuPress.ts @@ -23,25 +23,6 @@ import {contextMenu} from '../motion/uikit/contextMenu'; const {commitMs, menuDisplayMs, allowableMovement} = contextMenu.press; -/** - * How long the finger's moves may pause before the menu stops waiting for - * late ones, in ms: three frames at 60 Hz. - */ -const LATE_MOVE_GAP_MS = 50; - -/** - * The page counts as behind its input when an input or a timer runs this long - * after its own time. In ms: two frames at 60 Hz. - */ -const LATE_INPUT_MS = 33; - -/** - * The menu's timer ran behind a blocked page when it runs this long after its - * deadline. In ms: one frame at 60 Hz. A timer has no dispatch delay of its - * own, so one frame is enough. - */ -const LATE_TIMER_MS = 17; - /** * The foundation's own press timer, which this recognizer never lets fire: * the hold below commits instead. It is longer than any hold, and under the @@ -99,15 +80,8 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { private pressTouchId: number | null = null; /** Where the finger landed, while its hold runs. The drift counts from here. */ private holdFrom: {x: number; y: number} | null = null; - /** - * The held finger's latest move: the time it came with, and when the page - * got it. - */ - private latestMove: {time: number; arrivedAt: number} | null = null; /** When the finger landed, on the arena's clock. The deadlines count from it. */ private holdStart = 0; - /** The menu's moment passed while the finger's moves still came late. */ - private isMenuWaiting = false; constructor(options: ContextMenuPressRecognizerOptions = {}) { super({ @@ -152,9 +126,6 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { protected override touchesMoved(touches: ReadonlyArray): void { const touch = touches.find(each => each.id === this.pressTouchId); - if (touch != null) { - this.latestMove = {time: touch.inputTime, arrivedAt: this.pageTime()}; - } const hasDrifted = touch != null && !this.followHold(touch); if (hasDrifted && this.state === 'possible') { this.setState('failed'); @@ -169,21 +140,16 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { /** * Follows the finger during its hold, through each sample of the move at - * the time it came with. A sample from the menu's moment on shows a - * waiting menu: the finger stayed inside the tolerance until then, and it - * moves freely after. A drift past `allowableMovement` on either axis ends - * the hold. Returns whether the hold still runs. + * the time it came with. A drift past `allowableMovement` on either axis + * before the menu's moment ends the hold; the finger moves freely after it. + * Returns whether the hold still runs. */ private followHold(touch: GestureTouch): boolean { - const moment = this.holdStart + menuDisplayMs; for (const sample of touch.inputSamples) { const from = this.holdFrom; if (from == null) { return false; } - if (this.isMenuWaiting && sample.time >= moment) { - this.presentMenu(); - } if ( Math.abs(sample.x - from.x) > allowableMovement || Math.abs(sample.y - from.y) > allowableMovement @@ -197,17 +163,9 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { private endHold(): void { this.clearTimer(); - this.stopMoveWait(); this.holdFrom = null; } - private stopMoveWait(): void { - if (this.isMenuWaiting) { - this.isMenuWaiting = false; - this.clearTimer(); - } - } - /** The hold's commit claims the finger, then waits for the menu's moment. */ private commit(): void { if (this.holdFrom == null) { @@ -227,34 +185,14 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { } /** - * The finger is still down at the menu's moment: the menu is due. When the - * page is behind its input, the finger's moves can reach it after that - * moment, though they came before it. While they still come, the menu - * waits for them, so a drift in them still ends the hold. A timer that ran - * late ran behind a blocked page, which may hold such moves too. + * The finger is still down at the menu's moment: the menu is due. Behind a + * blocked page, the arena runs this moment only after the moves stamped + * before it, so a drift among them still ends the hold. */ private showMenu(): void { if (!this.isMenuPending()) { return; } - const moment = this.holdStart + menuDisplayMs; - if (this.pageTime() - moment > LATE_TIMER_MS || this.hasLateMove()) { - this.waitForMoves(); - return; - } - this.presentMenu(); - } - - /** The wait's end: moves that still come late keep the menu waiting. */ - private endMoveWait(): void { - this.stopMoveWait(); - if (!this.isMenuPending()) { - return; - } - if (this.hasLateMove()) { - this.waitForMoves(); - return; - } this.presentMenu(); } @@ -262,47 +200,16 @@ export class ContextMenuPressRecognizer extends LongPressGestureRecognizer { return this.holdFrom != null && isActive(this.state) && !this.isMenuDue; } - private waitForMoves(): void { - this.isMenuWaiting = true; - // On the arena's clock, like the hold's own deadlines. It counts from when - // the page runs again. Behind a block, the event clock still reads the - // moment, and moves stamped after it are still queued. - const from = Math.max(this.now(), this.pageTime()); - this.setTimer(from + LATE_MOVE_GAP_MS, () => this.endMoveWait()); - } - - /** When the page runs now, on the arena's injected clock. */ - private pageTime(): number { - return this.arena?.pageTime() ?? this.now(); - } - private presentMenu(): void { - this.stopMoveWait(); this.isMenuDue = true; this.setState('changed'); } - /** - * Whether a move from before the menu's moment reached the page in the last - * `LATE_MOVE_GAP_MS`, more than `LATE_INPUT_MS` after its own time. - */ - private hasLateMove(): boolean { - const move = this.latestMove; - const now = this.pageTime(); - return ( - move != null && - move.time < this.holdStart + menuDisplayMs && - now - move.arrivedAt < LATE_MOVE_GAP_MS && - move.arrivedAt - move.time > LATE_INPUT_MS - ); - } - protected override reset(): void { super.reset(); this.endHold(); this.pressTouchId = null; this.press = null; - this.latestMove = null; this.isMenuDue = false; } } diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index b60460656e14d..19e0d565aeb00 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -274,7 +274,6 @@ export class GestureArena { x: input.x, y: input.y, time, - inputTime: input.time, inputSamples: [ ...(input.history ?? []), {x: input.x, y: input.y, time: input.time}, @@ -370,7 +369,6 @@ export class GestureArena { x: input.x, y: input.y, time, - inputTime: input.time, inputSamples: [{x: input.x, y: input.y, time: input.time}], startX: input.x, startY: input.y, @@ -1062,7 +1060,6 @@ export class GestureArena { touch.x = input.x; touch.y = input.y; touch.time = time; - touch.inputTime = input.time; touch.inputSamples = [ ...(input.history ?? []), {x: input.x, y: input.y, time: input.time}, diff --git a/packages/core/src/gestures/__tests__/arena.test.ts b/packages/core/src/gestures/__tests__/arena.test.ts index 85e19be541508..3cdd78433a929 100644 --- a/packages/core/src/gestures/__tests__/arena.test.ts +++ b/packages/core/src/gestures/__tests__/arena.test.ts @@ -406,11 +406,11 @@ describe('arena: cancellation and time', () => { }); it('holds a late input at the clock, and keeps the time it came with', () => { const h = createHarness(); - const seen: {time: number; inputTime: number}[] = []; + const seen: {time: number; cameAt: number | undefined}[] = []; const r = new Scripted('r', { moved: recognizer => { const [touch] = recognizer.trackedTouches; - seen.push({time: touch.time, inputTime: touch.inputTime}); + seen.push({time: touch.time, cameAt: touch.inputSamples.at(-1)?.time}); }, }); h.finger(1).down(0, 0, 100, {recognizers: [r]}); @@ -418,8 +418,8 @@ describe('arena: cancellation and time', () => { h.finger(1).move(5, 0, 300); h.finger(1).move(6, 0, 520); expect(seen).toEqual([ - {time: 500, inputTime: 300}, - {time: 520, inputTime: 520}, + {time: 500, cameAt: 300}, + {time: 520, cameAt: 520}, ]); }); it('keeps a late move’s coalesced samples at the times they came with', () => { diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts index 598501a78456c..a0811112afe79 100644 --- a/packages/core/src/gestures/types.ts +++ b/packages/core/src/gestures/types.ts @@ -81,16 +81,11 @@ export interface GestureTouch { y: number; /** Timestamp of the latest position. */ time: number; - /** - * The latest position's own timestamp, as the host read it. The arena's - * clock never runs back, so a late input's `time` is held at the clock; - * this field keeps the time the input came with. - */ - inputTime: number; /** * The latest event's positions at the times they came with, oldest first, - * ending with the current one at `inputTime`. The arena's clock filters - * `samples`; it does not filter these. + * ending with the current one. The arena's clock never runs back, so it + * holds a late input's `time` and filters `samples`; it does not change + * these. */ inputSamples: TouchSample[]; readonly startX: number; From 87de1ad3060e0d71dd9c0a243ddcff4aa6a1bceb Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 19:29:44 -0800 Subject: [PATCH 099/151] test(ContextMenu): a finger held through the load slides to pick component:ContextMenu FR13 hands the finger the menu opened under on to the menu. A finger that landed before the touch layer loaded had no pointer paired, so it could not slide onto an item and pick it. The touch hold now hands that finger's pointer to the gesture host. This case holds a finger through the load, slides it onto Share past the handoff and lifts it there: Share takes the focus and acts. The test's pointer helper can now mark the primary pointer, as a browser does for a first finger. FR13's evidence row names the case. --- .../ContextMenu/ContextMenu.spec.md | 2 +- .../core/src/ContextMenu/ContextMenu.test.tsx | 68 ++++++++++++++++++- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 05f07e7d0d427..722b08967b8b9 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -287,7 +287,7 @@ anchor is positioning infrastructure rather than consumer anatomy. | FR10, PR1 | `ContextMenu.test.tsx` invocation and handler-composition cases ("composes the consumer context-menu handler with menu opening", "keeps component-owned opening when a consumer prevents default", "passes touch events through to the consumer’s own handlers", and the cases where a consumer `onTouchStart` or `onTouchEnd` runs beside the hold); `ContextMenu.sheetLoading.test.tsx` (a pointer menu loads no sheet action list; a sheet menu opens, drills in and comes back) | Right click, long press, keyboard | A context request that does not open the menu, a dropped consumer handler, or a pointer menu that loads the sheet's action list fails. Evidence gap: no test asserts listener cleanup on unmount; nothing tests a headless factory, which does not ship (the FR10 gap). | `audit:ContextMenu/behavior` | | FR11 | `ContextMenu.test.tsx` "Tab from a flyout leaves the whole menu" case | a sub-menu row | A Tab that leaves the menu or a flyout open, or a second `onOpenChange(false)`, fails. | `audit:ContextMenu/accessibility` | | FR12 | `ContextMenu.test.tsx` "opens for a finger still down at 735 ms (iOS 26.2), not a millisecond before" and "opens at the lift for a finger lifted after the commit (400 ms), as UIKit does", and the "before its touch layer loads" cases; `ContextMenu.touchLoadFailure.test.tsx` (after a failed load: one development warning, the 500 ms long press, the browser's own long-press menu, and a new load at the next touch); `contextMenuPress.test.ts`; `ContextMenuLongPress.interaction.browser.spec.ts` "a finger that lands before the touch layer loads starts the hold once it loads: the menu shows 735 ms after the load" and "a finger that drifts past the tolerance before the touch layer loads gets no menu once it loads"; `contextMenuPressFeedback.test.tsx` "grows toward the held scale on springs.contextMenuLift, from the onset" and "returns on springs.contextMenuDismiss, at the time the recognizer ended the press"; `ContextMenuTouchGrowth.test.tsx` onset cases; the touch story's browser curve and busy-thread cases in Chromium, and an iOS Safari recording for WebKit | A held finger: the commit, the display, the onset, the growth, the early-lift return, their springs; a finger down before the touch layer loads, held still or drifting; a failed load | A commit or a display off UIKit's moments, a growth before the onset, or a growth or return off its spring role fails. A hold that starts before the touch layer loads fails. A menu for a finger that drifted past the tolerance before the load fails. A failed load that leaves a finger without a menu, or never loads again, fails. | `audit:ContextMenu/behavior` | -| FR13 | `ContextMenu.test.tsx` "lets the finger the menu opened under slide onto an item, and its lift selects it" and its handoff, no-item and lift-open cases; `ContextMenuLongPress.interaction.browser.spec.ts` "the finger the menu opened under slides onto an item, which lights under it, and its lift selects it" and its early-lift and slide-past cases; `useMenuPress.test.tsx` continuation suite | Held until the menu opens: a slide onto an item, a still lift, a slide past the menu; a menu opened at the lift | A still lift that selects an item, a slide whose lift selects nothing or another item, a lift over no item that closes the menu, or a page that scrolls under the slide fails. | `audit:ContextMenu/behavior` | +| FR13 | `ContextMenu.test.tsx` "lets the finger the menu opened under slide onto an item, and its lift selects it" and its handoff, no-item and lift-open cases, and "lets a finger held through the load slide onto an item, and its lift selects it"; `ContextMenuLongPress.interaction.browser.spec.ts` "the finger the menu opened under slides onto an item, which lights under it, and its lift selects it" and its early-lift and slide-past cases; `useMenuPress.test.tsx` continuation suite | Held until the menu opens: a slide onto an item, a still lift, a slide past the menu; a finger held through the touch layer's load; a menu opened at the lift | A still lift that selects an item, a slide whose lift selects nothing or another item, a lift over no item that closes the menu, or a page that scrolls under the slide fails. | `audit:ContextMenu/behavior` | | Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` | | RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Presentation / BottomSheet submenu` story | BottomSheet opened into a submenu, LTR and RTL | The sheet header's back button not at the inline start of its heading in both directions fails D2. | `audit:ContextMenu/i18n-rtl` | diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index e76e8084e4b3d..59e27f0e6b671 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -772,7 +772,12 @@ const advance = (ms: number) => function dispatchPointer( type: 'pointerdown' | 'pointermove' | 'pointerup', target: EventTarget, - {pointerId, x, y}: {pointerId: number; x: number; y: number}, + { + pointerId, + x, + y, + isPrimary = false, + }: {pointerId: number; x: number; y: number; isPrimary?: boolean}, ): void { const event = new PointerEvent(type, { bubbles: true, @@ -780,6 +785,7 @@ function dispatchPointer( composed: true, pointerId, pointerType: 'touch', + isPrimary, clientX: x, clientY: y, button: 0, @@ -928,6 +934,66 @@ describe.each([ press.up(); }); + it('lets a finger held through the load slide onto an item, and its lift selects it', async () => { + const onCopy = vi.fn(); + const onShare = vi.fn(); + render( + +
Long-press me
+
, + ); + const trigger = screen.getByTestId('ctx'); + const contact = {id: 1, x: 20, y: 20}; + // The finger's pointer and its touch both reach the trigger before + // the layer loads. + dispatchPointer('pointerdown', trigger, { + pointerId: 7, + x: 20, + y: 20, + isPrimary: true, + }); + dispatchTouch('touchstart', trigger, [contact], [contact]); + advance(300); + await loadLayer(); + advance(contextMenu.press.menuDisplayMs); + expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1); + const share = screen.getByRole('menuitem', { + hidden: true, + name: 'Share', + }); + for (const y of [30, 45]) { + dispatchPointer('pointermove', share, { + pointerId: 7, + x: 20, + y, + isPrimary: true, + }); + dispatchTouch( + 'touchmove', + trigger, + [{...contact, y}], + [{...contact, y}], + ); + } + expect(share).toHaveFocus(); + act(() => { + dispatchPointer('pointerup', share, { + pointerId: 7, + x: 20, + y: 45, + isPrimary: true, + }); + dispatchTouch('touchend', trigger, [{...contact, y: 45}], []); + }); + expect(onShare).toHaveBeenCalledTimes(1); + expect(onCopy).not.toHaveBeenCalled(); + }); + it('opens nothing for a finger lifted before the load', async () => { const trigger = renderMenu(); const press = finger(trigger); From 65210b431776d58d6b68321f5c1dd214d57f4273 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 14 Nov 2026 19:30:10 -0800 Subject: [PATCH 100/151] test(useMenuPress): the continuation harness writes its ref at commit The continuation cases' harness wrote the hook's return into the test's ref during render, which architecture:react-component-runtime INV17 forbids: a render React discards would leave the test holding an uncommitted return. It now writes through useCommittedRefInto, with a fallback ref when the test passes none. --- packages/core/src/hooks/useMenuPress.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx index 79ec4058308d8..bdbda1d8eb0d8 100644 --- a/packages/core/src/hooks/useMenuPress.test.tsx +++ b/packages/core/src/hooks/useMenuPress.test.tsx @@ -24,6 +24,7 @@ import { type UseMenuPressReturn, } from './useMenuPress'; import {MENU_PRESS_HANDOFF_PX, MENU_PRESS_SETTLE_MS} from './menuPressGesture'; +import {useCommittedRefInto} from './useCommittedRef'; import {holdInput, isInputShield} from '../Layer/inputHold'; import { isMenuPressLit, @@ -119,6 +120,7 @@ function Harness({ }: HarnessProps) { const menuRef = useRef(null); const triggerRef = useRef(null); + const fallbackPressRef = useRef(null); const [isOpen, setIsOpen] = useState(false); const open = (next: boolean) => { setIsOpen(next); @@ -148,9 +150,7 @@ function Harness({ ? undefined : (longPressDelayMs ?? MENU_PRESS_LONG_PRESS_MS), }); - if (pressRef != null) { - pressRef.current = press; - } + useCommittedRefInto(pressRef ?? fallbackPressRef, press); return ( <>
+
+ {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + ]}> + Quarterly report for the whole design team + +
+ Quarterly report for the whole design team +
+
), }; diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 725e9538d7708..a01d4abbfb48a 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1163,6 +1163,29 @@ test('the trigger’s visual lays out its children as the trigger would: a block } }); +test('a trigger that cuts its own text with an ellipsis draws it as a plain box with the same style does', async ({ + page, +}) => { + await openStory(page, storybook(), 'core-contextmenu--touch-trigger-layouts'); + const trigger = page.getByTestId('layout-truncate'); + const reference = page.getByTestId('layout-truncate-reference'); + // The text is wider than the box that holds it, in each, so both cut it. + for (const box of [trigger, reference]) { + const isWider = await box.evaluate(root => { + const holder = [root, ...root.querySelectorAll('*')].find(el => + [...el.childNodes].some( + node => node.nodeType === Node.TEXT_NODE && node.textContent?.trim(), + ), + ); + return holder != null && holder.scrollWidth > holder.clientWidth; + }); + expect(isWider).toBe(true); + } + const drawn = await trigger.screenshot(); + const expected = await reference.screenshot(); + expect(drawn.equals(expected)).toBe(true); +}); + test('the menu’s anchor sits under the finger, on screen and as laid out, while the trigger is grown, and the menu stays put', async ({ page, }) => { From ce4266aeb6a5a6bb0131e414f4b329cc81d0d9c7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 11:15:27 -0800 Subject: [PATCH 126/151] docs(changeset): the arena's late wait follows the latest contact The release note tied the 50 ms wait to the pointer that owns the deadline. The arena gates it on the latest contact, as FR16 says. A late deadline first lets input still queued run. While the latest contact is a finger or a pen, a deadline whose timer runs more than 17 ms late also waits 50 ms. While it is a mouse or a trackpad, none does. --- .changeset/gesture-arena-late-input.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/gesture-arena-late-input.md b/.changeset/gesture-arena-late-input.md index 44d2e3bc54473..d2fb338a88f37 100644 --- a/.changeset/gesture-arena-late-input.md +++ b/.changeset/gesture-arena-late-input.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] A touch gesture's deadline now runs after the input stamped before it. Behind a blocked page, a finger's or pen's deadline whose timer runs more than 17 ms late waits 50 ms for input still queued. Each input from before it that comes late keeps it waiting. A mouse's or trackpad's deadline does not wait. A deadline that falls among a coalesced move's samples runs between them. A List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. +[fix] A touch gesture's deadline now runs after the input stamped before it. Behind a blocked page, a late deadline lets input still queued run first. While the latest contact is a finger or a pen, it waits 50 ms when its timer runs more than 17 ms late, even with nothing queued. Each finger's or pen's input from before it that comes late starts or extends that wait. While the latest contact is a mouse or a trackpad, no deadline waits 50 ms. A deadline that falls among a coalesced move's samples runs between them. A List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. @vjeux From bf8a6361abd537147e53e33a60ca8333a2cde894 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 11:15:27 -0800 Subject: [PATCH 127/151] chore(lint): the arena comment no longer cites FR16 This branch removed the FR16 citation from a comment in GestureArena.ts, but the comment-provenance baseline still listed it, so the baseline check failed. Drop that one entry. --- .../eslint-plugin-astryx/no-comment-provenance.baseline.json | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json index 2fa771d9de39c..618d904d191cb 100644 --- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json +++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json @@ -1389,7 +1389,6 @@ "FR15", "FR15", "FR15", - "FR16", "FR19", "FR21", "FR24", From ffb54471c21b268801d63d52f02ce4e76f8bcab3 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 11:17:40 -0800 Subject: [PATCH 128/151] fix(ContextMenu): the trigger's visual clips and cuts text as it would The inner box that the press grows holds the trigger's children. A trigger that cuts its own text with an ellipsis lost the ellipsis: the inner box neither clipped nor cut the text, so the trigger clipped it at its padding edge. The box now inherits the trigger's overflow and text-overflow, so it cuts the text as the trigger would. A trigger that scrolls its own content scrolls the box instead. --- packages/core/src/ContextMenu/ContextMenu.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index acc9d6af8f74c..d5c84b67ff06d 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -176,6 +176,11 @@ const styles = stylex.create({ minWidth: 0, height: '100%', borderRadius: 'inherit', + // The box takes the trigger's overflow and text-overflow as they are, so + // a trigger that cuts its own text keeps its ellipsis. A trigger that + // scrolls its own content scrolls this box instead. + overflow: 'inherit', + textOverflow: 'inherit', }, // 1px anchor placed at the cursor point within the trigger. The menu is // anchored to this element, so it sits under the cursor yet is positioned From 6eb342bae6b24d0a73863f82886e8e0fb5e5436a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 11:18:43 -0800 Subject: [PATCH 129/151] docs(changeset): the growth note names Reduce Motion and the load The note said a block trigger grows 150 ms after the finger lands. Under Reduce Motion it does not grow. A finger that lands before the touch code loads starts the hold at the load, so its growth starts 150 ms after the load. --- .changeset/contextmenu-touch-timeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index 810f46cf0f79e..8e40fc73bfd09 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. A block trigger whose menu opens at the finger starts to grow 150 ms after the finger lands, toward its held size on UIKit's lift spring, played on the compositor, and the hold keeps UIKit's measured moments. The growth scales an inner box that holds the trigger's children, so the menu never takes the press's scale. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the trigger springs back to its size. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. The trigger returns to its size when the menu closes. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. Either open focuses the first item, and the next touch on the trigger loads the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. A block trigger whose menu opens at the finger starts to grow 150 ms after the finger lands. It grows toward its held size on UIKit's lift spring, played on the compositor. Under Reduce Motion it does not grow. The hold keeps UIKit's measured moments. The growth scales an inner box that holds the trigger's children, so the menu never takes the press's scale. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu, and the trigger springs back to its size. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. The trigger returns to its size when the menu closes. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. A block trigger then starts to grow 150 ms after the load. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. Either open focuses the first item, and the next touch on the trigger loads the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux From f769e08cf263907aab5b09f84f0ee1c012c6461a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 13:25:15 -0800 Subject: [PATCH 130/151] test(PageControl): the held-finger proof's hold rule gets its own module The rule that finds where the hold began moves from the proof into holdBegin.ts, beside it, with the types it reads. It judges the same way, so a unit test can read it. --- .../PageControl.interaction.browser.spec.ts | 66 ++----------- .../src/PageControl/__tests__/holdBegin.ts | 94 +++++++++++++++++++ 2 files changed, 100 insertions(+), 60 deletions(-) create mode 100644 packages/lab/src/PageControl/__tests__/holdBegin.ts diff --git a/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts b/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts index d26a154fd709d..a56abf47f7cc3 100644 --- a/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts +++ b/packages/lab/src/PageControl/__tests__/PageControl.interaction.browser.spec.ts @@ -40,6 +40,7 @@ import { withStorybook, } from '@astryxdesign/interaction-harness'; import {jogInterval} from '../pageControlModel'; +import {holdBegin, type HeldClock, type TimerTask} from './holdBegin'; const storybook = withStorybook(test); @@ -56,42 +57,8 @@ const DOT_SCALE = 0.967; const MIN_JUDGED_FRAMES = 4; /** The one-slot slides the busy proof judges as one pool. */ const BUSY_SLIDES = 3; -/** UIPageControl's interaction delay, ms. */ -const HOLD_MS = 155; /** One frame at 60 Hz, ms. */ const FRAME_MS = 1000 / 60; -/** WebKit's page clocks keep whole milliseconds. */ -const CLOCK_SLOP_MS = 2; - -/** A timer the page ran, on the page's clock. */ -interface TimerTask { - id: number; - delay: number; - due: number; - ranAt: number | null; - scheduledAt: number; - /** The timer task that set it, if any. */ - parentId: number | null; -} - -/** What the held-finger proof records on the page, on the page's clock. */ -interface HeldClock { - /** The landing's pointer and touch event timeStamps. */ - landings: number[]; - /** When the page dispatched the landing, on the same clock. */ - dispatchedAt: number; - /** The timer task that runs now. */ - task: TimerTask | null; - timers: TimerTask[]; - frames: number[]; - flip: { - at: number; - task: TimerTask | null; - /** The pointer or touch event being dispatched at the commit, if any. */ - input: {type: string; timeStamp: number} | null; - fadedAt: number | null; - } | null; -} /** * Opens a PageControl story. The phone projects have a coarse primary @@ -565,32 +532,11 @@ test('a held finger shows the platter, the pressed overlay, and dims the other i if (flip == null) { throw new Error('The held look never showed.'); } - // The hold begins where the gesture arena learns its deadline has passed. - // That is the hold timer's own task, or the one 0 ms task the arena sets - // after the deadline when that timer ran late. It is also any input dated - // after the deadline that the page dispatches first. The look commits there. - const task = flip.task; - const parent = clock.timers.find(timer => timer.id === task?.parentId); - // The deadline is 155 ms after the landing, as the gesture arena dates it. - // The arena's clock never runs back, so a busy page that dispatches the - // landing late can date it as late as that dispatch. - const earliest = Math.min(...clock.landings) + HOLD_MS; - const latest = Math.max(clock.dispatchedAt, ...clock.landings) + HOLD_MS; - const holdTimer = - task != null && - task.delay === 0 && - parent != null && - task.scheduledAt >= earliest - ? parent - : task; - const isHoldTimer = - holdTimer != null && - holdTimer.due >= earliest - CLOCK_SLOP_MS && - holdTimer.due <= latest + CLOCK_SLOP_MS; - const isLateInput = - !isHoldTimer && - flip.input != null && - flip.input.timeStamp >= earliest - CLOCK_SLOP_MS; + const {task, parent, earliest, holdTimer, isLateInput} = holdBegin( + clock, + flip, + ); + const isHoldTimer = holdTimer != null; expect( isHoldTimer || isLateInput, `the held look commits where the hold begins: landing ${JSON.stringify(clock.landings)}, dispatched at ${clock.dispatchedAt}, commit task ${JSON.stringify(task)}, its parent ${JSON.stringify(parent ?? null)}, input ${JSON.stringify(flip.input)}`, diff --git a/packages/lab/src/PageControl/__tests__/holdBegin.ts b/packages/lab/src/PageControl/__tests__/holdBegin.ts new file mode 100644 index 0000000000000..c31da66a23e4a --- /dev/null +++ b/packages/lab/src/PageControl/__tests__/holdBegin.ts @@ -0,0 +1,94 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file holdBegin.ts + * @input What the held-finger proof records on the page: the landing, the + * timer tasks and the commit that shows the held look, on the page's clock + * @output Where the hold began: the gesture arena's deadline timer, or an + * input dated after the deadline + * @position Shared by the PageControl held-finger proof + * (PageControl.interaction.browser.spec.ts) and its unit test + */ + +/** UIPageControl's interaction delay, ms. */ +export const HOLD_MS = 155; +/** WebKit's page clocks keep whole milliseconds. */ +export const CLOCK_SLOP_MS = 2; + +/** A timer the page ran, on the page's clock. */ +export interface TimerTask { + id: number; + delay: number; + due: number; + ranAt: number | null; + scheduledAt: number; + /** The timer task that set it, if any. */ + parentId: number | null; +} + +/** The commit that shows the held look. */ +export interface HeldFlip { + at: number; + task: TimerTask | null; + /** The pointer or touch event being dispatched at the commit, if any. */ + input: {type: string; timeStamp: number} | null; + fadedAt: number | null; +} + +/** What the held-finger proof records on the page, on the page's clock. */ +export interface HeldClock { + /** The landing's pointer and touch event timeStamps. */ + landings: number[]; + /** When the page dispatched the landing, on the same clock. */ + dispatchedAt: number; + /** The timer task that runs now. */ + task: TimerTask | null; + timers: TimerTask[]; + frames: number[]; + flip: HeldFlip | null; +} + +export interface HoldBegin { + /** The timer task of the commit, and the task that set it. */ + task: TimerTask | null; + parent: TimerTask | undefined; + /** The earliest the deadline can be, as the gesture arena dates it. */ + earliest: number; + /** The gesture arena's deadline timer, when the hold began from it. */ + holdTimer: TimerTask | undefined; + /** An input dated after the deadline began the hold. */ + isLateInput: boolean; +} + +/** Where the hold began, for the commit that shows the held look. */ +export function holdBegin(clock: HeldClock, flip: HeldFlip): HoldBegin { + // The hold begins where the gesture arena learns its deadline has passed. + // That is the hold timer's own task, or the one 0 ms task the arena sets + // after the deadline when that timer ran late. It is also any input dated + // after the deadline that the page dispatches first. The look commits there. + const task = flip.task; + const parent = clock.timers.find(timer => timer.id === task?.parentId); + // The deadline is 155 ms after the landing, as the gesture arena dates it. + // The arena's clock never runs back, so a busy page that dispatches the + // landing late can date it as late as that dispatch. + const earliest = Math.min(...clock.landings) + HOLD_MS; + const latest = Math.max(clock.dispatchedAt, ...clock.landings) + HOLD_MS; + const candidate = + task != null && + task.delay === 0 && + parent != null && + task.scheduledAt >= earliest + ? parent + : task; + const holdTimer = + candidate != null && + candidate.due >= earliest - CLOCK_SLOP_MS && + candidate.due <= latest + CLOCK_SLOP_MS + ? candidate + : undefined; + const isLateInput = + holdTimer == null && + flip.input != null && + flip.input.timeStamp >= earliest - CLOCK_SLOP_MS; + return {task, parent, earliest, holdTimer, isLateInput}; +} From c25a39c5bf2da5b9a5fb44bf0f6372eeb2bf499c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 13:25:33 -0800 Subject: [PATCH 131/151] test(PageControl): the hold rule meets the arena's wait for queued input While a finger is down, the gesture arena waits 50 ms for input still queued after a late deadline, or after a late input from before it. The held-finger proof failed when that wait came. These cases replay what two runs recorded: the look committed in the wait's own task in Chromium, and at a move that ended a pending wait in WebKit. A wait that a later late input extends and a late deadline that waited come too. Each fails: the rule knows only the deadline's task and its 0 ms yield. --- .../PageControl/__tests__/holdBegin.test.ts | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 packages/lab/src/PageControl/__tests__/holdBegin.test.ts diff --git a/packages/lab/src/PageControl/__tests__/holdBegin.test.ts b/packages/lab/src/PageControl/__tests__/holdBegin.test.ts new file mode 100644 index 0000000000000..5e719f26dfd7e --- /dev/null +++ b/packages/lab/src/PageControl/__tests__/holdBegin.test.ts @@ -0,0 +1,120 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {describe, expect, it} from 'vitest'; +import { + holdBegin, + type HeldClock, + type HeldFlip, + type TimerTask, +} from './holdBegin'; + +/** A timer the page ran or cleared. */ +function timer( + id: number, + scheduledAt: number, + delay: number, + ranAt: number | null, + parentId: number | null = null, +): TimerTask { + return {id, delay, due: scheduledAt + delay, ranAt, scheduledAt, parentId}; +} + +function clockOf( + landing: number, + dispatchedAt: number, + timers: TimerTask[], +): HeldClock { + return { + landings: [landing, landing], + dispatchedAt, + task: null, + timers, + frames: [], + flip: null, + }; +} + +function flipAt( + at: number, + task: TimerTask | null, + input: HeldFlip['input'] = null, +): HeldFlip { + return {at, task, input, fadedAt: null}; +} + +describe('holdBegin', () => { + it('finds the deadline timer when the look commits in its own task', () => { + const deadline = timer(1, 551, 144, 695); + const result = holdBegin( + clockOf(540, 551, [deadline]), + flipAt(698, deadline), + ); + expect(result.holdTimer).toBe(deadline); + expect(result.isLateInput).toBe(false); + }); + + it('finds the deadline timer when the look commits in the 0 ms yield it sets after running late', () => { + const deadline = timer(1, 551, 144, 720); + const yieldTask = timer(2, 720, 0, 720.5, 1); + const result = holdBegin( + clockOf(540, 551, [deadline, yieldTask]), + flipAt(721, yieldTask), + ); + expect(result.holdTimer).toBe(deadline); + }); + + // A Chromium run under load: a move from before the deadline reached the + // page late, so the arena waited 50 ms after its on-time deadline. + it('finds the deadline timer when the look commits in the 50 ms wait for input still queued', () => { + const deadline = timer(1, 875.7, 147.6, 1022.9); + const wait = timer(2, 1023, 50, 1073.2, 1); + const result = holdBegin( + clockOf(868.3, 876.2, [deadline, wait]), + flipAt(1073.5, wait), + ); + expect(result.holdTimer).toBe(deadline); + }); + + // A WebKit run: the wait was pending when a move dated after the deadline + // came, and that move ended it. + it('finds the deadline timer when an input dated after the deadline ends a pending wait', () => { + const deadline = timer(1, 590, 153, 743); + const wait = timer(2, 743, 50, null, 1); + const result = holdBegin( + clockOf(586, 590, [deadline, wait]), + flipAt(782, null, {type: 'pointermove', timeStamp: 777}), + ); + expect(result.holdTimer).toBe(deadline); + }); + + it('finds the deadline timer through a wait that a later late input extended', () => { + const deadline = timer(1, 551, 144, 695); + const wait = timer(2, 695, 50, 745, 1); + const extended = timer(3, 745, 50, 795, 2); + const result = holdBegin( + clockOf(540, 551, [deadline, wait, extended]), + flipAt(796, extended), + ); + expect(result.holdTimer).toBe(deadline); + }); + + it('takes no other 50 ms timer for the hold', () => { + const other = timer(1, 600, 50, 650); + const result = holdBegin(clockOf(540, 551, [other]), flipAt(651, other)); + expect(result.holdTimer).toBeUndefined(); + expect(result.isLateInput).toBe(false); + }); + + it('keeps a deadline timer that ran late as the hold timer, so the proof judges its own lateness', () => { + const deadline = timer(1, 551, 144, 777); + const wait = timer(2, 777, 50, 827, 1); + const result = holdBegin( + clockOf(540, 551, [deadline, wait]), + flipAt(828, wait), + ); + expect(result.holdTimer).toBe(deadline); + expect((result.holdTimer?.ranAt ?? 0) - (result.holdTimer?.due ?? 0)).toBe( + 82, + ); + }); +}); From 35f9cb0648679ae5e45e0e414e96d76e2cc0e11a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 13:34:12 -0800 Subject: [PATCH 132/151] test(PageControl): the hold rule learns the arena's queued-input wait The held-finger proof now finds the deadline timer through the arena's own tasks after it: the one 0 ms yield, and each 50 ms wait for input still queued, a wait a later late input extends included. An input that ends a pending wait begins the hold from that deadline too. The page-stall check still judges the deadline timer's own lateness, so a deadline that ran late outside a stall still fails. --- .../src/PageControl/__tests__/holdBegin.ts | 56 +++++++++++++------ 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/packages/lab/src/PageControl/__tests__/holdBegin.ts b/packages/lab/src/PageControl/__tests__/holdBegin.ts index c31da66a23e4a..cdeb7980be3a9 100644 --- a/packages/lab/src/PageControl/__tests__/holdBegin.ts +++ b/packages/lab/src/PageControl/__tests__/holdBegin.ts @@ -14,6 +14,11 @@ export const HOLD_MS = 155; /** WebKit's page clocks keep whole milliseconds. */ export const CLOCK_SLOP_MS = 2; +/** + * While a finger is down, the gesture arena waits this long for input still + * queued after a late deadline, or after a late input from before it, ms. + */ +export const QUEUED_INPUT_WAIT_MS = 50; /** A timer the page ran, on the page's clock. */ export interface TimerTask { @@ -64,28 +69,47 @@ export interface HoldBegin { export function holdBegin(clock: HeldClock, flip: HeldFlip): HoldBegin { // The hold begins where the gesture arena learns its deadline has passed. // That is the hold timer's own task, or the one 0 ms task the arena sets - // after the deadline when that timer ran late. It is also any input dated - // after the deadline that the page dispatches first. The look commits there. + // after the deadline when that timer ran late. While a finger is down, a + // late deadline or a late input from before it makes the arena wait 50 ms + // for input still queued, in a task of its own. A later late input extends + // the wait, and an input dated at or after the deadline ends it. It is + // also any input dated after the deadline that the page dispatches first. + // The look commits there. const task = flip.task; - const parent = clock.timers.find(timer => timer.id === task?.parentId); + const byId = new Map(clock.timers.map(timer => [timer.id, timer])); + const parent = task?.parentId == null ? undefined : byId.get(task.parentId); // The deadline is 155 ms after the landing, as the gesture arena dates it. // The arena's clock never runs back, so a busy page that dispatches the // landing late can date it as late as that dispatch. const earliest = Math.min(...clock.landings) + HOLD_MS; const latest = Math.max(clock.dispatchedAt, ...clock.landings) + HOLD_MS; - const candidate = - task != null && - task.delay === 0 && - parent != null && - task.scheduledAt >= earliest - ? parent - : task; - const holdTimer = - candidate != null && - candidate.due >= earliest - CLOCK_SLOP_MS && - candidate.due <= latest + CLOCK_SLOP_MS - ? candidate - : undefined; + const isDeadline = (timer: TimerTask) => + timer.due >= earliest - CLOCK_SLOP_MS && + timer.due <= latest + CLOCK_SLOP_MS; + // The arena's own tasks after its deadline, each set from the task before + // it: the 0 ms yield and each 50 ms wait. + const isFollowUp = (timer: TimerTask) => + (timer.delay === 0 || timer.delay === QUEUED_INPUT_WAIT_MS) && + timer.scheduledAt >= earliest - CLOCK_SLOP_MS; + const deadlineOf = (timer: TimerTask | null | undefined) => { + let at = timer ?? undefined; + while (at != null && !isDeadline(at) && isFollowUp(at)) { + at = at.parentId == null ? undefined : byId.get(at.parentId); + } + return at != null && isDeadline(at) ? at : undefined; + }; + // An input that ends a wait commits the look while that wait is pending. + const pendingWait = + flip.input == null + ? undefined + : clock.timers.find( + timer => + timer.delay === QUEUED_INPUT_WAIT_MS && + timer.scheduledAt <= flip.at && + (timer.ranAt == null || timer.ranAt >= flip.at) && + deadlineOf(timer) != null, + ); + const holdTimer = deadlineOf(task) ?? deadlineOf(pendingWait); const isLateInput = holdTimer == null && flip.input != null && From 8c5edf9afef37f74204a4f992ba30452265c6893 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 16:03:19 -0800 Subject: [PATCH 133/151] docs(changeset): the arena's late wait, in FR16's words The release note promised that a touch deadline runs after every input stamped before it. The wait is bounded: an input that reaches the page after it, or that came less than 33 ms late, does not hold the deadline. The note now uses FR16's sentences for the wait and its extension, and a reorder hold or a Pager catch ends as it should only when the finger's drift or lift reaches the page during the wait. --- .changeset/gesture-arena-late-input.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/gesture-arena-late-input.md b/.changeset/gesture-arena-late-input.md index d2fb338a88f37..93d5051ea8c30 100644 --- a/.changeset/gesture-arena-late-input.md +++ b/.changeset/gesture-arena-late-input.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] A touch gesture's deadline now runs after the input stamped before it. Behind a blocked page, a late deadline lets input still queued run first. While the latest contact is a finger or a pen, it waits 50 ms when its timer runs more than 17 ms late, even with nothing queued. Each finger's or pen's input from before it that comes late starts or extends that wait. While the latest contact is a mouse or a trackpad, no deadline waits 50 ms. A deadline that falls among a coalesced move's samples runs between them. A List reorder hold or a Pager's catch whose finger drifted or lifted in time now ends as it should. +[fix] Behind a blocked page, a gesture deadline now waits for a finger's or pen's input stamped before it. A late deadline lets input still queued run first. While the latest contact is a finger or a pen, it waits 50 ms when its timer runs more than 17 ms late, even with nothing queued. Each finger's or pen's input from before it that reaches the page more than 33 ms late keeps it waiting 50 ms more. While the latest contact is a mouse or a trackpad, no deadline waits 50 ms. A deadline that falls among a coalesced move's samples runs between them. A List reorder hold or a Pager's catch whose finger's drift or lift reaches the page during that wait now ends as it should. @vjeux From b623ca58ab283ba82a4a24ed1f28ef2ad538e0ea Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 16:03:20 -0800 Subject: [PATCH 134/151] test(PageControl): an input from before the deadline ends no wait The hold rule counts an input that ends a pending wait as where the hold began, but it no longer checks that the input is dated at or after the deadline. Only such an input ends the arena's wait, so the proof would accept a look that an earlier input committed. The new case fails: the rule finds the deadline timer for it. --- .../lab/src/PageControl/__tests__/holdBegin.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/lab/src/PageControl/__tests__/holdBegin.test.ts b/packages/lab/src/PageControl/__tests__/holdBegin.test.ts index 5e719f26dfd7e..e536b2d67415e 100644 --- a/packages/lab/src/PageControl/__tests__/holdBegin.test.ts +++ b/packages/lab/src/PageControl/__tests__/holdBegin.test.ts @@ -98,6 +98,17 @@ describe('holdBegin', () => { expect(result.holdTimer).toBe(deadline); }); + it('takes no input dated before the deadline as the one that ends a pending wait', () => { + const deadline = timer(1, 551, 144, 695); + const wait = timer(2, 695, 50, null, 1); + const result = holdBegin( + clockOf(540, 551, [deadline, wait]), + flipAt(720, null, {type: 'pointermove', timeStamp: 650}), + ); + expect(result.holdTimer).toBeUndefined(); + expect(result.isLateInput).toBe(false); + }); + it('takes no other 50 ms timer for the hold', () => { const other = timer(1, 600, 50, 650); const result = holdBegin(clockOf(540, 551, [other]), flipAt(651, other)); From c5eddc264931dee0f772f8097283041a31b594dc Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 16:03:25 -0800 Subject: [PATCH 135/151] test(PageControl): only an input from the deadline on ends a wait The hold rule takes an input as the one that ended a pending wait only when it is dated at or after the deadline, as the arena's own rule does. The case added before now passes. --- packages/lab/src/PageControl/__tests__/holdBegin.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/lab/src/PageControl/__tests__/holdBegin.ts b/packages/lab/src/PageControl/__tests__/holdBegin.ts index cdeb7980be3a9..f06422dd967b8 100644 --- a/packages/lab/src/PageControl/__tests__/holdBegin.ts +++ b/packages/lab/src/PageControl/__tests__/holdBegin.ts @@ -99,8 +99,9 @@ export function holdBegin(clock: HeldClock, flip: HeldFlip): HoldBegin { return at != null && isDeadline(at) ? at : undefined; }; // An input that ends a wait commits the look while that wait is pending. + // Only an input dated at or after the deadline ends it. const pendingWait = - flip.input == null + flip.input == null || flip.input.timeStamp < earliest - CLOCK_SLOP_MS ? undefined : clock.timers.find( timer => From 1dd0bc3059d4bbd9b09f07af3eb3495560eaf7ea Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 16:06:51 -0800 Subject: [PATCH 136/151] docs(ContextMenu): the touch notes scope focus and the retry After a failed load, a bottom-sheet menu focuses its list, not its first item, so the touch timeline's note now says a popover menu focuses its first item, for keyboard and pointer opens too. The next touch only asks the module loader again, and a browser may keep a failed native import, so the note and FR12 say it asks for the code again. --- .changeset/contextmenu-touch-timeline.md | 2 +- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index 15a05957d964e..7c458b538e183 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. Either open focuses the first item, and the next touch on the trigger loads the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens of a popover menu still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. A popover menu opened this way focuses its first item, and the next touch on the trigger asks for the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index f481957f3bb96..d5764368fd540 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -127,7 +127,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships. ContextMenu owns its invocation: its touch model's hold (the 400 ms commit, the 735 ms display and the drift rule, which `gestures/contextRequest.ts`'s plain long press does not time), its right click and its menu keys. It owns its open state and cleanup, and closes on an outside press through Layer's outside-press watch. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | -| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. The touch layer loads once per page, after the page's first paint, when the main thread is idle and at most 2 s after that paint. No input starts or hurries the load. If it fails to load, a finger gets today's 500 ms long press, and the next touch loads it again. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | +| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. The touch layer loads once per page, after the page's first paint, when the main thread is idle and at most 2 s after that paint. No input starts or hurries the load. If it fails to load, a finger gets today's 500 ms long press, and the next touch asks for it again. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | ### Allowed variation From 105dccbde4504eec72bb221a003da5fb23c65c9a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 16:27:01 -0800 Subject: [PATCH 137/151] docs(changeset): the slide follows the touch model's hold The slide-to-pick note promised the slide wherever a held finger opens the menu. After a failed touch-layer load, the 500 ms long press opens it at the finger and hands nothing over. The note now says, in FR13's words, that the slide follows the touch model's hold. --- .changeset/contextmenu-touch-slide-to-pick.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/contextmenu-touch-slide-to-pick.md b/.changeset/contextmenu-touch-slide-to-pick.md index a1d8f0392d6b0..0caad0d9516d0 100644 --- a/.changeset/contextmenu-touch-slide-to-pick.md +++ b/.changeset/contextmenu-touch-slide-to-pick.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu where the primary pointer is coarse and the menu opens at the finger (`presentation` unset, or `adaptive` where it stays a popover): after the held finger opens the menu, the same finger may slide onto an action without lifting, as on iOS. Lifting over an action picks it, and lifting over no action leaves the menu open. The finger picks only after it has moved 10 px in the open menu, so a still lift picks nothing. +[feat] ContextMenu where the primary pointer is coarse (`presentation` unset, or `adaptive` where it stays a popover): after the touch model's hold opens the menu at the finger, the same finger may slide onto an action without lifting, as on iOS. Lifting over an action picks it, and lifting over no action leaves the menu open. The finger picks only after it has moved 10 px in the open menu, so a still lift picks nothing. @vjeux From 7ddbbf3af6bc8ab6c0d6dc686e597bd54422dea5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 18:15:35 -0800 Subject: [PATCH 138/151] test(ContextMenu): triggers that clip or scroll draw as plain boxes The trigger-layouts story gains triggers beside plain boxes with the same style: one clips a header pulled into its padding and nowrap text, one clips a child's ring, one cuts a multi-line label, one lets a badge overflow, and one scrolls. The spec compares each pair's pixels under the touch model once the touch layer loads, and with a mouse. Both fail in Chromium and WebKit: the trigger's visual takes its overflow, so it clips at the content edge, and the visual scrolls instead. --- .../storybook/stories/ContextMenu.stories.tsx | 127 +++++++++++++++--- ...tMenuLongPress.interaction.browser.spec.ts | 97 ++++++++++--- 2 files changed, 188 insertions(+), 36 deletions(-) diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 5b2f3a548f2ca..9dca8cc8d5d28 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -740,7 +740,7 @@ const layoutStyles = stylex.create({ borderRadius: '8px', backgroundColor: '#d1d5db', }, - truncatePair: { + cutPair: { display: 'grid', gridTemplateColumns: '160px 160px', gap: '24px', @@ -752,8 +752,92 @@ const layoutStyles = stylex.create({ whiteSpace: 'nowrap', backgroundColor: '#f3f4f6', }, + clip: { + padding: '12px', + overflow: 'hidden', + borderRadius: '12px', + backgroundColor: '#f3f4f6', + }, + bleed: { + height: '24px', + margin: '-12px -12px 8px', + backgroundColor: '#6b7280', + }, + nowrap: { + display: 'block', + whiteSpace: 'nowrap', + }, + ring: { + padding: '12px', + overflow: 'hidden', + backgroundColor: '#f3f4f6', + }, + ringed: { + width: '64px', + height: '24px', + borderRadius: '6px', + backgroundColor: '#d1d5db', + boxShadow: '0 0 0 8px #6366f1', + }, + lines: { + height: '52px', + padding: '8px', + overflow: 'hidden', + backgroundColor: '#f3f4f6', + }, + badge: { + position: 'relative', + padding: '12px', + backgroundColor: '#f3f4f6', + }, + badgeDot: { + position: 'absolute', + top: '-6px', + insetInlineEnd: '-6px', + width: '16px', + height: '16px', + borderRadius: '8px', + backgroundColor: '#ef4444', + }, + scroll: { + height: '48px', + padding: '8px', + overflow: 'auto', + scrollbarWidth: 'none', + backgroundColor: '#f3f4f6', + }, + scrollContent: { + height: '120px', + backgroundImage: 'linear-gradient(#d1d5db, #374151)', + }, }); +/** Triggers that clip, cut, scroll or overflow their content, by name. */ +const CUT_CASES = { + truncate: () => <>Quarterly report for the whole design team, + clip: () => ( + <> +
+ + Quarterly report for the team + + + ), + ring: () =>
, + lines: () => ( + <> + Quarterly report for the whole design team, edited today by three people + + ), + badge: () => ( + <> + Inbox + + + ), + scroll: () =>
, +} as const; + const LAYOUTS = ['block', 'row', 'grid'] as const; function TallContent() { @@ -776,7 +860,7 @@ export const TouchTriggerLayouts: Story = { docs: { description: { story: - 'The press grows only the trigger’s own visual, an inner box that lays the children out as the trigger would. Each trigger here sits beside a plain box with the same style, and both lay out the same, a set-height trigger with a full-height child too. A trigger that cuts its own text with an ellipsis draws it as the plain box does.', + 'The press grows only the trigger’s own visual, an inner box that lays the children out as the trigger would. Each trigger here sits beside a plain box with the same style, and both lay out the same, a set-height trigger with a full-height child too. Below them, triggers that cut their text, clip a header pulled into their padding, clip a child’s ring, cut a multi-line label, let a badge overflow, or scroll draw their content as the plain box does.', }, }, }, @@ -818,23 +902,28 @@ export const TouchTriggerLayouts: Story = {
-
- {}}, - {label: 'Share', icon: ShareIcon, onClick: () => {}}, - ]}> - Quarterly report for the whole design team - -
- Quarterly report for the whole design team -
-
+ {(Object.keys(CUT_CASES) as (keyof typeof CUT_CASES)[]).map(name => { + const Content = CUT_CASES[name]; + return ( +
+ {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + ]}> + + +
+ +
+
+ ); + })}
), }; diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index a01d4abbfb48a..3c36239fca75d 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1163,27 +1163,90 @@ test('the trigger’s visual lays out its children as the trigger would: a block } }); -test('a trigger that cuts its own text with an ellipsis draws it as a plain box with the same style does', async ({ +/** The trigger-layouts story's triggers that clip, cut, scroll or overflow. */ +const CUT_CASES = ['truncate', 'clip', 'ring', 'lines', 'badge', 'scroll']; + +/** + * Each cut case's trigger beside a plain box with the same style: the names + * whose pixels differ, and the display of the trigger's own visual. The + * truncating pair's text is wider than the box that holds it, and each + * scrolling box scrolls 30 px first. + */ +async function readCutCases(page: Page) { + const differing: string[] = []; + for (const name of CUT_CASES) { + const trigger = page.getByTestId(`layout-${name}`); + const reference = page.getByTestId(`layout-${name}-reference`); + for (const box of [trigger, reference]) { + if (name === 'truncate') { + const isWider = await box.evaluate(root => { + let holder: Element | null | undefined = [ + root, + ...root.querySelectorAll('*'), + ].find(el => + [...el.childNodes].some( + node => + node.nodeType === Node.TEXT_NODE && node.textContent?.trim(), + ), + ); + // An element with no box of its own leaves its text to the box + // around it. + while ( + holder != null && + holder !== root && + getComputedStyle(holder).display === 'contents' + ) { + holder = holder.parentElement; + } + return holder != null && holder.scrollWidth > holder.clientWidth; + }); + expect(isWider, name).toBe(true); + } + if (name === 'scroll') { + await box.evaluate(el => { + el.scrollTop = 30; + }); + } + } + const drawn = await trigger.screenshot(); + const expected = await reference.screenshot(); + if (!drawn.equals(expected)) { + differing.push(name); + } + } + const visualDisplay = await page + .getByTestId('layout-clip') + .evaluate(el => getComputedStyle(el.firstElementChild as Element).display); + return {differing, visualDisplay}; +} + +test('once the touch layer loads, a block trigger’s visual is a box, and triggers that clip, cut, scroll or overflow their content draw it as a plain box with the same style does', async ({ page, }) => { + const touchLayerChunk = watchTouchLayer(page); await openStory(page, storybook(), 'core-contextmenu--touch-trigger-layouts'); - const trigger = page.getByTestId('layout-truncate'); - const reference = page.getByTestId('layout-truncate-reference'); - // The text is wider than the box that holds it, in each, so both cut it. - for (const box of [trigger, reference]) { - const isWider = await box.evaluate(root => { - const holder = [root, ...root.querySelectorAll('*')].find(el => - [...el.childNodes].some( - node => node.nodeType === Node.TEXT_NODE && node.textContent?.trim(), - ), - ); - return holder != null && holder.scrollWidth > holder.clientWidth; + await waitForTouchLayer(page, touchLayerChunk); + const {differing, visualDisplay} = await readCutCases(page); + expect(visualDisplay).not.toBe('contents'); + expect(differing).toEqual([]); +}); + +test.describe('with a mouse', () => { + test.use({hasTouch: false, isMobile: false}); + + test('a block trigger’s visual is no box where the hold cannot grow it, so triggers that clip, cut, scroll or overflow their content draw it as a plain box does', async ({ + page, + }) => { + await openStory( + page, + storybook(), + 'core-contextmenu--touch-trigger-layouts', + ); + expect(await readCutCases(page)).toEqual({ + differing: [], + visualDisplay: 'contents', }); - expect(isWider).toBe(true); - } - const drawn = await trigger.screenshot(); - const expected = await reference.screenshot(); - expect(drawn.equals(expected)).toBe(true); + }); }); test('the menu’s anchor sits under the finger, on screen and as laid out, while the trigger is grown, and the menu stays put', async ({ From 4e1cc60eb67b8b0f805887833a10b31ea119112e Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 18:16:21 -0800 Subject: [PATCH 139/151] fix(ContextMenu): the trigger's visual is a box only where it grows The visual that the press grows wrapped every block trigger's children and took the trigger's overflow. A trigger that clips its overflow then cut its children at its content edge for every pointer, and a trigger that scrolls scrolled the visual instead. The visual is now no box (display: contents) unless the hold can grow it: under the touch model, for a block trigger whose menu opens at the finger, once the touch layer has loaded. There it takes the trigger's overflow only when the trigger cuts its own text, so the ellipsis stays and any other trigger keeps its own clip and its own scrolling. The touch layer reads that from the trigger's computed style, so the first load carries none of it. The element stays in place, so the children never remount. --- packages/core/src/ContextMenu/ContextMenu.tsx | 38 ++++++++++++++----- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 28 ++++++++++++++ 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index d5c84b67ff06d..a1f0940d26204 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -148,11 +148,16 @@ const styles = stylex.create({ WebkitUserSelect: 'none', userSelect: 'none', }, - // The trigger's own visual, which the press feedback grows. It lays its - // children out as the trigger would, and fills the trigger in block, flex - // and grid layout. A full-height child then keeps a set-height trigger's - // height. The cursor anchor stays outside it, so a layer never takes the - // press's scale. + // The trigger's own visual, which the press feedback grows. It is a box + // only where the hold can grow it. Elsewhere it is no box, so the trigger + // lays out, clips and cuts its children itself. + triggerVisualNone: { + display: 'contents', + }, + // As a box it lays its children out as the trigger would, and fills the + // trigger in block, flex and grid layout. A full-height child then keeps a + // set-height trigger's height. The cursor anchor stays outside it, so a + // layer never takes the press's scale. triggerVisual: { display: 'inherit', flexDirection: 'inherit', @@ -176,9 +181,11 @@ const styles = stylex.create({ minWidth: 0, height: '100%', borderRadius: 'inherit', - // The box takes the trigger's overflow and text-overflow as they are, so - // a trigger that cuts its own text keeps its ellipsis. A trigger that - // scrolls its own content scrolls this box instead. + }, + // The text of a trigger that cuts its own text sits in the box, so the box + // clips and cuts it as the trigger would. Any other trigger keeps its own + // clip, its children's rings and its own scrolling. + triggerVisualCut: { overflow: 'inherit', textOverflow: 'inherit', }, @@ -502,6 +509,9 @@ export function ContextMenu({ const cursorAnchorRef = useRef(null); // The trigger's own visual: what the press feedback grows. const visualRef = useRef(null); + // Whether the trigger cuts its own text (`text-overflow`). The touch layer + // reads it where the trigger's visual is a box. + const [cutsText, setCutsText] = useState(false); const triggerRef = useRef(null); // Element focused before the menu opened, restored when it closes so focus // does not fall to after Escape or outside-click dismissal. @@ -1192,6 +1202,10 @@ export function ContextMenu({ // An inline trigger (`span`) lets prose own a context menu without // breaking its flow. const TriggerElement = triggerAs === 'div' ? 'div' : 'span'; + // The hold grows a block trigger whose menu opens at the finger, once the + // touch layer has loaded. + const growsVisual = + TouchLayer != null && triggerAs === 'div' && !usesBottomSheet; const SheetForContent = usesSheetActionList ? MenuBottomSheet : MenuBottomSheetWithoutActionList; @@ -1222,7 +1236,12 @@ export function ContextMenu({ : []), )}> {triggerAs === 'div' ? ( -
+
{children}
) : ( @@ -1245,6 +1264,7 @@ export function ContextMenu({ triggerRef={triggerRef} visualRef={visualRef} isShown={triggerAs !== 'span' && !usesBottomSheet} + onTextCut={setCutsText} onOpen={openFromFinger} onCommit={prepareMenu} onCancel={layer.releasePrepared} diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 0f0b8f3ca256d..68afcd89588b5 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -27,6 +27,7 @@ import {isTerminal} from '../gestures/GestureRecognizer'; import {playHaptic} from '../gestures/haptics'; import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {useCommittedRef, useCommittedRefInto} from '../hooks/useCommittedRef'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {contextMenu} from '../motion/uikit/contextMenu'; import {isElement} from '../utils/nodeType'; import {ContextMenuPressRecognizer} from './contextMenuPress'; @@ -53,6 +54,12 @@ export interface ContextMenuTouchLayerProps { visualRef: RefObject; /** False for an inline trigger, which does not grow. */ isShown: boolean; + /** + * Receives whether the trigger cuts its own text (`text-overflow`), where + * its visual is a box: as the layer mounts, and when the trigger's class + * changes. + */ + onTextCut?: (cuts: boolean) => void; /** Receives the layer's handle as it mounts, and null as it unmounts. */ ref?: Ref; /** Open the menu at a client point (where the finger landed). */ @@ -89,6 +96,7 @@ export function ContextMenuTouchLayer({ triggerRef, visualRef, isShown, + onTextCut, ref, onOpen, onCommit, @@ -105,6 +113,26 @@ export function ContextMenuTouchLayer({ isFollowedRef, ); const feedbackRef = useCommittedRef(feedback); + // The trigger's class at the last read of its text-overflow. + const textCutClassRef = useRef(null); + // Syncs with the trigger's computed style: whether it cuts its own text, + // which decides whether its visual clips that text. It reads again only + // when the trigger's class changes. + useIsomorphicLayoutEffect(() => { + const trigger = triggerRef.current; + if ( + !isShown || + trigger == null || + onTextCut == null || + trigger.className === textCutClassRef.current + ) { + return; + } + textCutClassRef.current = trigger.className; + const cut = + trigger.ownerDocument.defaultView?.getComputedStyle(trigger).textOverflow; + onTextCut(cut != null && cut !== '' && cut !== 'clip'); + }); const onCancelRef = useCommittedRef(onCancel); const hasPressOpenedRef = useRef(false); From 78ee68fe6289e90b75d63d2b22504e583de6e70d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 20:24:27 -0800 Subject: [PATCH 140/151] docs(ContextMenu): a finger down before the touch layer loads FR12 said "a finger that lands before the touch layer has loaded", which the knowledge check reads as project status and warns on. It now says "a finger down before", with the same meaning. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index d5764368fd540..511ce73e58ef8 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -127,7 +127,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | | FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships. ContextMenu owns its invocation: its touch model's hold (the 400 ms commit, the 735 ms display and the drift rule, which `gestures/contextRequest.ts`'s plain long press does not time), its right click and its menu keys. It owns its open state and cleanup, and closes on an outside press through Layer's outside-press watch. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | -| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger that lands before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. The touch layer loads once per page, after the page's first paint, when the main thread is idle and at most 2 s after that paint. No input starts or hurries the load. If it fails to load, a finger gets today's 500 ms long press, and the next touch asks for it again. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | +| FR12 | Under a finger, the hold commits at 400 ms and the menu displays at 735 ms, as UIKit's do. They are measured input, not motion, and stay internal (`spec:AST-094` FR4, FR45). A finger down before the touch layer has loaded starts the hold once it loads; a mouse or keyboard opens as today. The touch layer loads once per page, after the page's first paint, when the main thread is idle and at most 2 s after that paint. No input starts or hurries the load. If it fails to load, a finger gets today's 500 ms long press, and the next touch asks for it again. | Measured: UIContextMenuInteraction on the iOS 26.2 simulator commits at 400 ms and displays its menu at 735 ms (`motion/uikit/contextMenu.ts`); `spec:AST-094` FR4, FR45 | ### Allowed variation From 265bc98c510b134aa06f312be4fd4795a5acf165 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 20:52:54 -0800 Subject: [PATCH 141/151] docs(gestures): a finger down before its recognizer attaches AST-094's late-begin evidence row said "a finger that lands before its recognizer attaches", which the knowledge check reads as project status and warns on. It now says "a finger down before", with the same meaning. --- docs/specs/AST-094-touch-presentations/spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md index 184f581a0da8e..982fd8ec02b4c 100644 --- a/docs/specs/AST-094-touch-presentations/spec.md +++ b/docs/specs/AST-094-touch-presentations/spec.md @@ -1175,7 +1175,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li | FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails | | FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails | | FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails | -| FR43 late begin | Gesture host unit tests on a finger that lands before its recognizer attaches | a finger begun at the attach from its own touchstart; its later drift past the press's limit; a touchstart the host already heard; one it heard but left untracked; the finger's own pointer handed over | a late finger whose hold counts from its touchstart rather than the attach, a late finger whose later moves or lift miss its recognizer, a touchstart begun twice, a heard but untracked finger left unbegun, or a late finger with no pointer fails | +| FR43 late begin | Gesture host unit tests on a finger down before its recognizer attaches | a finger begun at the attach from its own touchstart; its later drift past the press's limit; a touchstart the host already heard; one it heard but left untracked; the finger's own pointer handed over | a late finger whose hold counts from its touchstart rather than the attach, a late finger whose later moves or lift miss its recognizer, a touchstart begun twice, a heard but untracked finger left unbegun, or a late finger with no pointer fails | | FR44 | Unit tests of a pen press a window blur ends, on a Switch, a Slider and the host, under a coarse and a fine pointer | a pen press on a Switch and on a Slider, blur mid-press: nothing toggles or commits; a pen whose contact ends in `pointercancel` | with the host keeping no note of a blur-cancelled pen, the Switch toggles at the pen's click | | all | iOS simulator: the UIKit reference capture and the same gesture in Safari; real iOS Safari devices; Android Chrome in the Android emulator or on a real Pixel (DEC-27) | per component | an unmatched curve or timing is a parity defect | | all (DEC-31) | The evidence-carry check, before device or emulator evidence from an earlier head counts at a later head | a later head that only merges `main`; the pull request's own changes byte-identical or changed; a merge that changes a file the pull request changes, a direct import of those changes, a shared motion or layer module, or none of them; a generated file among the pull request's own files that CI proves regenerates identically, or does not prove; a commit, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, or knowledge records, or not | the evidence-carry check compares the PR's own diff between the two heads, and the merge's changed files against the files the PR changes, the changes' direct imports and the shared motion and layer modules (currently `motion/transientCopy`, `motion/inertClone`, `motion/animator`, `motion/carryAnimations`, `Layer/useLayer`, `hooks/usePager`, and the gesture arena and host of `architecture:react-component-runtime` INV13's shared touch set, `gestures/GestureArena` and `gestures/GestureHost`); any overlap fails, except a generated file among the pull request's own files that CI proves regenerates identically at the new head; a changed own diff, or an overlap with the pull request's own files, confined to test-only files as DEC-31 defines them, knowledge records or `.changeset/` release notes, passes | From a5fc8b6d8727ec0dde368faa910c07ccd91f2637 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 20:54:32 -0800 Subject: [PATCH 142/151] docs(ContextMenu): an outside press closes it through the shared watch The record's current-state note still said ContextMenu owns its outside-press listener. Its outside press now goes through the shared outside-press watch, for a mouse and a finger alike. The note now says so: ContextMenu owns its invocation and open state, and it closes on an outside press through that watch, against AST-107 FR8. --- docs/specs/components/ContextMenu/ContextMenu.spec.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index 81e549ef38e4b..358e2cd032506 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -292,8 +292,8 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Current-state impact - **No headless factory (FR10).** No headless context menu ships, so ContextMenu - owns its invocation, open state, and outside-press listener itself, against - `spec:AST-107` FR8. + owns its invocation and open state itself, and it closes on an outside press + through the shared outside-press watch, against `spec:AST-107` FR8. - **Touch grow, handoff, and lift (FR5).** A touch-opened menu keeps the layer's own entrance and exit instead of growing from the finger, the held finger that opened it cannot slide to a row, and a block trigger is not From bb96dd18fe5c8d205d73c69133f4610569f848b9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 21:54:10 -0800 Subject: [PATCH 143/151] docs(changeset): the page scrolls under a popover menu only The touch timeline's note said the page stays free to scroll while the menu is up. A bottom-sheet menu's scrim locks the page's scroll, so the note now says that of a popover menu, as the outside-press note does. --- .changeset/contextmenu-touch-timeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md index 7c458b538e183..3dcdad25e359d 100644 --- a/.changeset/contextmenu-touch-timeline.md +++ b/.changeset/contextmenu-touch-timeline.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. The page stays free to scroll while the menu is up: a touch outside the menu closes it as it begins to pan, or at its lift. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens of a popover menu still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. A popover menu opened this way focuses its first item, and the next touch on the trigger asks for the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. +[feat] ContextMenu opens from a held finger on iOS 26's measured timeline where the primary pointer is coarse. The hold keeps UIKit's measured moments. At 400 ms the press takes the finger: its lift no longer sends a click, and the page cannot scroll under it. The menu opens at 735 ms if the finger is still down, or as soon as it lifts after 400 ms. A finger that lifts before 400 ms, or drifts more than 11.5 px on either axis before the menu opens, gets no menu. While a popover menu is up, the page stays free to scroll: a touch outside the menu closes it as it begins to pan, or at its lift. A menu the hold opens lights no row: the menu itself takes the focus, as in UIKit (keyboard and pointer opens of a popover menu still focus the first item). A second finger cancels the press before 400 ms; after it, the menu still opens. A fine pointer (a mouse) keeps the right-click menu, and a finger there keeps today's 500 ms long press. The touch code loads after the page first paints, so a page's first load does not carry it. Until it loads, nothing takes a finger, and a lift opens no menu. A finger still down at the load starts the hold then, so its menu opens 735 ms later. If the load fails, today's 500 ms long press opens the menu, as does a `contextmenu` event the browser sends for a long press. A popover menu opened this way focuses its first item, and the next touch on the trigger asks for the code again. Pass `presentation="popover"` to keep today's menu: the menu at the pointer, opened by a finger held for 500 ms. @vjeux From 47340043b6f6cf1a2125010d504e42a61071370f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 21:57:21 -0800 Subject: [PATCH 144/151] test(ContextMenu): a narrower viewport that starts a trigger's cut The touch layer read whether the trigger cuts its own text only as it mounted and when the trigger's class changed. A cut that a media query starts after the load then lost its ellipsis under the touch model. The trigger-layouts story gains a trigger that cuts its text only in a narrow viewport, beside a plain box with the same style. The spec loads the touch layer in a wide viewport, narrows it, and compares the pair's pixels. It fails here. --- .../storybook/stories/ContextMenu.stories.tsx | 13 ++++++++- ...tMenuLongPress.interaction.browser.spec.ts | 28 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 9dca8cc8d5d28..c2ab6d6a8aea5 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -810,6 +810,16 @@ const layoutStyles = stylex.create({ height: '120px', backgroundImage: 'linear-gradient(#d1d5db, #374151)', }, + narrowCut: { + padding: '8px', + overflow: 'hidden', + textOverflow: { + default: 'clip', + '@media (max-width: 480px)': 'ellipsis', + }, + whiteSpace: 'nowrap', + backgroundColor: '#f3f4f6', + }, }); /** Triggers that clip, cut, scroll or overflow their content, by name. */ @@ -836,6 +846,7 @@ const CUT_CASES = { ), scroll: () =>
, + narrowCut: () => <>Quarterly report for the whole design team, } as const; const LAYOUTS = ['block', 'row', 'grid'] as const; @@ -860,7 +871,7 @@ export const TouchTriggerLayouts: Story = { docs: { description: { story: - 'The press grows only the trigger’s own visual, an inner box that lays the children out as the trigger would. Each trigger here sits beside a plain box with the same style, and both lay out the same, a set-height trigger with a full-height child too. Below them, triggers that cut their text, clip a header pulled into their padding, clip a child’s ring, cut a multi-line label, let a badge overflow, or scroll draw their content as the plain box does.', + 'The press grows only the trigger’s own visual, an inner box that lays the children out as the trigger would. Each trigger here sits beside a plain box with the same style, and both lay out the same, a set-height trigger with a full-height child too. Below them, triggers that cut their text, clip a header pulled into their padding, clip a child’s ring, cut a multi-line label, let a badge overflow, or scroll draw their content as the plain box does. The last one cuts its text only in a narrow viewport.', }, }, }, diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 3c36239fca75d..8730e79dee9e4 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1231,6 +1231,34 @@ test('once the touch layer loads, a block trigger’s visual is a box, and trigg expect(differing).toEqual([]); }); +test('a trigger that a narrower viewport starts to cut, after the touch layer loads, draws its text as a plain box with the same style does', async ({ + page, +}) => { + await page.setViewportSize({width: 800, height: 900}); + const touchLayerChunk = watchTouchLayer(page); + await openStory(page, storybook(), 'core-contextmenu--touch-trigger-layouts'); + await waitForTouchLayer(page, touchLayerChunk); + const trigger = page.getByTestId('layout-narrowCut'); + const reference = page.getByTestId('layout-narrowCut-reference'); + await page.setViewportSize({width: 360, height: 900}); + expect( + await reference.evaluate(el => getComputedStyle(el).textOverflow), + ).toBe('ellipsis'); + // The layer reads the cut after the resize, and React commits it. + await expect + .poll( + async () => + trigger.evaluate( + el => getComputedStyle(el.firstElementChild as Element).textOverflow, + ), + {timeout: 2000}, + ) + .toBe('ellipsis'); + expect( + (await trigger.screenshot()).equals(await reference.screenshot()), + ).toBe(true); +}); + test.describe('with a mouse', () => { test.use({hasTouch: false, isMobile: false}); From 789a0c7a0c0d092a78a006aaee33dfec2f5222b5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 1 Dec 2026 23:50:14 -0800 Subject: [PATCH 145/151] fix(ContextMenu): read the trigger's cut at each commit and on resize The touch layer read whether the trigger cuts its own text only as it mounted and when the trigger's class changed. A cut that a media or container query or a dynamic style starts later lost its ellipsis under the touch model. The layer now reads it at each commit, when the trigger resizes and when the window resizes; the window's resize comes through core's shared input stream. The read stays in the touch layer, so the first load carries none of it. The visual's comments now say where it is a box: once the touch layer has loaded, for a block trigger whose menu opens at the finger. --- packages/core/src/ContextMenu/ContextMenu.tsx | 9 +-- .../src/ContextMenu/ContextMenuTouchLayer.tsx | 57 +++++++++++++------ 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index a1f0940d26204..f6783705ca97a 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -149,8 +149,9 @@ const styles = stylex.create({ userSelect: 'none', }, // The trigger's own visual, which the press feedback grows. It is a box - // only where the hold can grow it. Elsewhere it is no box, so the trigger - // lays out, clips and cuts its children itself. + // once the touch layer has loaded, for a block trigger whose menu opens at + // the finger. Elsewhere it is no box, so the trigger lays out, clips and + // cuts its children itself. triggerVisualNone: { display: 'contents', }, @@ -1202,8 +1203,8 @@ export function ContextMenu({ // An inline trigger (`span`) lets prose own a context menu without // breaking its flow. const TriggerElement = triggerAs === 'div' ? 'div' : 'span'; - // The hold grows a block trigger whose menu opens at the finger, once the - // touch layer has loaded. + // A block trigger whose menu opens at the finger has a box for its visual + // once the touch layer has loaded, so the hold can grow it. const growsVisual = TouchLayer != null && triggerAs === 'div' && !usesBottomSheet; const SheetForContent = usesSheetActionList diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx index 68afcd89588b5..af1df9c350b61 100644 --- a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx +++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx @@ -15,6 +15,7 @@ */ import { + useCallback, useEffect, useImperativeHandle, useRef, @@ -29,7 +30,9 @@ import {useGestureRecognizer} from '../gestures/useGestureRecognizer'; import {useCommittedRef, useCommittedRefInto} from '../hooks/useCommittedRef'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {contextMenu} from '../motion/uikit/contextMenu'; -import {isElement} from '../utils/nodeType'; +import {subscribeInput} from '../utils/inputStream'; +import {isElement, isNode} from '../utils/nodeType'; +import {observeResize} from '../utils/sharedResizeObserver'; import {ContextMenuPressRecognizer} from './contextMenuPress'; import {useContextMenuPressFeedback} from './contextMenuPressFeedback'; @@ -56,8 +59,8 @@ export interface ContextMenuTouchLayerProps { isShown: boolean; /** * Receives whether the trigger cuts its own text (`text-overflow`), where - * its visual is a box: as the layer mounts, and when the trigger's class - * changes. + * its visual is a box: at each commit, and when the trigger or the viewport + * resizes. */ onTextCut?: (cuts: boolean) => void; /** Receives the layer's handle as it mounts, and null as it unmounts. */ @@ -113,26 +116,46 @@ export function ContextMenuTouchLayer({ isFollowedRef, ); const feedbackRef = useCommittedRef(feedback); - // The trigger's class at the last read of its text-overflow. - const textCutClassRef = useRef(null); - // Syncs with the trigger's computed style: whether it cuts its own text, - // which decides whether its visual clips that text. It reads again only - // when the trigger's class changes. - useIsomorphicLayoutEffect(() => { + // Whether the trigger cuts its own text decides whether its visual clips + // that text. + const onTextCutRef = useCommittedRef(onTextCut); + const readTextCut = useCallback(() => { const trigger = triggerRef.current; - if ( - !isShown || - trigger == null || - onTextCut == null || - trigger.className === textCutClassRef.current - ) { + if (trigger == null) { return; } - textCutClassRef.current = trigger.className; const cut = trigger.ownerDocument.defaultView?.getComputedStyle(trigger).textOverflow; - onTextCut(cut != null && cut !== '' && cut !== 'clip'); + onTextCutRef.current?.(cut != null && cut !== '' && cut !== 'clip'); + }, [triggerRef, onTextCutRef]); + // Syncs with the trigger's computed style at each commit: a class or a + // dynamic style can start or stop the cut. + useIsomorphicLayoutEffect(() => { + if (isShown) { + readTextCut(); + } }); + // Syncs with the trigger's size and the viewport: a container or media + // query can start or stop the cut with no commit. + useEffect(() => { + const trigger = triggerRef.current; + const view = trigger?.ownerDocument.defaultView; + if (!isShown || trigger == null || view == null) { + return; + } + const unobserve = observeResize(trigger, readTextCut); + // Only the window's own resize: a window's own event has no node as its + // target. + const unsubscribe = subscribeInput(view, 'resize', event => { + if (!isNode(event.target)) { + readTextCut(); + } + }); + return () => { + unobserve(); + unsubscribe(); + }; + }, [isShown, triggerRef, readTextCut]); const onCancelRef = useCommittedRef(onCancel); const hasPressOpenedRef = useRef(false); From e642688e02c1d5a21b3bd6a9e5ee4761977a1cf8 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 02:38:03 -0800 Subject: [PATCH 146/151] docs(gestures): the late-input flag's comment gives only the reason The comment on the arena's latest-contact flag opened by restating the field's name. It now says only what the name does not: a late deadline waits for queued input only while the flag is true, and a mouse keeps the one-task yield. --- packages/core/src/gestures/GestureArena.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts index 952dc62af0cd6..7510c384f145c 100644 --- a/packages/core/src/gestures/GestureArena.ts +++ b/packages/core/src/gestures/GestureArena.ts @@ -187,8 +187,8 @@ export class GestureArena { /** The latest input that reached the page late: its own time, and when. */ private lateInput: {time: number; arrivedAt: number} | null = null; /** - * Whether the latest contact is a finger or a pen. Only then does a late - * deadline wait for queued input; a mouse keeps the one-task yield. + * A late deadline waits for queued input only while this is true. A mouse + * keeps the one-task yield. */ private isLatestContactFingerOrPen = false; /** From b9115eedd70fa2f93c69039ccce5d02935320d66 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 02:38:04 -0800 Subject: [PATCH 147/151] docs(gestures): name the arena in the input-samples comment The comment on a touch's input samples said "the arena's clock never runs back, so it holds a late input's time", where "it" reads as the clock. The arena holds that time and filters the samples, and it leaves the input's positions as they came. The comment now names the arena as the subject of each sentence. --- packages/core/src/gestures/types.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts index a0811112afe79..f070a777e1058 100644 --- a/packages/core/src/gestures/types.ts +++ b/packages/core/src/gestures/types.ts @@ -83,9 +83,9 @@ export interface GestureTouch { time: number; /** * The latest event's positions at the times they came with, oldest first, - * ending with the current one. The arena's clock never runs back, so it - * holds a late input's `time` and filters `samples`; it does not change - * these. + * ending with the current one. The arena's clock never runs back, so the + * arena holds a late input's `time` and filters `samples`. The arena leaves + * these positions as they came. */ inputSamples: TouchSample[]; readonly startX: number; From dee55df6adfb1c00419c0521310393f429c5184a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 03:26:21 -0800 Subject: [PATCH 148/151] test(ContextMenu): a finger on a trigger's child inside a shadow root A finger held on a block trigger's child that renders inside an open shadow root opens the menu, but the trigger never grows: the press feedback finds the trigger a landing belongs to with `closest`, which stops at the shadow root. A unit case lands on a control inside a shadow root in the trigger. The touch stories gain a card whose label renders inside an open shadow root, and the long-press spec holds a finger on it and reads the trigger's growth. Both fail here. --- .../storybook/stories/ContextMenu.stories.tsx | 52 ++++++++++++++++++- ...tMenuLongPress.interaction.browser.spec.ts | 23 ++++++++ .../contextMenuPressFeedback.test.tsx | 36 +++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index c2ab6d6a8aea5..b300a9daf184b 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -1,6 +1,6 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. import type {Meta, StoryObj} from '@storybook/react'; -import {useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import { ContextMenu, ContextMenuItem, @@ -692,6 +692,56 @@ export const TouchLongPress: Story = { ), }; +/** + * A label that renders inside an open shadow root, as a web component's does. + * The shadow content fills the host, so a finger on the host lands inside it. + */ +function ShadowLabel() { + const hostRef = useRef(null); + useEffect(() => { + const host = hostRef.current; + if (host == null) { + return; + } + const shadow = host.shadowRoot ?? host.attachShadow({mode: 'open'}); + const label = host.ownerDocument.createElement('div'); + label.style.cssText = + 'display: grid; place-items: center; width: 100%; height: 100%;'; + label.textContent = 'Hold for actions'; + shadow.replaceChildren(label); + }, []); + return ( +
+ ); +} + +export const TouchShadowChild: Story = { + name: 'Touch / child in a shadow root', + parameters: { + docs: { + description: { + story: + 'The card’s label renders inside an open shadow root, as a web component’s does. Where the primary pointer is coarse, a finger held on the label grows the card, as on any other child.', + }, + }, + }, + render: () => ( + {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + ]}> + + + ), +}; + const layoutStyles = stylex.create({ page: { display: 'grid', diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index 8730e79dee9e4..d278b5642bf6a 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1378,6 +1378,29 @@ test('the stays-put check sees a menu that a transform moves after its show', as expect((after?.y ?? NaN) - (before?.y ?? NaN)).toBeCloseTo(8, 0); }); +test('a finger held on a child inside a shadow root grows the trigger, as on any other child', async ({ + page, +}) => { + const {driver, trigger, center} = await openTouchStory( + page, + 'core-contextmenu--touch-shadow-child', + ); + // The finger lands inside the shadow root, not on its host. + const landsInside = await page.evaluate(({x, y}) => { + const host = document.querySelector('[data-testid="shadow-label"]'); + const hit = host?.shadowRoot?.elementFromPoint(x, y); + return hit != null && hit !== host && host?.shadowRoot?.contains(hit); + }, center); + expect(landsInside).toBe(true); + const menu = page.getByRole('menu', {name: 'Photo actions'}); + const playing = driver.play(hold(center, menuDisplayMs + 1500)); + await expect(menu).toBeVisible(); + await untilMenuSettled(page); + const grown = await grownScale(trigger); + await playing; + expect(grown).toBeGreaterThan(1); +}); + test('a drag past the tolerance after the commit opens nothing', async ({ page, }) => { diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx index 799d2b70f217d..592377898b986 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -103,6 +103,30 @@ function TriggerWithControl() { ); } +/** + * A trigger whose content renders inside an open shadow root, with a control + * there, as a web component's does. + */ +function TriggerWithShadowControl() { + const ref = useRef(null); + feedback = useContextMenuPressFeedback(ref, ref, true); + return ( +
+
{ + if (host != null && host.shadowRoot == null) { + const control = host.ownerDocument.createElement('button'); + control.type = 'button'; + control.textContent = 'Open'; + host.attachShadow({mode: 'open'}).append(control); + } + }} + /> +
+ ); +} + const nested: { outer: ContextMenuPressFeedback | null; inner: ContextMenuPressFeedback | null; @@ -189,6 +213,18 @@ describe('useContextMenuPressFeedback', () => { expect(animator.animate).toHaveBeenCalledOnce(); }); + it('grows for a landing on a control inside a shadow root in the trigger', async () => { + const {getByTestId} = render(); + const control = + getByTestId('shadow-host').shadowRoot?.querySelector('button'); + if (control == null) { + throw new Error('no control in the shadow root'); + } + landNow(control); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + }); + it('grows only the outer trigger for a landing on its own control beside a nested trigger', async () => { const {getByTestId} = render(); const control = getByTestId('outer-control'); From 031f8e1fb692094e08f2475fff1800b83560fea4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 03:27:10 -0800 Subject: [PATCH 149/151] fix(ContextMenu): find the trigger out of a shadow root in it The press feedback finds the trigger a landing belongs to with `closest`, which stops at a shadow root. A finger held on a trigger's child inside a shadow root opened the menu, but the trigger never grew. The lookup now goes on from each shadow root's host, open or closed, so the innermost trigger at or above the landing is found. --- .../contextMenuTrigger.stylex.ts | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts index fb57645f753b2..db7326eeb067c 100644 --- a/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts +++ b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts @@ -4,13 +4,16 @@ * @file privateAttributes/contextMenuTrigger.stylex.ts * @input A ContextMenu trigger whose touch press feedback is attached * @output markContextMenuTrigger, which marks the trigger, and - * closestContextMenuTrigger, which finds the trigger at or above an element + * closestContextMenuTrigger, which finds the trigger at or above an element, + * out of shadow roots too * @position Owner module of the private context-menu-trigger attribute: the * only file that writes its name. ContextMenu's press feedback * (ContextMenu/contextMenuPressFeedback.ts) marks its trigger and finds the * trigger a press belongs to. No package entry exports it. */ +import {shadowHostOf} from '../utils/flatTree'; + const CONTEXT_MENU_TRIGGER = 'data-astryx-context-menu-trigger'; /** Marks `trigger` as a ContextMenu trigger. The returned call unmarks it. */ @@ -21,7 +24,21 @@ export function markContextMenuTrigger(trigger: Element): () => void { }; } -/** The ContextMenu trigger at or above `element`, or null outside one. */ +/** + * The ContextMenu trigger at or above `element`, or null outside one. A + * finger can land inside a shadow root in the trigger, where `closest` stops, + * so the search goes on from each shadow root's host. + */ export function closestContextMenuTrigger(element: Element): Element | null { - return element.closest(`[${CONTEXT_MENU_TRIGGER}]`); + for ( + let at: Element | null = element; + at != null; + at = shadowHostOf(at.getRootNode()) + ) { + const trigger = at.closest(`[${CONTEXT_MENU_TRIGGER}]`); + if (trigger != null) { + return trigger; + } + } + return null; } From 063e6eca4ecadbe758bcdb736d72862cf6d8e267 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 05:57:22 -0800 Subject: [PATCH 150/151] test(ContextMenu): a finger on content slotted into a trigger A web component can render a ContextMenu trigger in its shadow root, around a , with its own children slotted into the trigger. A finger held on that slotted content opens the menu, but the trigger never grows: the trigger lookup climbs the slotted content's own parents, outside the shadow root, and so never reaches the trigger. A unit case lands on a control slotted into the trigger. The touch stories gain a web component card whose label is slotted into the trigger, and the long-press spec holds a finger on the label and reads the trigger's growth. Both fail here. --- .../storybook/stories/ContextMenu.stories.tsx | 59 +++++++++++++++++++ ...tMenuLongPress.interaction.browser.spec.ts | 29 +++++++++ .../contextMenuPressFeedback.test.tsx | 35 +++++++++++ 3 files changed, 123 insertions(+) diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index b300a9daf184b..8307f1225657d 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -1,6 +1,7 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. import type {Meta, StoryObj} from '@storybook/react'; import {useEffect, useRef, useState} from 'react'; +import {createRoot} from 'react-dom/client'; import { ContextMenu, ContextMenuItem, @@ -742,6 +743,64 @@ export const TouchShadowChild: Story = { ), }; +/** + * A web component whose open shadow root renders a ContextMenu card around a + * ``: the card's label is the component's own child, slotted into the + * trigger. The page's StyleX sheet does not reach into the shadow root, so the + * card's size is inline. + */ +function SlottedCard() { + const hostRef = useRef(null); + useEffect(() => { + const host = hostRef.current; + if (host == null) { + return; + } + const shadow = host.shadowRoot ?? host.attachShadow({mode: 'open'}); + const container = host.ownerDocument.createElement('div'); + shadow.replaceChildren(container); + const root = createRoot(container); + root.render( + {}}, + {label: 'Share', icon: ShareIcon, onClick: () => {}}, + ]}> +
+ +
+
, + ); + return () => { + root.unmount(); + }; + }, []); + return ( +
+
+ Hold for actions +
+
+ ); +} + +export const TouchSlottedChild: Story = { + name: 'Touch / child slotted into a shadow root', + parameters: { + docs: { + description: { + story: + 'A web component renders the card inside its open shadow root, around a slot. Its own child, the label, is slotted into the card. Where the primary pointer is coarse, a finger held on the label grows the card, as on any other child.', + }, + }, + }, + render: () => , +}; + const layoutStyles = stylex.create({ page: { display: 'grid', diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts index d278b5642bf6a..7793c6a1fe7b4 100644 --- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts +++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts @@ -1401,6 +1401,35 @@ test('a finger held on a child inside a shadow root grows the trigger, as on any expect(grown).toBeGreaterThan(1); }); +test('a finger held on content slotted into a trigger grows the trigger, as on any other child', async ({ + page, +}) => { + const {driver, trigger, center} = await openTouchStory( + page, + 'core-contextmenu--touch-slotted-child', + ); + // The finger lands on the slotted label, which the trigger shows through its + // slot inside the web component's shadow root. + const landsOnLabel = await page.evaluate(({x, y}) => { + const label = document.querySelector('[data-testid="slotted-label"]'); + const hit = document.elementFromPoint(x, y); + return ( + hit != null && + label != null && + label.contains(hit) && + label.assignedSlot != null + ); + }, center); + expect(landsOnLabel).toBe(true); + const menu = page.getByRole('menu', {name: 'Photo actions'}); + const playing = driver.play(hold(center, menuDisplayMs + 1500)); + await expect(menu).toBeVisible(); + await untilMenuSettled(page); + const grown = await grownScale(trigger); + await playing; + expect(grown).toBeGreaterThan(1); +}); + test('a drag past the tolerance after the commit opens nothing', async ({ page, }) => { diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx index 592377898b986..54101bbe606bb 100644 --- a/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx +++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.test.tsx @@ -127,6 +127,20 @@ function TriggerWithShadowControl() { ); } +/** + * A trigger around a ``, as a web component renders one in its shadow + * root: the component's own children are slotted into the trigger. + */ +function SlottedTrigger() { + const ref = useRef(null); + feedback = useContextMenuPressFeedback(ref, ref, true); + return ( +
+ +
+ ); +} + const nested: { outer: ContextMenuPressFeedback | null; inner: ContextMenuPressFeedback | null; @@ -225,6 +239,27 @@ describe('useContextMenuPressFeedback', () => { expect(animator.animate).toHaveBeenCalledOnce(); }); + it('grows for a landing on a control slotted into the trigger from outside its shadow root', async () => { + const host = document.createElement('div'); + const control = document.createElement('button'); + control.type = 'button'; + control.textContent = 'Open'; + host.append(control); + document.body.append(host); + const container = document.createElement('div'); + host.attachShadow({mode: 'open'}).append(container); + const {unmount} = render(, {container}); + try { + expect(control.assignedSlot).not.toBeNull(); + landNow(control); + await flush(); + expect(animator.animate).toHaveBeenCalledOnce(); + } finally { + unmount(); + host.remove(); + } + }); + it('grows only the outer trigger for a landing on its own control beside a nested trigger', async () => { const {getByTestId} = render(); const control = getByTestId('outer-control'); From b337bd9fa3616b56d7f33b18968cb540102d4b86 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 2 Dec 2026 05:58:43 -0800 Subject: [PATCH 151/151] fix(ContextMenu): find the trigger along the flat tree The trigger lookup ran `closest` and then went on from each shadow root's host, so it climbed the parents an element has in its own tree. Content slotted into a trigger has its parents outside the shadow root that holds the trigger, so a finger held on it opened the menu, but the trigger never grew. The lookup now follows the flat tree the browser dispatches through, with core's flat-tree parent: slotted content goes to its slot, and a shadow root to its host. A landing inside a shadow root in the trigger still finds it. --- .../contextMenuTrigger.stylex.ts | 25 ++++++++----------- packages/core/src/utils/flatTree.ts | 5 ++-- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts index db7326eeb067c..4ee45bad2ba24 100644 --- a/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts +++ b/packages/core/src/privateAttributes/contextMenuTrigger.stylex.ts @@ -4,15 +4,16 @@ * @file privateAttributes/contextMenuTrigger.stylex.ts * @input A ContextMenu trigger whose touch press feedback is attached * @output markContextMenuTrigger, which marks the trigger, and - * closestContextMenuTrigger, which finds the trigger at or above an element, - * out of shadow roots too + * closestContextMenuTrigger, which finds the trigger at or above an element + * along the flat tree * @position Owner module of the private context-menu-trigger attribute: the * only file that writes its name. ContextMenu's press feedback * (ContextMenu/contextMenuPressFeedback.ts) marks its trigger and finds the * trigger a press belongs to. No package entry exports it. */ -import {shadowHostOf} from '../utils/flatTree'; +import {parentAcrossShadow} from '../utils/flatTree'; +import {isElement} from '../utils/nodeType'; const CONTEXT_MENU_TRIGGER = 'data-astryx-context-menu-trigger'; @@ -25,19 +26,15 @@ export function markContextMenuTrigger(trigger: Element): () => void { } /** - * The ContextMenu trigger at or above `element`, or null outside one. A - * finger can land inside a shadow root in the trigger, where `closest` stops, - * so the search goes on from each shadow root's host. + * The ContextMenu trigger at or above `element`, or null outside one. The + * search follows the flat tree the browser dispatches through: slotted content + * goes to its slot, and a shadow root to its host. So a landing inside a + * shadow root in the trigger, or on content slotted into it, finds it. */ export function closestContextMenuTrigger(element: Element): Element | null { - for ( - let at: Element | null = element; - at != null; - at = shadowHostOf(at.getRootNode()) - ) { - const trigger = at.closest(`[${CONTEXT_MENU_TRIGGER}]`); - if (trigger != null) { - return trigger; + for (let at: Node | null = element; at != null; at = parentAcrossShadow(at)) { + if (isElement(at) && at.hasAttribute(CONTEXT_MENU_TRIGGER)) { + return at; } } return null; diff --git a/packages/core/src/utils/flatTree.ts b/packages/core/src/utils/flatTree.ts index 2c1cd26e1aaf3..1c11778bafb55 100644 --- a/packages/core/src/utils/flatTree.ts +++ b/packages/core/src/utils/flatTree.ts @@ -8,8 +8,9 @@ * shadowRootsOutward * @position The flat-tree parent the browser scrolls and dispatches * through. The gesture host's native-scroll probe, the outside-press watch, - * the selection lock and the Layer module's input hold share it. The press - * feedback controller uses the selection lock without the gesture system + * the selection lock, the Layer module's input hold and ContextMenu's + * trigger lookup share it. The press feedback controller uses the selection + * lock without the gesture system */ import {isShadowRoot} from './nodeType';