diff --git a/.changeset/build-stylex-cross-file-consts.md b/.changeset/build-stylex-cross-file-consts.md
new file mode 100644
index 0000000000000..736b20da4327d
--- /dev/null
+++ b/.changeset/build-stylex-cross-file-consts.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/build': patch
+---
+
+[fix] `astryxStylex` resolves `defineConsts` values read from another file. With the `{stylexOptions}` form (the one Storybook uses), a file that read only constants from a `.stylex.ts` module lost that import once StyleX compiled it, so the constants never reached the CSS: a constant used as a media-query key failed the build ("Invalid empty selector") and one used as a value shipped as a custom property nothing declares. In either form, a constant defined on the other side of the layer split, or in an Astryx package (compiled with the library class-name prefix) and read from an app file (compiled with its own), stayed unresolved.
+
+@vjeux
diff --git a/.changeset/click-guard.md b/.changeset/click-guard.md
new file mode 100644
index 0000000000000..7376b26fef796
--- /dev/null
+++ b/.changeset/click-guard.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture recognizers and the menu press model share one guard for the browser's click after a gesture that already acted, swallowing it for 400ms or until the next press. Keyboard and assistive-technology clicks (`detail` 0) always pass.
+
+@vjeux
diff --git a/.changeset/contextmenu-context-request.md b/.changeset/contextmenu-context-request.md
new file mode 100644
index 0000000000000..accfc214359f2
--- /dev/null
+++ b/.changeset/contextmenu-context-request.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] ContextMenu is built on `createContextMenu`: it attaches the headless context menu to its own trigger, so the two open, present and dismiss alike. It opens on its trigger's context request (a right click, Shift+F10 or the context-menu key, or a finger's or a pen's hold, once per gesture), and its hold yields to a gesture that has already claimed the finger. `menuContent` still reads the caller's own contexts.
+
+@vjeux
diff --git a/.changeset/contextmenu-glass-morph.md b/.changeset/contextmenu-glass-morph.md
new file mode 100644
index 0000000000000..cb0e131fcc9a6
--- /dev/null
+++ b/.changeset/contextmenu-glass-morph.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Under a finger, on every touch device, when a held finger opens a ContextMenu, the menu now grows out of the finger as iOS 26's does: it starts small at the press point and grows into its place beside the lifted trigger, overshooting slightly, as it fades in. Only its position, scale and opacity move, on the compositor. Under Reduce Motion the menu cross-fades in where it is instead, in 200 ms: nothing moves or grows.
+
+@vjeux
diff --git a/.changeset/contextmenu-headless.md b/.changeset/contextmenu-headless.md
new file mode 100644
index 0000000000000..0b6455b786b59
--- /dev/null
+++ b/.changeset/contextmenu-headless.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `createContextMenu(element, {items | render, label?, isDisabled?, onOpenChange?, presentation?})` attaches ContextMenu's menu to an element already on the page, without React, and returns `{open(at?), close(), destroy()}`. It opens on the element's context request (a held finger or pen, a right click, Shift+F10 or the context-menu key), and the element's markup is untouched, so a list row keeps its list valid. `render(container)` fills the menu with custom content in plain DOM, once, as the menu is attached; its cleanup runs when it is destroyed. Under a finger the menu follows ContextMenu's touch model: UIKit's timeline, the press feedback and, on a block element, the lift. `useContextMenu(ref, options)` is its React wrapper and takes `menuContent` JSX, as ContextMenu does.
+
+@vjeux
diff --git a/.changeset/contextmenu-lift-dismissal.md b/.changeset/contextmenu-lift-dismissal.md
new file mode 100644
index 0000000000000..2430a5105788b
--- /dev/null
+++ b/.changeset/contextmenu-lift-dismissal.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Under a finger, on every touch device, closing a ContextMenu opened by a held finger now follows iOS 26. The menu shrinks back into the finger as it fades, on the layer runtime's exit copy, while the lifted trigger returns to its place and its shadow and the backdrop clear. A close while the menu is still growing (Escape; a tap then is swallowed) shrinks it back from where it is, keeping its motion, with no jump to its full size. Picking an action closes it the same way. A press that lands on the fading backdrop opens nothing and reaches nothing under it, even when it is held past the end of the close. Only position, scale and opacity move, on the compositor. Under Reduce Motion everything fades out where it stands instead, in 200 ms.
+
+@vjeux
diff --git a/.changeset/contextmenu-lift-presentation.md b/.changeset/contextmenu-lift-presentation.md
new file mode 100644
index 0000000000000..25de19d5cf964
--- /dev/null
+++ b/.changeset/contextmenu-lift-presentation.md
@@ -0,0 +1,10 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feat] Under a finger, on every touch device (iOS and Android alike), a ContextMenu opened by a held finger now presents as iOS 26's does. A block trigger itself lifts out of the page, with no copy and with its spot in the page held: it grows on from the press to 26 px larger on its longer side (15% at most), with the theme's high shadow fading in under it, over the theme's overlay, and it stays inside the layer runtime's viewport gutter. A tap on the tint closes the menu; while the lift is still growing, a tap or a drag closes nothing and reaches nothing under it, and the menu finishes opening (keys still work). The menu sits 16 px from the lifted trigger, below it when it fits and above it otherwise, centered on it or flush with the edge it is held against (right-to-left pages included), and fades in, with no row lit until the finger moves onto one. Closing returns the trigger to its place. Under Reduce Motion the animator cross-fades everything in place instead, in 200 ms, as the reduced-motion design record asks: nothing travels or grows. Inline triggers, pointer opens and the bottom sheet are unchanged. A fine pointer keeps today's menu at the cursor.
+
+The tint is the theme's modal overlay (`--color-overlay`).
+
+@vjeux
diff --git a/.changeset/contextmenu-presentation-popover.md b/.changeset/contextmenu-presentation-popover.md
new file mode 100644
index 0000000000000..b5ee8f739742e
--- /dev/null
+++ b/.changeset/contextmenu-presentation-popover.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Under a finger, a ContextMenu whose `presentation` is omitted now opens from a held finger on iOS's timeline (the touch model). Pass `presentation="popover"` to keep today's menu on every device: the menu at the pointer, opened by a finger held for 500 ms (the long press). Where the primary pointer is fine (a mouse or trackpad), a finger keeps that same long press.
+
+@vjeux
diff --git a/.changeset/contextmenu-press-constants.md b/.changeset/contextmenu-press-constants.md
new file mode 100644
index 0000000000000..a598482bd7bc7
--- /dev/null
+++ b/.changeset/contextmenu-press-constants.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[chore] The UIKit constants table gains ContextMenu's touch timeline as measured on iOS 26.2: the press feedback starts at 150 ms, the press commits at 400 ms, and the menu displays at 735 ms. It also records the drift tolerance, and the press feedback's growth, spring and display latency. A closed-form press-feedback curve, checked against UIKit's per-frame presentation, comes with them. ContextMenu's touch timeline uses them.
+
+@vjeux
diff --git a/.changeset/contextmenu-touch-timeline.md b/.changeset/contextmenu-touch-timeline.md
new file mode 100644
index 0000000000000..1d246dacda17d
--- /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, on every touch device (a coarse primary pointer, iOS and Android alike). The trigger starts to grow at 150 ms (the onset of core's one press machine), following UIKit's measured press curve on the compositor, and the hold runs on the trigger's context request with 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. The page stays still while the menu is up, and 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, and Android's own long-press menu no longer opens a second menu. A fine pointer (a mouse) keeps the right-click menu, and UIKit's timeline stays off there.
+
+@vjeux
diff --git a/.changeset/gesture-arena-moving-cancel.md b/.changeset/gesture-arena-moving-cancel.md
new file mode 100644
index 0000000000000..5b7e52cad131a
--- /dev/null
+++ b/.changeset/gesture-arena-moving-cancel.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a gesture that cancels itself on a finger's move (a long press dragged past its tolerance) keeps that finger claimed until it lifts, so the page never takes the drag over midway; a resting finger is still given back when its gesture is cancelled. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-browser-negotiation.md b/.changeset/gesture-browser-negotiation.md
new file mode 100644
index 0000000000000..1930e34496d7e
--- /dev/null
+++ b/.changeset/gesture-browser-negotiation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: touch-action derivation, the native scroll probe and haptics for the gesture system. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-hook-fixes.md b/.changeset/gesture-hook-fixes.md
new file mode 100644
index 0000000000000..87f08a0948e31
--- /dev/null
+++ b/.changeset/gesture-hook-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture hooks call nothing back after unmount; `usePressTracker` brakes with the host by default and keeps one tracker, so an option change or a new ref never drops a press in progress; the recognizer's arena plumbing is `protected`. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-host-fixes.md b/.changeset/gesture-host-fixes.md
new file mode 100644
index 0000000000000..2fc0915c974a6
--- /dev/null
+++ b/.changeset/gesture-host-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: gesture host fixes from review. A page scroll under a still finger keeps the press and its click; watchers and touches nothing can claim get passive listeners only; a claimed pen holds only its own stylus touches; an element's own `touch-action` is never widened; slotted content scrolls with its shadow-tree scroller. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-host-owner.md b/.changeset/gesture-host-owner.md
new file mode 100644
index 0000000000000..9ff3bb2d7aded
--- /dev/null
+++ b/.changeset/gesture-host-owner.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture host becomes the one document-level touch owner: the finger count, touch gates, and a kept press for continuous-tracking controls, whose element gets `touch-action: manipulation` where the pointer is coarse. A scroll lock's page hold and the finger-scroll watch keep their own listeners and ask the host only about the touches it owns. A second finger fails a one-finger pan that has not claimed, so the page can pinch. A scroll-edge pan holds a lone finger from the first move that pulls away from an edge every scroller under it is at, so those moves are cancelled before it begins; with a second finger anywhere on the screen the page keeps its pinch. Where the primary pointer is fine, the host attaches nothing and registers no listener, following the pointer when it changes; a recognizer that reads each event's pointer itself opts out with `perEventPointer`, and a press tracker with it paints a finger's press feedback only, with no control event and no mouse or pen press. A press tracker whose hold acts (a stepper's hold-repeat) can bring a selection lock for its presses, as a recognizer can. Internal, for the touch components that adopt them; not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-host.md b/.changeset/gesture-host.md
new file mode 100644
index 0000000000000..eb9f2fec42db2
--- /dev/null
+++ b/.changeset/gesture-host.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture system's DOM host (claims, click suppression, the browser's takeover, the pointer behind a contact). Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-pan.md b/.changeset/gesture-pan.md
index 12eb02fc42391..908da1b367575 100644
--- a/.changeset/gesture-pan.md
+++ b/.changeset/gesture-pan.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: the pan gesture recognizer, with UIKit's measured hysteresis and velocity filter. Not exported from the package entry point; no component uses it yet.
+[chore] Internal: the pan gesture recognizer, with UIKit's measured hysteresis and velocity filter. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/gesture-press-tracking.md b/.changeset/gesture-press-tracking.md
new file mode 100644
index 0000000000000..1c66836c74243
--- /dev/null
+++ b/.changeset/gesture-press-tracking.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: UIControl press tracking with control and cell profiles and the gesture hooks, with every press painter writing `data-astryx-press` through one internal writer in `utils/pressFeedback.ts`. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-readme.md b/.changeset/gesture-readme.md
new file mode 100644
index 0000000000000..9a6293b811b68
--- /dev/null
+++ b/.changeset/gesture-readme.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture system's README for component authors, with its browser proof in Chromium and WebKit.
+
+@vjeux
diff --git a/.changeset/gesture-recognizer-core.md b/.changeset/gesture-recognizer-core.md
index 0b0bfc389235f..28caef0d5579c 100644
--- a/.changeset/gesture-recognizer-core.md
+++ b/.changeset/gesture-recognizer-core.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: the gesture recognizer core for touch presentations: UIKit's recognizer state machine and the arena that settles which recognizer owns a touch. Not exported from the package entry point; no component uses it yet.
+[chore] Internal: the gesture recognizer core for touch presentations: UIKit's recognizer state machine and the arena that settles which recognizer owns a touch. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/gesture-recognizer-fixes.md b/.changeset/gesture-recognizer-fixes.md
new file mode 100644
index 0000000000000..9e6754a78d733
--- /dev/null
+++ b/.changeset/gesture-recognizer-fixes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: gesture recognizer and arena fixes from review; a pan claims nothing before it begins at 10 pt; one velocity tracker for every gesture (`spec:AST-100`: UIKit's measured blend, a scrolling surface's release through the pan's `scrollVelocity()`, and FR2's release rules). Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-swipe-pinch-rotation-edge-hover.md b/.changeset/gesture-swipe-pinch-rotation-edge-hover.md
new file mode 100644
index 0000000000000..ffeadde679ef5
--- /dev/null
+++ b/.changeset/gesture-swipe-pinch-rotation-edge-hover.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: swipe, pinch, rotation, screen-edge pan and hover gesture recognizers. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gesture-tap-long-press.md b/.changeset/gesture-tap-long-press.md
index 9ef786da65842..f1efef8d29014 100644
--- a/.changeset/gesture-tap-long-press.md
+++ b/.changeset/gesture-tap-long-press.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: tap and long-press gesture recognizers with UIKit's measured thresholds. Not exported from the package entry point; no component uses them yet.
+[chore] Internal: tap and long-press gesture recognizers with UIKit's measured thresholds. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/gesture-watcher.md b/.changeset/gesture-watcher.md
new file mode 100644
index 0000000000000..bec7cd286e49d
--- /dev/null
+++ b/.changeset/gesture-watcher.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a recognizer created with `claimsTouches: false` is a watcher: passive listeners only, simultaneous with every recognizer, and it follows a touch the browser takes for a scroll to the lift. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gestures-context-request.md b/.changeset/gestures-context-request.md
new file mode 100644
index 0000000000000..d8919dcfa02c9
--- /dev/null
+++ b/.changeset/gestures-context-request.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: one shared context request from a long press, a right click, or Shift+F10 and the context-menu key (AST-094 FR43), reporting which input made it, one per gesture. A held finger's hold loses to a claim another gesture already made on that finger, and a control that keeps its press for a hold-repeat keeps its own long press, right click and Shift+F10. A two-stage hold commits, then requests at its request time on the gesture clock, at a lift after the commit when asked to, and cancels if the finger drifts first. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/gestures-every-pointer.md b/.changeset/gestures-every-pointer.md
new file mode 100644
index 0000000000000..87e2940ff80b7
--- /dev/null
+++ b/.changeset/gestures-every-pointer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: gestures attach for every pointer, a mouse, a pen and a finger alike (AST-094 FR43). Under a fine primary pointer an element that uses a gesture keeps one passive `pointerdown` listener (a recognizer that claims a moving finger also keeps its blocking `touchmove`), and the page's listeners last only a press. A right click or a ctrl-click on macOS starts no press. A mouse or pen drag that a recognizer claims takes no text selection from then on, anywhere on the page, and a finger is read once where the browser sends Touch Events without exposing `ontouchstart`. A press tracker takes a mouse press as a press, painting at once with no scroll brake. The screen-edge pan stays off under a mouse, a trackpad and a pen unless its caller allows one, and `perEventPointer` is accepted and does nothing. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/input-stream.md b/.changeset/input-stream.md
new file mode 100644
index 0000000000000..61c8b2d52ed22
--- /dev/null
+++ b/.changeset/input-stream.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] The touch press feedback and the gesture recognizers now listen on the window's capture phase through one shared input stream: one passive listener per event type for both. An app's own capture-phase `stopPropagation` at the document no longer starves them, and a page of pressables registers no listener that can hold a scroll.
+
+@vjeux
diff --git a/.changeset/layer-exit-copy.md b/.changeset/layer-exit-copy.md
new file mode 100644
index 0000000000000..441788643f6d2
--- /dev/null
+++ b/.changeset/layer-exit-copy.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the layer runtime gains one exit copy for touch presentations that animate a popover out: a static, inert copy of the closing popover, shown only in the top layer where the popover was drawn, for the close to play on.
+
+@vjeux
diff --git a/.changeset/layer-input-hold.md b/.changeset/layer-input-hold.md
new file mode 100644
index 0000000000000..89eb007172d37
--- /dev/null
+++ b/.changeset/layer-input-hold.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: one input hold for every layer (`Layer/inputHold`). While a layer presents, a touch, a press or a click anywhere reaches nothing (keys and assistive technology still act, and a pinch still zooms the page); while it dismisses, the same, and the layer's content is inert. The gesture host holds the layer's touches through its touch gates, and `isInputShield` lets a hit test see past a hold's shield. Not exported from the package entry point; ContextMenu's touch lift uses it.
+
+@vjeux
diff --git a/.changeset/lift-module.md b/.changeset/lift-module.md
new file mode 100644
index 0000000000000..de42637a5b97a
--- /dev/null
+++ b/.changeset/lift-module.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: one opt-in lift-from-trigger presentation for touch surfaces. The trigger itself lifts into the top layer above a tinted backdrop; a surface grows out of the press beside it on the shared rect morph and shrinks back into it on the layer runtime's exit copy; the trigger returns to its place. Translate, scale and opacity only; nothing mounted at rest, four elements while lifted. Not exported from the package entry point; ContextMenu's touch lift uses it.
+
+@vjeux
diff --git a/.changeset/long-press-one-source.md b/.changeset/long-press-one-source.md
new file mode 100644
index 0000000000000..00150c46e90f6
--- /dev/null
+++ b/.changeset/long-press-one-source.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useLongPress` (the held finger that opens a menu from its trigger) takes its default duration and tolerance, 500ms and 10px on either axis, from the same source as the long-press gesture recognizer. No behavior changes.
+
+@vjeux
diff --git a/.changeset/menu-trigger-drift.md b/.changeset/menu-trigger-drift.md
new file mode 100644
index 0000000000000..adbf976c7b1d0
--- /dev/null
+++ b/.changeset/menu-trigger-drift.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A finger held on a DropdownMenu trigger may drift up to 13px on each axis and still open the menu where the primary pointer is coarse (phones and tablets), as AST-094 FR29 allows; it cancelled past 10px. Where the primary pointer is fine (a touchscreen laptop, a pen tablet), the trigger keeps its 10px. The trigger reads the pointer when its press starts, so no menu or row observes the pointer query.
+
+@vjeux
diff --git a/.changeset/motion-progress.md b/.changeset/motion-progress.md
new file mode 100644
index 0000000000000..6f5882f7f6e02
--- /dev/null
+++ b/.changeset/motion-progress.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: one progress module for the motion foundation. `progressCurve` gives a spring's progress from 0 to 1 as a closed-form curve, `mapProgress` maps any curve from another (a companion's dim following a sheet, a clamped range), `mapRange` is the clamped linear map they share, and `presentedProgressVelocity` reads the velocity an interrupted motion continues from. One velocity unit throughout: progress per second. Nothing public changes; ContextMenu's touch lift uses it.
+
+@vjeux
diff --git a/.changeset/motion-rect-morph.md b/.changeset/motion-rect-morph.md
new file mode 100644
index 0000000000000..8598e899b7e10
--- /dev/null
+++ b/.changeset/motion-rect-morph.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the rect morph, one way for a touch presentation to grow out of a source rect and shrink back into it. `lerpPath` (a straight line between two rects) and `edgeGrowPath` (UIKit's popover, growing out of a point on its edge) name the rect an element shows at each progress; `morphCurves` turns a path into compositor curves (`translate`, `scale` and a companion `opacity`); `createRectMorph` presents an element along a path and dismisses it back on a copy or on itself, each continuing the other from the rect on screen with its velocity, with Reduced Motion left to the animator. It runs on new progress helpers (`progressCurve`, `mapProgress`, `mapRange`, `presentedProgressVelocity`). Not exported from the package entry point; ContextMenu's touch lift uses it.
+
+@vjeux
diff --git a/.changeset/presentation-resolver.md b/.changeset/presentation-resolver.md
new file mode 100644
index 0000000000000..decee65fa0585
--- /dev/null
+++ b/.changeset/presentation-resolver.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] An internal `usePresentation` / `readPresentation` resolves a component's `presentation` prop into the surface to render and whether its touch input modes apply, keeping an omitted value distinct from an explicit `'popover'` so a caller's choice always wins over a touch default. ContextMenu reads it; its touch behavior has its own entry.
+
+@vjeux
diff --git a/.changeset/presented-hit-testing.md b/.changeset/presented-hit-testing.md
new file mode 100644
index 0000000000000..e27c857277aad
--- /dev/null
+++ b/.changeset/presented-hit-testing.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] On iOS, a touch on an element the compositor animator is moving reaches what is drawn: the animator reports each moving element's offset from its layout box, and the gesture host sends the touch, press bounds and the tap's click there instead of to the layout position iOS WebKit hit-tests.
+
+@vjeux
diff --git a/.changeset/reduced-motion-record.md b/.changeset/reduced-motion-record.md
new file mode 100644
index 0000000000000..2ec44f4c1f9c8
--- /dev/null
+++ b/.changeset/reduced-motion-record.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: Reduce Motion for the touch presentations follows design:reduced-motion beyond the animator too. `reducedMotionFade()` gives code beside the animator the animator's own fade (an opacity-only 200 ms cross-fade on a coarse pointer or after a touch release, at once on any other pointer), `animator.reducedMotion()` reports which form a change takes for feedback that plays no fade of its own, and `reducedMotion.stylex.ts` holds the fade's constants for StyleX transitions. The fade's length is not a theme motion role. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/touch-selection-lock-gestures.md b/.changeset/touch-selection-lock-gestures.md
new file mode 100644
index 0000000000000..d1f3ab7c2b7fc
--- /dev/null
+++ b/.changeset/touch-selection-lock-gestures.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the gesture host applies a recognizer's own `selectionLock` to that recognizer's contact and imports no lock itself; a long press brings one only when it has a hold (a `minimumPressDuration` above 0), and `selectionLock: null` opts out. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/touch-selection-lock.md b/.changeset/touch-selection-lock.md
new file mode 100644
index 0000000000000..e5285afc1f8ad
--- /dev/null
+++ b/.changeset/touch-selection-lock.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Where the primary pointer is fine (a mouse, a trackpad, a touchscreen laptop, a desktop pen tablet), the press feedback controller no longer registers a touch listener: it reads the primary pointer at the first finger or pen press and keeps its `touchcancel` listener only while that pointer is coarse.
+
+@vjeux
diff --git a/.changeset/uikit-constants-table.md b/.changeset/uikit-constants-table.md
index 01fd41a182b0b..2c063cdb50bc7 100644
--- a/.changeset/uikit-constants-table.md
+++ b/.changeset/uikit-constants-table.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: the UIKit constants table for touch presentations (springs, scroll physics, timing curves and navigation values), each value with its source and a checked list of the simulator measurements still owed. Not exported from the package entry point; no component reads it yet.
+[chore] Internal: the UIKit constants table for touch presentations (springs, scroll physics, timing curves and navigation values), each value with its source and a checked list of the simulator measurements still owed. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/uikit-motion-animator-pseudo-element.md b/.changeset/uikit-motion-animator-pseudo-element.md
new file mode 100644
index 0000000000000..7ccb10bab35da
--- /dev/null
+++ b/.changeset/uikit-motion-animator-pseudo-element.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the touch presentations' animator drives a pseudo-element such as a dialog's ::backdrop: a static filling animation holds its value after a curve ends and after `set`, a custom property on its host promotes it, and a Reduce Motion dip borrows and hands back the pseudo-element's own opacity. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/uikit-motion-animator.md b/.changeset/uikit-motion-animator.md
index d489e3022e6db..6b23ce1985186 100644
--- a/.changeset/uikit-motion-animator.md
+++ b/.changeset/uikit-motion-animator.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: a compositor animator for touch presentations. It plays UIKit's springs, and scroll coasts (built by a separate coast module, so a surface that never coasts does not carry them; `decay` plays momentum, and sends a spring back from past an edge through the Reduce Motion policy: a cross-fade on a coarse pointer or after a touch release, at once elsewhere) as Web Animations on translate, rotate, scale and opacity, so they keep running while JavaScript is busy, and reads values and velocities back from the curves for interruption, retargeting and Reduce Motion cross-fades. Not exported from the package entry point; no component uses it yet.
+[chore] Internal: a compositor animator for touch presentations. It plays UIKit's springs, and scroll coasts (built by a separate coast module, so a surface that never coasts does not carry them; `decay` plays momentum, and sends a spring back from past an edge through the Reduce Motion policy: a cross-fade on a coarse pointer or after a touch release, at once elsewhere) as Web Animations on translate, rotate, scale and opacity, so they keep running while JavaScript is busy, and reads values and velocities back from the curves for interruption, retargeting and Reduce Motion cross-fades. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/uikit-motion-math.md b/.changeset/uikit-motion-math.md
index 7af3d73a92a98..cbb9399568857 100644
--- a/.changeset/uikit-motion-math.md
+++ b/.changeset/uikit-motion-math.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: the spring, decay, rubber-band and projection math of UIKit for touch presentations, as pure functions checked against an independent integration and against values read from UIKit. Not exported from the package entry point; no component uses it yet.
+[chore] Internal: the spring, decay, rubber-band and projection math of UIKit for touch presentations, as pure functions checked against an independent integration and against values read from UIKit. Not exported from the package entry point.
@vjeux
diff --git a/.changeset/uikit-motion-use-animator.md b/.changeset/uikit-motion-use-animator.md
new file mode 100644
index 0000000000000..b234a4e987752
--- /dev/null
+++ b/.changeset/uikit-motion-use-animator.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: useAnimator, a React wrapper around the touch presentations' animator that never re-renders per frame, and browser proofs on the interaction harness that the animator's motion keeps running through a blocked main thread in Chromium and WebKit. Not exported from the package entry point.
+
+@vjeux
diff --git a/.changeset/use-finger-scroll.md b/.changeset/use-finger-scroll.md
new file mode 100644
index 0000000000000..e48f0b171df03
--- /dev/null
+++ b/.changeset/use-finger-scroll.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: `useFingerScroll(scroller)` tells a finger's scroll from the program's, and the gestures README gains a guide to migrating a raw-touch drag onto the recognizers. Internal to the touch components: not exported from the package entry point or the gestures barrel.
+
+@vjeux
diff --git a/.changeset/uselongpress-stages.md b/.changeset/uselongpress-stages.md
new file mode 100644
index 0000000000000..117d207af33ba
--- /dev/null
+++ b/.changeset/uselongpress-stages.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] useLongPress takes `stages`: later moments of the same hold, each fired once the finger has stayed that long from the start and still within `moveCancelPx`. `start` also takes the press's start time, so the deadlines can count from a touch's own timestamp.
+
+@vjeux
diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx
index 5c144b8bf45a9..c4e862793418d 100644
--- a/apps/storybook/stories/ContextMenu.stories.tsx
+++ b/apps/storybook/stories/ContextMenu.stories.tsx
@@ -1,12 +1,14 @@
// 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,
ContextMenuCheckboxItem,
ContextMenuRadioGroup,
ContextMenuRadioItem,
+ createContextMenu,
+ useContextMenu,
} from '@astryxdesign/core/ContextMenu';
import {Divider} from '@astryxdesign/core/Divider';
import {
@@ -589,3 +591,172 @@ export const InScrollContainer: 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:
+ 'On a touch screen (iOS or Android), 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. While the menu is up the page stays still, and 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
+
+ ),
+};
+
+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
+
+ ),
+};
+
+const headlessStyles = stylex.create({
+ list: {
+ listStyle: 'none',
+ margin: 0,
+ padding: 0,
+ maxWidth: '320px',
+ },
+ row: {
+ padding: '12px 16px',
+ borderBottomWidth: '1px',
+ borderBottomStyle: 'solid',
+ borderBottomColor: '#e5e7eb',
+ userSelect: 'none',
+ },
+});
+
+/**
+ * Three rows of a list: the second carries a menu from the framework-agnostic
+ * createContextMenu, the third from useContextMenu. The list keeps only `li`
+ * children; the menus render outside it. The log below the list records what
+ * the page saw, for the interaction tests.
+ */
+function HeadlessRows() {
+ const plainRowRef = useRef(null);
+ const hookRowRef = useRef(null);
+ const contentRowRef = useRef(null);
+ const [log, setLog] = useState>([]);
+ const record = (entry: string) => setLog(entries => [...entries, entry]);
+ useEffect(() => {
+ const row = plainRowRef.current;
+ if (row == null) {
+ return;
+ }
+ const menu = createContextMenu(row, {
+ label: 'Inbox actions',
+ onOpenChange: isOpen => record(isOpen ? 'open' : 'close'),
+ items: [
+ {label: 'Archive', onClick: () => record('archive')},
+ {label: 'Delete', variant: 'destructive', onClick: () => {}},
+ ],
+ });
+ return () => menu.destroy();
+ }, []);
+ useContextMenu(hookRowRef, {
+ label: 'Sent actions',
+ items: [{label: 'Forward', onClick: () => record('forward')}],
+ });
+ useContextMenu(contentRowRef, {
+ label: 'Archive actions',
+ menuContent: (
+ record('restore')} />
+ ),
+ });
+ return (
+
+
+
+ Drafts
+
+ record('row-click')}
+ {...stylex.props(headlessStyles.row)}>
+ Inbox
+
+
+ Sent
+
+
+ Archive
+
+
+
{log.join(',')}
+
+ );
+}
+
+export const HeadlessOnAListRow: Story = {
+ name: 'Headless / createContextMenu on a list row',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'createContextMenu attaches ContextMenu to an element that is already on the page, here a list row, without React; useContextMenu does the same from a component. A held finger, a right click, Shift+F10 or the context-menu key opens it.',
+ },
+ },
+ },
+ render: () => ,
+};
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 0fab0e43de33e..5404257cc43cd 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -33,6 +33,8 @@ verified_by:
packages/core/src/Layer/anchorName.test.ts,
packages/core/src/Layer/useLayerDismissal.test.tsx,
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
+ packages/core/src/Layer/layerExitCopy.test.ts,
+ packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts,
packages/core/src/Popover/Popover.test.tsx,
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
packages/core/src/ContextMenu/ContextMenu.test.tsx,
@@ -62,6 +64,7 @@ deciding_specs: [spec:AST-038, spec:AST-059]
"INV7",
"INV11",
"INV12",
+ "INV13",
"INV14",
"INV15"
],
@@ -297,6 +300,25 @@ during a press so native light dismissal does not mistake them for outside
interaction. Their click action is cancelled as an invoker toggle so the control
can perform its own action without closing the layer.
+### Exit copy
+
+The browser hides a popover the moment it closes, whether by a pick, Escape, or
+its own light dismiss. A touch presentation whose close stays on screen plays it
+on an exit copy: a static copy of the layer that `placeLayerExitCopy` takes as
+the layer closes. The copy is laid out on the layer's own box and carries the
+transform and opacity the layer is drawn with, so a copy taken while the layer
+is still entering holds where it was drawn. It carries no ids, form names, or
+form owner; it is `inert`, hidden from assistive technology, and out of pointer
+reach; it keeps the layer's scroll positions. It is shown only in the top layer,
+as a manual popover, so a clipping, transformed, or sticky ancestor neither cuts
+nor moves it; a fixed box or a larger `z-index` is no substitute
+(`spec:AST-027` FR8). Where the browser refuses that show during the closing
+popover's own toggle, the copy waits, hidden, and enters the top layer once the
+toggle is over: after the script that closed the layer, or in the next frame
+before it paints. Where there is no top layer (no popover API), or the browser
+still refuses, there is no copy and the close is immediate. The presentation
+that placed the copy animates it and removes it when its close settles.
+
### Current dismissal plumbing
`family:overlay-dismissal` owns the shipped Escape/platform-close membership
@@ -480,6 +502,12 @@ layers use Layer rendering without joining Escape/platform dismissal.
correct, and the runtime polls nothing: an anchor that a scrolled
container hides is followed again when an intersection observer reports it
back in view.
+- **INV13 — One exit copy per closing layer.** A layer's close plays on at most
+ one exit copy, made by `placeLayerExitCopy`: drawn where the layer was drawn,
+ inert, hidden from assistive technology, without ids, form names, or form
+ owner, shown only in the top layer, and removed by its owner when the close
+ settles. Placing a second copy for the same layer removes the first; another
+ layer's copy stays.
- **INV14 — The runtime owns every layer's shared mechanism.** Internally, the layer runtime owns the shared
mechanism layers use: top-layer mounting, close-request delivery, the
presentation hold (keeping a layer's chosen presentation from the open until
@@ -533,11 +561,13 @@ Current gaps are observable facts, not current target behavior:
migration, verification, and completion criteria for these gaps. This record must
be updated only as that work ships.
-INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them: no
-shared presentation hold, exit copy, runtime backdrop tint, or lift module
-exists, and Dialog, Drawer, BottomSheet, Lightbox, MobileNav, ToastViewport,
-and Selector each build their own top-layer mounting, exit, or backdrop, and
-Popover builds its own presentation hold for its sheet presentation.
+INV14 and INV15 are not met yet, and `spec:AST-003` does not cover them. The
+runtime owns the shared exit copy (INV13, `placeLayerExitCopy`), and the one
+lift-from-trigger module exists (INV15, `packages/core/src/liftFromTrigger/`);
+no shared presentation hold or runtime backdrop tint exists, Dialog, Drawer,
+BottomSheet, Lightbox, MobileNav, ToastViewport, and Selector each build their
+own top-layer mounting, exit, or backdrop, and Popover builds its own
+presentation hold for its sheet presentation.
BottomSheet's own includes its sheet stack's mounting — the re-show that
keeps a document's sheets in open order, a step dialog's modal present, and
the non-modal sheet's popover host — alongside its scrim; the ordering rules
@@ -568,6 +598,12 @@ above are the stack's, the mounting under them is this gap's.
entry/return, and controlled close behavior.
- A browser fallback change updates public `useLayer` and Popover docs and tests
for both the native path and actual fallback.
+- An exit-copy change verifies, where each can be observed: the copy's reach,
+ accessibility and form exclusion in jsdom; its top-layer show (from script
+ and by light dismiss), its place mid-entrance, and that a layer keeps one
+ copy, in jsdom and in Chromium and WebKit; and the refused show's wait in
+ jsdom and on Android Chromium, the engine that refuses a show during another
+ popover's toggle.
## Owning code
@@ -589,6 +625,8 @@ above are the stack's, the mounting under them is this gap's.
transitions of a layer and its content across the re-placement's display
reset.
- `Layer/gestureCounter.ts` owns physical pointer/key gesture identity.
+- `Layer/layerExitCopy.ts` owns the exit copy a touch presentation's close plays
+ on.
- `Layer/layerStack.ts`, `Layer/useLayerDismissal.ts`, and
`Layer/LayerDepthContext.tsx` own current registration, presence, ordering, and
Escape/platform routing.
@@ -638,6 +676,7 @@ this current architecture record.
| INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost |
| INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor |
| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |
+| INV13 | `layerExitCopy.test.ts` and `layerExitCopy.interaction.browser.spec.ts` | A copy with an id, a form name, a form owner, or pointer reach; a copy off the layer's drawn box; a copy outside the top layer; a second copy for one layer |
| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |
diff --git a/docs/specs/AST-057-row-actions/spec.md b/docs/specs/AST-057-row-actions/spec.md
index 2b3f6c57495e1..4c1ed5a60d229 100644
--- a/docs/specs/AST-057-row-actions/spec.md
+++ b/docs/specs/AST-057-row-actions/spec.md
@@ -131,10 +131,11 @@ and its panels stay put, so no element is added to any row.
- **A render prop for a custom panel.** Deferred, not foreclosed: a
`render*`-shaped addition can land when a caller needs something the
vocabulary cannot say (DEC-1).
-- **Gesture tuning.** Axis-lock distance, commit ratio, fling velocity, slide
- and spring durations, resistance past the panel: behavior constants in
- source, not public API and not design tokens (the same ruling the touch
- press model received for its clocks).
+- **Gesture tuning.** Axis-lock distance, commit ratio, fling velocity,
+ resistance past the panel: behavior constants in source, not public API and
+ not design tokens (the same ruling the touch press model received for its
+ clocks). The row's slide and spring motion plays on theme motion roles
+ (`spec:AST-094` FR4).
- **Vertical swipes**, and a swipe whose only
meaning is dismissal (Toast already has that in `useToastGesture`).
- **Public out-of-flow slots on `Item`.** Deliberately not admitted: the
@@ -219,9 +220,10 @@ and its panels stay put, so no element is added to any row.
| open state | closed, resting open | The row's own. A pointer landing anywhere outside a resting row closes it, which is also how a drag on a neighbour closes it; no group state exists. | closed | `spec:AST-057` | proposed |
| the modality split | internal | A mouse drag never starts the swipe; a finger's or a pen's pointer event or a horizontal wheel gesture does, read from the input event, not a prop or a media query (`architecture:interaction-modality` INV6). | — | `spec:AST-057` | proposed |
-Not public: axis-lock distance, commit ratio, fling velocity, durations,
-resistance, panel widths, the custom property's name. They are behavior
-constants.
+Not public: axis-lock distance, commit ratio, fling velocity, resistance,
+panel widths, the custom property's name. They are behavior constants. The
+row's slide and spring motion plays on theme motion roles (`spec:AST-094`
+FR4).
## Requirements
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 9c0995b96a26d..842ac3b9bc27b 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -130,25 +130,28 @@ a measured, sourced difference exists.
wherever the native motion settles with an overshoot or stretches with a
rubber band.
- | Role | Default | Source |
- | -------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------- |
- | `springs.fingerTracking` | response 0.15 s, damping ratio 0.86 | Apple: SwiftUI `interactiveSpring()` |
- | `springs.emphasis` | duration 0.5 s, bounce 0.3 | Apple: SwiftUI `.bouncy` |
- | `springs.settle` | duration 0.5 s, bounce 0 | Apple: SwiftUI `.smooth` |
- | `springs.quickChange` | duration 0.5 s, bounce 0.15 | Apple: SwiftUI `.snappy` |
- | `springs.viewChange` | mass 3, stiffness 1000, damping 500 | measured: UIKit `UISpringTimingParameters()`, iOS 26.2 simulator, 2026-10-23 |
- | `springs.timedChange` | duration 0.5 s, bounce 0 | Apple: UIKit `UIView.animate(springDuration:bounce:)` |
- | `springs.stateChange` | response 0.55 s, damping ratio 1 | Apple: SwiftUI `Animation.default` |
- | `springs.directChange` | response 0.5 s, damping ratio 0.825 | Apple: SwiftUI `.spring(response:dampingFraction:)` |
- | `springs.menuOpen` | damping ratio 0.8, response 0.32 s | measured: UIMenu opening, iOS 26.2 simulator, 2026-10-23 |
- | `springs.menuClose` | damping ratio 0.85, response 0.35 s | measured: UIMenu closing, iOS 26.2 simulator, 2026-10-23 |
- | `springs.subMenuOpen` | damping ratio 0.85, response 0.4 s | measured: UIKit's own spring for UIMenu's sub-menu opening, iOS 26.2 simulator, 2026-10-24 |
- | `springs.subMenuBack` | damping ratio 1, response 0.4 s | measured: UIKit's own spring for UIMenu's sub-menu header back, iOS 26.2 simulator, 2026-10-24 |
- | `timing.stateChangeMs` | 250 ms | measured: Core Animation's implicit transaction, iOS 26.2 simulator, 2026-10-23 |
- | `timing.curves.viewChange` | cubic-bezier(0.25, 0.1, 0.25, 1) | Apple: `CAMediaTimingFunctionName.default` |
- | `timing.curves.exit` | cubic-bezier(0.42, 0, 1, 1) | measured: UIKit's ease-in, iOS 26.2 simulator, 2026-10-23 |
- | `timing.curves.entrance` | cubic-bezier(0, 0, 0.58, 1) | measured: UIKit's ease-out, iOS 26.2 simulator, 2026-10-23 |
- | `timing.curves.move` | cubic-bezier(0.42, 0, 0.58, 1) | measured: UIKit's ease-in-out, iOS 26.2 simulator, 2026-10-23 |
+ | Role | Default | Source |
+ | ---------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
+ | `springs.fingerTracking` | response 0.15 s, damping ratio 0.86 | Apple: SwiftUI `interactiveSpring()` |
+ | `springs.emphasis` | duration 0.5 s, bounce 0.3 | Apple: SwiftUI `.bouncy` |
+ | `springs.settle` | duration 0.5 s, bounce 0 | Apple: SwiftUI `.smooth` |
+ | `springs.quickChange` | duration 0.5 s, bounce 0.15 | Apple: SwiftUI `.snappy` |
+ | `springs.viewChange` | mass 3, stiffness 1000, damping 500 | measured: UIKit `UISpringTimingParameters()`, iOS 26.2 simulator, 2026-10-23 |
+ | `springs.timedChange` | duration 0.5 s, bounce 0 | Apple: UIKit `UIView.animate(springDuration:bounce:)` |
+ | `springs.stateChange` | response 0.55 s, damping ratio 1 | Apple: SwiftUI `Animation.default` |
+ | `springs.directChange` | response 0.5 s, damping ratio 0.825 | Apple: SwiftUI `.spring(response:dampingFraction:)` |
+ | `springs.menuOpen` | damping ratio 0.8, response 0.32 s | measured: UIMenu opening, iOS 26.2 simulator, 2026-10-23 |
+ | `springs.menuClose` | damping ratio 0.85, response 0.35 s | measured: UIMenu closing, iOS 26.2 simulator, 2026-10-23 |
+ | `springs.subMenuOpen` | damping ratio 0.85, response 0.4 s | measured: UIKit's own spring for UIMenu's sub-menu opening, iOS 26.2 simulator, 2026-10-24 |
+ | `springs.subMenuBack` | damping ratio 1, response 0.4 s | measured: UIKit's own spring for UIMenu's sub-menu header back, iOS 26.2 simulator, 2026-10-24 |
+ | `springs.contextMenuLift` | damping ratio 0.8, response 0.32 s | measured: UIContextMenuInteraction's preview lift, iOS 26.2 simulator, 2026-10-23 |
+ | `springs.contextMenuDismiss` | damping ratio 0.85, response 0.35 s | measured: UIContextMenuInteraction's dismissal, iOS 26.2 simulator, 2026-10-23 |
+ | `springs.contextMenuMorph` | damping ratio 0.8, response 0.3 s | measured: UIContextMenuInteraction's menu entrance and preview shadow, iOS 26.2 simulator, 2026-10-23 |
+ | `timing.stateChangeMs` | 250 ms | measured: Core Animation's implicit transaction, iOS 26.2 simulator, 2026-10-23 |
+ | `timing.curves.viewChange` | cubic-bezier(0.25, 0.1, 0.25, 1) | Apple: `CAMediaTimingFunctionName.default` |
+ | `timing.curves.exit` | cubic-bezier(0.42, 0, 1, 1) | measured: UIKit's ease-in, iOS 26.2 simulator, 2026-10-23 |
+ | `timing.curves.entrance` | cubic-bezier(0, 0, 0.58, 1) | measured: UIKit's ease-out, iOS 26.2 simulator, 2026-10-23 |
+ | `timing.curves.move` | cubic-bezier(0.42, 0, 0.58, 1) | measured: UIKit's ease-in-out, iOS 26.2 simulator, 2026-10-23 |
### Motion
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index 31c5149c2d407..27e054e9beb71 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -1,20 +1,24 @@
# @astryxdesign/interaction-harness
Playwright instruments for touch interaction and animation proofs: real touch
-input, curve sampling and storyboards. **Internal and unpublished.** Specs live
-next to their component as `*.interaction.browser.spec.ts` and run under
+input, frame evidence, curve sampling and storyboards. **Internal and
+unpublished.** Specs live next to their component as
+`*.interaction.browser.spec.ts` and run under
[`playwright.interaction.config.ts`](../../playwright.interaction.config.ts) on
a phone-sized touch screen (402 × 714 CSS px page, 402 × 874 screen, 3 device
pixels per CSS px, touch, mobile viewport rules), in Chromium and WebKit.
The harness proves its own instruments in
-[`src/harness.interaction.browser.spec.ts`](src/harness.interaction.browser.spec.ts),
-on fixture pages written inline.
+[`src/harness.interaction.browser.spec.ts`](src/harness.interaction.browser.spec.ts).
+The busy-main-thread proof and the rendering-trace counts have a negative
+control beside their positive checks (a rAF animation that freezes under a
+blocked main thread, a `top` animation that lays out every frame); other
+self-tests check an instrument against a known answer.
## Running
```sh
-pnpm storybook:build # component specs read stories from the built Storybook
+pnpm storybook:build # the specs read stories from the built Storybook
pnpm exec playwright install chromium webkit
pnpm test:interaction --project chromium # everything, Chromium
pnpm test:interaction # one spec, both engines
@@ -31,6 +35,12 @@ under a rootful docker daemon the container runs as your user so its
node internal/interaction-harness/scripts/webkit-container.mjs [playwright test args…]
```
+WebKit composites through Mesa's software GL there, which compiles each shader
+the first time a page draws it (450–700 ms for the first frame of a blurred or
+newly animated layer). The script keeps Mesa's shader cache on the host
+(`~/.cache/astryx-webkit-shaders/`, or `ASTRYX_WEBKIT_SHADER_CACHE`), so
+only the first run on a machine pays for them.
+
Evidence (storyboards, curve traces) is written to
`test-results/interaction-evidence/` (override with
`ASTRYX_INTERACTION_EVIDENCE`) and attached to the test report. It is never
@@ -38,15 +48,18 @@ committed: a pull request links or attaches it.
## Instruments
-| Module | What it gives a spec |
-| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `scripts.ts` | Touch scripts as data: `tap`, `drag` (hold, rest), `flick` (exact final-move speed, velocity profiles), `holdThenDrag`, `pinch`, `rotate`, `path`, `merge` (a second finger mid-gesture), `releaseVelocity`, `toTouchEvents`. |
-| `touch.ts` | `touchDriver(page).play(script)`: the script as real engine input. `installInputLog` / `readInputLog`: what the page received. |
-| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`. |
-| `math.ts` | Oracles independent of the code under test: `cubicBezier`, `timingFunction`, `springStep` (SwiftUI response / dampingFraction, initial velocity), `projectDecay`, `rubberBand`, `parseTransform`, `compareCurve`, `timeline`. |
-| `storyboard.ts` | `animationStoryboard` (seek to t = 0, 16.7, 33.3 … ms), `touchStoryboard` (a frame per scripted event): PNG contact sheet + JSON trace. |
-| `output.ts` | `evidenceDir`, `writeEvidence`: where evidence goes and how it is attached to the report. |
-| `story.ts` | `phone`, `withStorybook`, `openStory`, `frames`, and the timer gate (`installTimerGate`, `freezeTimers`, `thawTimers`). |
+| Module | What it gives a spec |
+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `scripts.ts` | Touch scripts as data: `tap`, `drag` (hold, rest), `flick` (exact final-move speed, velocity profiles), `holdThenDrag`, `pinch`, `rotate`, `path`, `merge` (a second finger mid-gesture), `releaseVelocity`, `toTouchEvents`. |
+| `touch.ts` | `touchDriver(page).play(script)`: the script as real engine input. `installInputLog` / `readInputLog`: what the page received. |
+| `frames.ts` | `startScreencast` (timestamped composited frames), `markElement` (a marker chip or outline), `trackMarker` (marker box per frame), `sampleRects` (per-rAF rects), `frameStats`. |
+| `busy.ts` | `blockMainThread(page, ms)` and `busyWindowProof(tracked, window)`: frames presented, frames that moved, longest stall, a verdict; `presented` adds the compositor's own frames. |
+| `trace.ts` | `traceRendering(page, body)`: main-thread counts of UpdateLayoutTree / Layout / PrePaint / Paint / Layerize / UpdateLayer / ScrollLayer / HitTest, `countBetween`, long tasks; `installLongTaskLog` / `readLongTasks`; `startCompositorTrace`: when the compositor presents. |
+| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`. |
+| `math.ts` | Oracles independent of the code under test: `cubicBezier`, `timingFunction`, `springStep` (SwiftUI response / dampingFraction, initial velocity), `projectDecay`, `rubberBand`, `parseTransform`, `compareCurve`, `timeline`. |
+| `storyboard.ts` | `animationStoryboard` (seek to t = 0, 16.7, 33.3 … ms), `touchStoryboard` (a frame per scripted event), `castStoryboard` (real screencast frames): PNG contact sheet + JSON trace. |
+| `output.ts` | `evidenceDir`, `writeEvidence`: where evidence goes and how it is attached to the report. |
+| `story.ts` | `phone`, `withStorybook`, `openStory`, `frames`, and the timer gate (`installTimerGate`, `freezeTimers`, `thawTimers`). |
## The proofs
@@ -60,6 +73,14 @@ dispatch latency, and the events go through the compositor's gesture detection
the limits below. Read positions a frame after a move: Chromium delivers
`pointermove` aligned to animation frames.
+**Stories, not Storybook.** `openStory` turns Storybook's highlight module off
+on every page it opens, and checks that its root element is absent. Left on,
+the module observes `#storybook-root` and, on every insertion, reads the
+computed style of every element on the page inside the inserting task (117
+reads and two forced style recalculations for one exit copy in a Button story),
+so a proof would measure Storybook as well as the component.
+`openStory(page, origin, id, args, {storybookHighlight: true})` keeps it on.
+
**Curve sampling.** Pause every running animation (CSS transitions and
animations are Web Animations too), seek to a time, read `getComputedStyle`:
the presented value at that exact time, independent of frame timing. Finished
@@ -97,6 +118,109 @@ set): a short entrance no longer races the first look on a cold page. When the
action may be the page's first contact with the harness, take
`watchAnimations(locator)` before it and read `watch.started()` after.
+**Busy main thread.** Mark the element, start the screencast, start the
+animation, wait until it runs (`waitForAnimation`: an animation cannot start
+while the thread is held), block the main thread for 1 s (`spec:AST-094`
+FR5's verification row), stop. Always
+start the gesture or animation first and block mid-flight, never before:
+in headless Chromium a touch that starts while the main thread is busy does
+not scroll or start a gesture even with only passive listeners (the input
+waits for the main thread). Tracking a finger under a busy main thread is
+therefore proven on the iOS simulator, not here. The
+screencast is captured off the main thread, so a compositor animation shows a
+new position every frame of the block, and a main-thread animation shows none
+(nothing changed, so no frame is sent at all: `busyWindowProof` counts the
+whole window as one stall). `settledWithin` (2 px) stops judging at the easing
+tail: the screencast rounds to whole pixels, so a tail that still moves shows
+plateaus within a pixel or two of rest. A judged part shorter than four of the
+screencast's intervals fails: the animation under test was not moving during
+the block. With
+`during`, `blockMainThread` starts the loop from a task queued in the frame
+that saw the animation, after that frame's rendering update: WebKit hands a
+newly started animation to its compositor there, and a loop inside the rAF
+callback would freeze even a compositor animation. Call it before the release
+that starts a settle and await it after, so the page is already waiting when
+the settle begins. An animation counts once it is no longer pending and has
+run at least one frame: a `minProgressMs` under 16 is raised to 16, since one
+created in the frame the page looks is not on the compositor yet. The `verdict` judges the
+frames the screencast delivered, whatever its rate (a loaded machine's can
+deliver one frame in five or six), and tolerates nothing a frozen animation
+does: at least one frame in the judged part, no stall longer than three of the
+screencast's intervals (two dropped frames), and at least 90% of the frames it
+delivered in the judged part presenting a new position (one miss is always
+allowed; a frame it did not deliver is a gap, for the stall check, unless
+it delivered fewer than four frames there: then the judged part's span counts
+every frame, so one late frame is not "1 of 1 moved"). Pass
+`maxMedianFrameMs` (20 at 60 Hz) only in a proof that claims display rate.
+`verdict.failures` names each miss with its numbers, and `summary` carries the
+raw numbers for the report. Frames are judged in presentation order: a loaded
+machine can deliver them out of order. `castStoryboard` turns the frames of the
+block into a filmstrip.
+
+A just-started animation can reach the screen after the block began (50–100 ms
+later in WebKit on a loaded machine). When the cast saw the element at rest
+before the block (wait for `cast.frameCount()` to pass 0 before starting the
+animation), judging starts at its first presented change: the judged part still
+ends with the block and still needs four intervals, and `onScreenFromMs` and the
+summary report when it came. An element already moving is judged from the
+block's start. WebKit's casts are 2 px quantized: the frames come at the
+viewport's size, but the page in them is captured at half resolution, so
+positions move in 2 CSS px steps (Chromium's in 1). With under two steps of
+motion per frame, a frame delivered a few ms early shows no step and reads as
+not moved. The proof reports `stepPx` and `pxPerFrame` and notes motion under
+two steps per frame, which never fails it. Move a proof's element at least two
+steps a frame: the self-tests move 560 px in 1,600 ms, about 4.8 px a frame.
+
+On a loaded machine Chromium's screencast can skip frames the compositor
+still presents. `startCompositorTrace(page)`, started with the screencast and
+stopped after the block, records when the compositor presented each frame
+(`Display::FrameDisplayed`); pass it as `presented`. The record is
+browser-wide (its frames carry no page identity), so it throws when another
+page is open as it starts or stops, or opened while it ran. A gap between two moved
+frames with nothing delivered inside it is then measured between the
+compositor's own frames: the frames it presented there count as presented
+(`recorderSkipped`, in the summary), and a gap it did not present through is
+a stall as before. A gap that opens or closes the judged part, or holds a
+delivered frame that did not move, is judged from the screencast, so a
+frozen element fails whatever else the compositor draws (a rAF animation's
+block presents no compositor frame at all). With the record, the 90% counts the
+compositor's frames from the first to the last moved frame; the gaps before and
+after are the stall check's. WebKit has no such trace:
+`stop()` resolves to `[]` and the screencast is judged alone.
+
+**No Layout / Paint.** `traceRendering` records a Chromium trace around the
+interaction; `countBetween` counts the steady middle of an animation (its
+first and last frames may commit). A transform/opacity animation does no
+Layout or Paint there; a layout-property animation does one per frame. The
+harness's own animation recorder stands down while the trace runs, since its
+frame loop would make every frame a main-thread one, restyling each running
+animation's target and laying out an anchored one: it reads only the element a
+CSS animation or transition event names, once, when that animation starts, and
+catches up afterwards. A `waitForRest` awaited inside the traced body stands
+down too: it waits on timers for the scheduled ends of the element's curves
+(looking `frames` times a frame apart before settling on none, so an
+animation the action starts a frame or two later is waited for) and polls no
+style until the trace ends (in the anchored fixture's steady middle,
+24 Layouts before, 0 now). Its one read of the element's animations, as it is
+called, restyles the element (2 Layouts and 2 style recalculations in the
+anchored fixture when called 200 ms into its animation), so await it right
+after the action that starts the motion, before the window a proof counts. So do `waitForAnimation` and a watch's
+`started()`: they take the element's animations from the recorder's log,
+judge a started one by its own times, and reach the element through a handle,
+since each `locator.evaluate` makes a main-thread frame (there too, 24
+Layouts before, 0 now). That holds for script animations and CSS
+transitions. On a CSS `@keyframes` animation (and, unwatched, a cancelled CSS
+transition), `waitForAnimation` and `started()` read the animation's timing,
+which flushes its style and adds Layouts to the trace: wait on one with
+`waitForRest`, or after the trace. Taking a watch (`watchAnimations`) inside
+a trace reads the watched element's animations, which restyles it (and lays
+out an anchored one), so a proof takes its traced watch before the window it
+counts. The trace's `longTasks` are the page's own: only a
+task the harness marked as its own read (`waitForAnimation` describing
+keyframes, `blockMainThread` without `during`) is in `devtoolsTasks` instead,
+and only when no page script ran inside it. A test's own `page.evaluate` stays a
+long task, whether it calls page code directly or sets it off.
+
**Storyboards.** Deterministic: frames come from seeking held animations or
from stepping scripted input, never from wall-clock capture. The JSON trace
carries each frame's measurements and the spec asserts on it; the sheet is
@@ -104,16 +228,18 @@ evidence. A component that finishes an animation from a timer (a transitionend
backstop, a cleanup render) would do so behind a held storyboard's back:
`installTimerGate` before the animation starts and `freezeTimers` while
photographing. The page can still cancel a held callback, a held frame callback
-gets the time it actually runs, and the harness's own frame waits are not held.
+gets the time it actually runs, and the harness's own waits (its frame waits,
+`blockMainThread` with `during`, `sampleRects`) are not held.
An animation that repeats forever does not set a storyboard's default length;
with nothing else to film, pass `times`. A touch filmstrip keeps the scripted
event `timeStamp`s (Chromium), but a handler that reads `performance.now()` or
`Date.now()` sees one event per photograph, about 100 ms apart, so a
clock-timed release flings slower when filmed than when played: a storyboard
-cannot show such a gesture; record it in real time instead. Chromium can return
-an empty copy of the page's surface right after it changes ("Unable to capture
-screenshot"); a storyboard takes that photograph again two frames later, up to
-three attempts in all, and lists each retake under `recaptures` in the trace.
+cannot show such a gesture; record it in real time instead, with
+`startScreencast` and `castStoryboard`. Chromium can return an empty copy of
+the page's surface right after it changes ("Unable to capture screenshot"); a
+storyboard takes that photograph again two frames later, up to three attempts
+in all, and lists each retake under `recaptures` in the trace.
## Engine limits (measured with Playwright 1.61)
@@ -126,11 +252,15 @@ three attempts in all, and lists each retake under `recaptures` in the trace.
| Lifting one finger while others stay down | yes | pointer events right, but that `touchend` lists no remaining `touches`: skip with `PARTIAL_LIFT_SKIP` |
| Click synthesised from a touch | yes | only from `driver.tap` (WebKit's tap gesture), not from a raw touch sequence |
| Curve sampling, storyboards, input log | yes | yes |
+| Screencast frame evidence (busy main thread) | yes | yes (WebKit's own screencast; frames keep coming while the main thread is blocked) |
+| Rendering trace, long tasks | yes | no (Playwright exposes neither) |
+| Compositor presentation record | yes | no: `stop()` resolves to `[]`; the busy verdict judges the screencast alone |
What WebKit cannot show here — native scroll hand-off, flings, a finger
-lifting while another stays down, and anything iOS-only — needs Mobile Safari
-itself, on a device or the iOS simulator. Skip such a proof on the driver's
-flag, citing the reason: `test.skip(!driver.partialLifts, PARTIAL_LIFT_SKIP)`.
+lifting while another stays down, finger tracking under a busy main thread, and
+anything iOS-only — needs Mobile Safari itself, on a device or the iOS
+simulator. Skip such a proof on the driver's flag, citing the reason:
+`test.skip(!driver.partialLifts, PARTIAL_LIFT_SKIP)`.
The WebKit input command is reached through Playwright's in-process server
object, so it needs a locally launched browser (the default), not `connect()`.
diff --git a/internal/interaction-harness/package.json b/internal/interaction-harness/package.json
index 40cccb26ca206..942eccb9ed8d5 100644
--- a/internal/interaction-harness/package.json
+++ b/internal/interaction-harness/package.json
@@ -3,7 +3,7 @@
"version": "0.0.0",
"private": true,
"type": "module",
- "description": "Internal: Playwright helpers for touch interaction and animation proofs (real touch input, curve sampling, storyboards). Never published.",
+ "description": "Internal: Playwright helpers for touch interaction and animation proofs (real touch input, frame evidence, curve sampling, storyboards). Never published.",
"main": "./src/index.ts",
"exports": {
".": "./src/index.ts",
diff --git a/internal/interaction-harness/scripts/webkit-container.mjs b/internal/interaction-harness/scripts/webkit-container.mjs
index cb20fd44aa725..a077eae415ed5 100644
--- a/internal/interaction-harness/scripts/webkit-container.mjs
+++ b/internal/interaction-harness/scripts/webkit-container.mjs
@@ -16,10 +16,19 @@
* docker daemon the container runs as the invoking user (rootless podman and
* rootless docker already map it), so the `test-results/` it writes into the
* mounted checkout stay the host user's and the next host run can clear them.
+ *
+ * WebKit composites through Mesa's software GL in the image, which compiles
+ * each shader variant the first time a page draws it: 450–700 ms for the
+ * first frame of a blurred or newly animated layer, long enough for a short
+ * animation to end before it is ever presented. Mesa caches what it compiles,
+ * and the cache is kept on the host (`~/.cache/astryx-webkit-shaders/`,
+ * or `ASTRYX_WEBKIT_SHADER_CACHE`), so a run starts with every shader an
+ * earlier run compiled instead of paying for them in its first tests.
*/
import {spawnSync} from 'node:child_process';
import fs from 'node:fs';
import {createRequire} from 'node:module';
+import os from 'node:os';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
@@ -42,6 +51,21 @@ if (engine == null) {
process.exit(1);
}
const args = process.argv.slice(2);
+// Where the container sees the host's shader cache (see the header).
+const containerShaderCache = '/astryx-shader-cache';
+// Resolved to an absolute path: a bare relative value would be mounted as a
+// named volume rather than a host directory. An empty value means the default.
+const shaderCache = process.env.ASTRYX_WEBKIT_SHADER_CACHE
+ ? path.resolve(process.env.ASTRYX_WEBKIT_SHADER_CACHE)
+ : path.join(
+ os.homedir(),
+ '.cache',
+ 'astryx-webkit-shaders',
+ image.replace(/[^\w.-]+/g, '_'),
+ );
+fs.mkdirSync(shaderCache, {recursive: true});
+// The harness self-test reads this marker inside the container.
+fs.writeFileSync(path.join(shaderCache, 'ASTRYX-SHADER-CACHE'), `${image}\n`);
const env = [
'ASTRYX_STORYBOOK_DIR',
'ASTRYX_INTERACTION_EVIDENCE',
@@ -79,6 +103,10 @@ const command = [
'--ipc=host',
'-v',
`${root}:${root}`,
+ '-v',
+ `${shaderCache}:${containerShaderCache}`,
+ '-e',
+ `MESA_SHADER_CACHE_DIR=${containerShaderCache}`,
'-w',
root,
...env,
diff --git a/internal/interaction-harness/src/busy.skip.fixture.ts b/internal/interaction-harness/src/busy.skip.fixture.ts
new file mode 100644
index 0000000000000..409886f12e6f8
--- /dev/null
+++ b/internal/interaction-harness/src/busy.skip.fixture.ts
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file busy.skip.fixture.ts
+ * @input One recorded busy-main-thread run in headless Chromium under
+ * parallel load: a compositor coast through a 566 ms block
+ * @output `frames`: the screencast frames the marker was tracked in, as
+ * [ms after the block started, y in CSS px, or null where the marker was not
+ * found]; `presented`: when the compositor presented each frame
+ * (`Display::FrameDisplayed`), ms after the block started; `block`: the
+ * block's span on the same clock. The screencast skipped frames at about
+ * +366 and +466 ms while the compositor kept presenting every 16.7 ms.
+ * @position Fixture for busy.test.ts
+ */
+
+export const block = {from: 0, to: 566.1};
+
+export const frames: ReadonlyArray = [
+ [-1145.8, null],
+ [-1114, null],
+ [-1063.9, null],
+ [-1031.1, null],
+ [-996.6, null],
+ [-964.3, null],
+ [-930.7, null],
+ [-896.7, null],
+ [-864, null],
+ [-830.6, null],
+ [-797.8, null],
+ [-762.7, null],
+ [-731.3, null],
+ [-686.5, null],
+ [-680.8, null],
+ [-651, null],
+ [-634.1, null],
+ [-620.7, null],
+ [-615.8, null],
+ [-514.4, null],
+ [-495, null],
+ [-472.4, null],
+ [-465.3, null],
+ [-448.5, null],
+ [-430.3, null],
+ [-414.8, null],
+ [-398.3, null],
+ [-379.5, null],
+ [-364.2, null],
+ [-348.3, null],
+ [-330.6, null],
+ [-315, null],
+ [-297.6, null],
+ [-281.9, null],
+ [-265.1, null],
+ [-247.6, null],
+ [-230.8, null],
+ [-215.3, null],
+ [-198.6, null],
+ [-181, null],
+ [-165.3, null],
+ [-147.7, null],
+ [-132, null],
+ [-115.4, null],
+ [-98.5, null],
+ [-81.2, 504],
+ [-65.2, 500],
+ [-48.5, 496],
+ [-30.9, 491],
+ [-15.2, 487],
+ [1.3, 484],
+ [32.8, 480],
+ [49.8, 476],
+ [66.3, 473],
+ [82.8, 469],
+ [99.7, 466],
+ [116.1, 463],
+ [132.9, 460],
+ [149.5, 457],
+ [166.3, 454],
+ [182.9, 451],
+ [199.4, 448],
+ [216.2, 446],
+ [232.8, 443],
+ [249.4, 441],
+ [266.1, 438],
+ [282.7, 436],
+ [299.5, 434],
+ [316, 432],
+ [332.7, 430],
+ [349.5, 428],
+ [366.1, 426],
+ [433.1, 418],
+ [449.7, 417],
+ [466.2, 415],
+ [516.2, 411],
+ [532.8, 409],
+ [549.5, 408],
+ [566.2, 407],
+ [650.6, 401],
+ [666.2, 400],
+ [682.9, 399],
+ [699.6, 398],
+ [716.3, 397],
+ [816.1, 391],
+ [832.8, 391],
+ [849.5, 390],
+ [866.2, 389],
+ [882.9, 388],
+ [899.5, 388],
+ [916.1, 387],
+ [1033.8, 383],
+ [1050.1, 383],
+ [1066.7, 382],
+ [1083.3, 382],
+ [1099.5, 381],
+ [1117.3, 381],
+ [1134.2, 380],
+ [1149.5, 380],
+];
+
+export const presented: readonly number[] = [
+ -98.7, -81.3, -65.3, -48.7, -31.1, -15.3, 1.3, 32.5, 49.6, 66.1, 82.7, 99.6,
+ 115.9, 132.6, 149.3, 166.1, 182.6, 199.3, 216, 232.6, 249.3, 266, 282.6,
+ 299.2, 315.8, 332.6, 349.3, 366, 381.5, 398.3, 415.1, 432.9, 449.6, 466.1,
+ 481.5, 498.3, 516, 532.6, 549.4, 566.1, 581.7, 598.4, 615, 631.6, 650.3, 666,
+];
diff --git a/internal/interaction-harness/src/busy.test.ts b/internal/interaction-harness/src/busy.test.ts
new file mode 100644
index 0000000000000..44a2446ecca18
--- /dev/null
+++ b/internal/interaction-harness/src/busy.test.ts
@@ -0,0 +1,536 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file busy.test.ts
+ * @input Synthetic tracked frames (no browser)
+ * @output The busy-main-thread verdict's limits: dropped frames a loaded
+ * machine produces pass, a frozen animation fails every criterion, a window
+ * with nothing moving to judge fails, and out-of-order frames are judged in
+ * presentation order.
+ * @position Unit test of ./busy and ./frames' ordering; the browser proof
+ * with a real compositor animation and a rAF control is in
+ * harness.interaction.browser.spec.ts.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {busyWindowProof} from './busy';
+import * as skip from './busy.skip.fixture';
+import {inPresentationOrder, type TrackedFrame} from './frames';
+
+const FRAME = 1000 / 60;
+const BLOCK = {from: 1000, to: 1700};
+
+/** A marker moving 3 px per frame from t = 800 to 1900, minus `dropped` frame indices. */
+function moving(dropped: readonly number[] = []): TrackedFrame[] {
+ const frames: TrackedFrame[] = [];
+ for (let i = 0; 800 + i * FRAME <= 1900; i += 1) {
+ if (dropped.includes(i)) {
+ continue;
+ }
+ frames.push({
+ t: 800 + i * FRAME,
+ box: {x: 0, y: 3 * i, width: 10, height: 10},
+ } as TrackedFrame);
+ }
+ return frames;
+}
+
+/** Index of the first frame at or after `t`. */
+const at = (t: number) => Math.ceil((t - 800) / FRAME);
+
+/** `moving()` with each frame in `repeats` presenting the previous frame's position. */
+function repeating(repeats: readonly number[]): TrackedFrame[] {
+ return moving().map((f, i) =>
+ repeats.includes(i)
+ ? ({...f, box: {...f.box!, y: 3 * (i - 1)}} as TrackedFrame)
+ : f,
+ );
+}
+
+/** A marker moving 3 px per frame from t = 800 to 1900, frames `intervals` apart in turn. */
+function cadenced(intervals: readonly number[]): TrackedFrame[] {
+ const frames: TrackedFrame[] = [];
+ for (let i = 0, t = 800; t <= 1900; i += 1) {
+ frames.push({
+ t,
+ box: {x: 0, y: 3 * i, width: 10, height: 10},
+ } as TrackedFrame);
+ t += intervals[i % intervals.length];
+ }
+ return frames;
+}
+
+describe('busyWindowProof verdict', () => {
+ it('passes a compositor animation with every frame', () => {
+ const proof = busyWindowProof(moving(), BLOCK);
+ expect(proof.verdict.failures).toEqual([]);
+ expect(proof.longestStallFrames).toBe(1);
+ });
+
+ it('passes one and two consecutive dropped frames (3 intervals)', () => {
+ const k = at(1300);
+ expect(busyWindowProof(moving([k]), BLOCK).verdict.failures).toEqual([]);
+ const two = busyWindowProof(moving([k, k + 1]), BLOCK);
+ expect(two.longestStallFrames).toBe(3);
+ expect(two.verdict.failures).toEqual([]);
+ });
+
+ it('fails three consecutive dropped frames', () => {
+ const k = at(1300);
+ const proof = busyWindowProof(moving([k, k + 1, k + 2]), BLOCK);
+ expect(proof.longestStallFrames).toBe(4);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('fails when more than 10% of the delivered frames do not move', () => {
+ const k = at(1050);
+ // 39 frames delivered: up to 3 may show no new position (10% = 3.9).
+ const scattered = [0, 12, 24].map(d => k + d);
+ expect(
+ busyWindowProof(repeating(scattered), BLOCK).verdict.failures,
+ ).toEqual([]);
+ const many = [0, 6, 12, 18, 24].map(d => k + d);
+ expect(
+ busyWindowProof(repeating(many), BLOCK).verdict.failures.join('\n'),
+ ).toMatch(/expected frames moved/);
+ });
+
+ it('judges a frame the screencast did not deliver as a gap for the stall check, not a miss', () => {
+ // The same five frames, not delivered: two-interval gaps, and every
+ // delivered frame moved.
+ const k = at(1050);
+ const many = [0, 6, 12, 18, 24].map(d => k + d);
+ const proof = busyWindowProof(moving(many), BLOCK);
+ expect(proof.verdict.failures).toEqual([]);
+ expect(proof.deliveredFrames).toBe(proof.moved);
+ });
+
+ it('judges an irregular cast on the frames it delivered', () => {
+ // A cast cycling 11.7, 11.7 and 17 ms: its median interval would expect
+ // 56 frames where it delivered 49, every one moved.
+ const proof = busyWindowProof(cadenced([11.7, 11.7, 17]), BLOCK);
+ expect(proof.verdict.failures).toEqual([]);
+ expect(proof.deliveredFrames).toBe(49);
+ expect(proof.moved).toBe(49);
+ // Still a stall where it delivers nothing for four frames, and still a
+ // miss where five delivered frames show no new position.
+ const gap = cadenced([11.7, 11.7, 17]).filter(
+ f => f.t < 1300 || f.t > 1360,
+ );
+ expect(busyWindowProof(gap, BLOCK).verdict.failures.join('\n')).toMatch(
+ /longest stall/,
+ );
+ const unmoved = cadenced([11.7, 11.7, 17]).map((f, i, all) =>
+ [20, 26, 32, 38, 44].includes(i)
+ ? ({...f, box: {...all[i - 1].box!}} as TrackedFrame)
+ : f,
+ );
+ expect(busyWindowProof(unmoved, BLOCK).verdict.failures.join('\n')).toMatch(
+ /expected frames moved/,
+ );
+ });
+
+ it('judges a window that delivered fewer than four frames against its span', () => {
+ // A rAF animation frozen by the block, in WebKit: one frame from before
+ // the block arrives 45 ms into it, then nothing until after it.
+ const late = moving().filter(f => f.t <= 1000 || f.t >= 1750);
+ late.push({
+ t: 1045,
+ box: {x: 0, y: 3 * at(1001), width: 10, height: 10},
+ } as TrackedFrame);
+ const proof = busyWindowProof(inPresentationOrder(late), BLOCK);
+ expect(proof.verdict.failures.join('\n')).toMatch(/expected frames moved/);
+ });
+
+ it('lets a short window miss a frame, not three', () => {
+ // 150 ms judged: nine frames delivered, one miss allowed (10% would be 0.9).
+ const short = {from: 1000, to: 1190};
+ const k = at(1040);
+ expect(busyWindowProof(repeating([k]), short).verdict.failures).toEqual([]);
+ expect(
+ busyWindowProof(
+ repeating([k, k + 3, k + 6]),
+ short,
+ ).verdict.failures.join('\n'),
+ ).toMatch(/expected frames moved/);
+ });
+
+ it('fails a frozen animation on every criterion', () => {
+ // Frames before and after the block only: nothing changed during it.
+ const frozen = moving().filter(f => f.t < BLOCK.from || f.t > BLOCK.to);
+ const proof = busyWindowProof(frozen, BLOCK);
+ expect(proof.changed).toBe(0);
+ expect(proof.verdict.pass).toBe(false);
+ expect(proof.verdict.failures.join('\n')).toMatch(/no frame presented/);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ expect(proof.verdict.failures.join('\n')).toMatch(/expected frames moved/);
+ });
+
+ it('fails a window in which the animation under test was not moving', () => {
+ // Settled before the block: the judgment ends where it starts.
+ const settled = moving().map(f =>
+ f.t < 950
+ ? f
+ : ({...f, box: {...f.box!, y: 3 * at(950)}} as TrackedFrame),
+ );
+ const before = busyWindowProof(settled, BLOCK, {settledWithin: 2});
+ expect(before.verdict.pass).toBe(false);
+ expect(before.verdict.failures.join('\n')).toMatch(
+ /judged = -?\d+ frames < 4: the animation under test was not moving/,
+ );
+ // Settled 40 ms into the block: two frames, too few to judge.
+ const early = moving().map(f =>
+ f.t < 1040
+ ? f
+ : ({...f, box: {...f.box!, y: 3 * at(1040)}} as TrackedFrame),
+ );
+ expect(
+ busyWindowProof(early, BLOCK, {settledWithin: 2}).verdict.failures.join(
+ '\n',
+ ),
+ ).toMatch(/frames < 4: the animation under test was not moving/);
+ });
+
+ it('judges the frames a slower screencast delivers by default, and display rate only when asked', () => {
+ // One frame in six, as a loaded machine's screencast delivers: every
+ // delivered frame moved, so the default verdict passes.
+ const sixth = moving().filter((_, i) => i % 6 === 0);
+ expect(busyWindowProof(sixth, BLOCK).verdict.failures).toEqual([]);
+ // Half rate fails only a proof that claims display rate.
+ const odd = moving().filter((_, i) => i % 2 === 1);
+ expect(busyWindowProof(odd, BLOCK).verdict.pass).toBe(true);
+ expect(
+ busyWindowProof(odd, BLOCK, {maxMedianFrameMs: 20}).verdict.failures.join(
+ '\n',
+ ),
+ ).toMatch(/median frame interval/);
+ });
+});
+
+describe('busyWindowProof settledWithin', () => {
+ it('ends the judgment at a rounded easing tail, which would read as a stall', () => {
+ // An ease-out to y = 24 as the screencast reports it: whole pixels, so the
+ // tail repeats values while it still moves.
+ const ys = [
+ 120, 100, 82, 67, 55, 46, 39, 34, 30, 28, 27, 26, 26, 26, 25, 25, 24, 24,
+ 24, 24,
+ ];
+ const frames = ys.map(
+ (y, i) =>
+ ({
+ t: 1000 + i * FRAME,
+ box: {x: 0, y, width: 10, height: 10},
+ }) as TrackedFrame,
+ );
+ const window = {from: 1000, to: 1000 + ys.length * FRAME};
+ const loose = busyWindowProof(frames, window, {
+ settledWithin: 2,
+ marginMs: 0,
+ });
+ expect(loose.verdict.failures).toEqual([]);
+ const strict = busyWindowProof(frames, window, {
+ settledWithin: 1,
+ marginMs: 0,
+ });
+ expect(strict.longestStallFrames).toBeGreaterThanOrEqual(3);
+ });
+
+ it('takes the end value from settledAt over a stale last frame', () => {
+ // The tail reaches y = 24, then the last frame shows a stale 100 (WebKit
+ // presents the last committed position once an accelerated animation
+ // ends while the main thread is still blocked).
+ const ys = [
+ 120, 100, 82, 67, 55, 46, 39, 34, 30, 28, 27, 26, 25, 24, 24, 24, 100,
+ ];
+ const frames = ys.map(
+ (y, i) =>
+ ({
+ t: 1000 + i * FRAME,
+ box: {x: 0, y, width: 10, height: 10},
+ }) as TrackedFrame,
+ );
+ const window = {from: 1000, to: 1000 + ys.length * FRAME};
+ const stale = busyWindowProof(frames, window, {
+ settledWithin: 2,
+ marginMs: 0,
+ });
+ expect(stale.verdict.pass).toBe(false);
+ const fromPage = busyWindowProof(frames, window, {
+ settledWithin: 2,
+ settledAt: 24,
+ marginMs: 0,
+ });
+ expect(fromPage.verdict.failures).toEqual([]);
+ expect(fromPage.judged.to).toBe(frames[11].t);
+ });
+});
+
+/** Seen at rest at t = 900, then on screen from `start`, moving 3 px a frame. */
+function startingAt(start: number): TrackedFrame[] {
+ const frames = [
+ {t: 900, box: {x: 0, y: 0, width: 10, height: 10}} as TrackedFrame,
+ ];
+ for (let i = 1; start + (i - 1) * FRAME <= 1900; i += 1) {
+ frames.push({
+ t: start + (i - 1) * FRAME,
+ box: {x: 0, y: 3 * i, width: 10, height: 10},
+ } as TrackedFrame);
+ }
+ return frames;
+}
+
+describe('busyWindowProof on-screen start', () => {
+ it('judges a just-started animation from its first presented change when it was seen at rest before the block, and reports when', () => {
+ // On screen 87 ms into the block: four intervals after the judged part's start.
+ const proof = busyWindowProof(startingAt(1087), BLOCK);
+ expect(proof.verdict.failures).toEqual([]);
+ expect(proof.onScreenFromMs).toBeCloseTo(87, 5);
+ expect(proof.judged.from).toBeCloseTo(1087, 5);
+ expect(proof.summary).toMatch(
+ /on screen from \+87 ms \(nothing moved before the block\)/,
+ );
+ });
+
+ it('still fails an animation that was already moving and stalls at the block start', () => {
+ const k = at(1020);
+ const proof = busyWindowProof(moving([k, k + 1, k + 2, k + 3]), BLOCK);
+ expect(proof.onScreenFromMs).toBeNull();
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('still fails a stall at the start when no frame before the block shows it at rest', () => {
+ const unseen = startingAt(1087).filter(f => f.t >= BLOCK.from);
+ const proof = busyWindowProof(unseen, BLOCK);
+ expect(proof.onScreenFromMs).toBeNull();
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('still fails a start the block itself delays until it ends', () => {
+ const proof = busyWindowProof(startingAt(1720), BLOCK);
+ expect(proof.onScreenFromMs).toBeNull();
+ expect(proof.verdict.failures.join('\n')).toMatch(/no frame presented/);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('still fails a start that leaves fewer than minJudgedFrames inside the block', () => {
+ const proof = busyWindowProof(startingAt(1640), BLOCK);
+ expect(proof.onScreenFromMs).toBeCloseTo(640, 5);
+ expect(proof.verdict.failures.join('\n')).toMatch(
+ /frames < 4: the animation under test was not moving/,
+ );
+ });
+});
+
+describe('busyWindowProof position step', () => {
+ it("reports the cast's position step and motion per frame, and notes motion under two steps without failing", () => {
+ // 2.4 px a frame on a 2 px grid, as WebKit's casts report positions.
+ const grid = moving().map(
+ (f, i) =>
+ ({
+ ...f,
+ box: {...f.box!, y: 2 * Math.round((2.4 * i) / 2)},
+ }) as TrackedFrame,
+ );
+ const coarse = busyWindowProof(grid, BLOCK);
+ expect(coarse.stepPx).toBe(2);
+ expect(coarse.pxPerFrame).toBeCloseTo(2.4, 1);
+ expect(coarse.notes.join('\n')).toMatch(
+ /under two of the cast's 2 px position steps/,
+ );
+ expect(coarse.summary).toMatch(/2\.4 px\/frame in 2 px steps; note: /);
+ expect(coarse.verdict.failures).toEqual([]);
+ // 3 px a frame in whole pixels: resolvable, nothing to note.
+ const fine = busyWindowProof(moving(), BLOCK);
+ expect(fine.stepPx).toBe(1);
+ expect(fine.pxPerFrame).toBeCloseTo(3, 1);
+ expect(fine.notes).toEqual([]);
+ });
+});
+
+/** The compositor presenting every frame from `from` to `to`, minus `gaps` ([from, to] spans). */
+function drawn(
+ gaps: ReadonlyArray = [],
+ from = 700,
+ to = 2000,
+): number[] {
+ const draws: number[] = [];
+ for (let t = from; t <= to; t += FRAME) {
+ if (!gaps.some(([a, b]) => t > a && t < b)) {
+ draws.push(t);
+ }
+ }
+ return draws;
+}
+
+const skipFrames = (): TrackedFrame[] =>
+ skip.frames.map(
+ ([t, y]) =>
+ ({
+ t,
+ box: y == null ? null : {x: 0, y, width: 10, height: 10},
+ }) as TrackedFrame,
+ );
+
+describe('busyWindowProof with the compositor record', () => {
+ it('with a compositor record, judges a sparse cast from its first to its last moved frame', () => {
+ // One screencast frame in six, as on a loaded machine, with the compositor
+ // presenting every frame: the frames before the first and after the last
+ // moved one are the stall check's, not misses.
+ const sparse = moving().filter((_, i) => i % 6 === 0);
+ expect(
+ busyWindowProof(sparse, BLOCK, {presented: drawn()}).verdict.failures,
+ ).toEqual([]);
+ });
+
+ it('with a compositor record and an on-screen start, counts the frames it credits as skipped in what it judges', () => {
+ // On screen 87 ms into the block, then four delivered frames that show
+ // no new position: that fails on a full cast.
+ const misses = [15, 20, 25, 30];
+ const missing = startingAt(1087).map((f, i, all) =>
+ misses.includes(i)
+ ? ({...f, box: {...all[i - 1].box!}} as TrackedFrame)
+ : f,
+ );
+ const full = busyWindowProof(missing, BLOCK, {presented: drawn()});
+ expect(full.verdict.failures.join('\n')).toMatch(/expected frames moved/);
+ // The screencast skipping the five frames after the on-screen frame
+ // changes nothing: the compositor presented them, and they are judged.
+ const skip = (frames: TrackedFrame[]) =>
+ frames.filter((_, i) => i < 2 || i > 6);
+ const skipped = busyWindowProof(skip(missing), BLOCK, {
+ presented: drawn(),
+ });
+ expect(skipped.recorderSkipped).toBe(5);
+ expect(skipped.verdict.failures.join('\n')).toMatch(
+ /expected frames moved/,
+ );
+ // And a run with no misses never reads as more than every frame moved.
+ const clean = busyWindowProof(skip(startingAt(1087)), BLOCK, {
+ presented: drawn(),
+ });
+ expect(clean.verdict.failures).toEqual([]);
+ expect(clean.movedFraction).toBeLessThanOrEqual(1);
+ });
+
+ it('reads frames the screencast skipped while the compositor presented them as presented: a recorded run that fails without the record', () => {
+ const frames = skipFrames();
+ const alone = busyWindowProof(frames, skip.block, {settledWithin: 1});
+ expect(alone.verdict.failures.join('\n')).toMatch(
+ /longest stall 6\d\.\d ms = 4 intervals > 3/,
+ );
+ // Every frame the screencast delivered moved: only the stall remains,
+ // which the record resolves.
+ expect(alone.verdict.failures.join('\n')).not.toMatch(
+ /expected frames moved/,
+ );
+ const proof = busyWindowProof(frames, skip.block, {
+ settledWithin: 1,
+ presented: skip.presented,
+ });
+ expect(proof.verdict.failures).toEqual([]);
+ expect(proof.recorderSkipped).toBe(5);
+ expect(proof.longestStallFrames).toBeLessThanOrEqual(2);
+ expect(proof.summary).toMatch(
+ /the screencast skipped 5 frames the compositor presented \(at \+3\d\d ms, \+4\d\d ms\)/,
+ );
+ });
+
+ it('counts a gap the compositor drew through as skipped, and one it did not draw through as a stall', () => {
+ const k = at(1300);
+ const gap: [number, number] = [
+ 800 + (k - 1) * FRAME,
+ 800 + (k + 4) * FRAME,
+ ];
+ const frames = moving([k, k + 1, k + 2, k + 3]);
+ expect(busyWindowProof(frames, BLOCK).verdict.pass).toBe(false);
+ const skipped = busyWindowProof(frames, BLOCK, {presented: drawn()});
+ expect(skipped.verdict.failures).toEqual([]);
+ expect(skipped.recorderSkipped).toBe(4);
+ const stalled = busyWindowProof(frames, BLOCK, {presented: drawn([gap])});
+ expect(stalled.recorderSkipped).toBe(0);
+ expect(stalled.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('still fails an element that does not move while the compositor presents for something else', () => {
+ const frozen = moving().map(f =>
+ f.t >= BLOCK.from && f.t <= BLOCK.to
+ ? ({...f, box: {...f.box!, y: 3 * at(BLOCK.from)}} as TrackedFrame)
+ : f,
+ );
+ const proof = busyWindowProof(frozen, BLOCK, {presented: drawn()});
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ expect(proof.verdict.failures.join('\n')).toMatch(/expected frames moved/);
+ });
+
+ it('still fails a frozen animation, whether or not the compositor presents during the block', () => {
+ const frozen = moving().filter(f => f.t < BLOCK.from || f.t > BLOCK.to);
+ for (const presented of [drawn([[BLOCK.from, BLOCK.to]]), drawn()]) {
+ const proof = busyWindowProof(frozen, BLOCK, {presented});
+ expect(proof.verdict.failures.join('\n')).toMatch(/no frame presented/);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ }
+ });
+
+ it('keeps a gap a stall when the screencast delivered a frame inside it that did not move', () => {
+ const k = at(1300);
+ const frames = moving([k, k + 1, k + 3]).map(f =>
+ f.t > 800 + (k + 1.5) * FRAME && f.t < 800 + (k + 2.5) * FRAME
+ ? ({...f, box: {...f.box!, y: 3 * (k - 1)}} as TrackedFrame)
+ : f,
+ );
+ const proof = busyWindowProof(frames, BLOCK, {presented: drawn()});
+ expect(proof.recorderSkipped).toBe(0);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('still counts single dropped frames the compositor did not present as missed', () => {
+ const k = at(1050);
+ const drops = [0, 6, 12, 18, 24, 30].map(d => k + d);
+ const frames = moving(drops);
+ const gaps = drops.map(
+ i =>
+ [800 + (i - 0.5) * FRAME, 800 + (i + 0.5) * FRAME] as [number, number],
+ );
+ expect(
+ busyWindowProof(frames, BLOCK, {
+ presented: drawn(gaps),
+ }).verdict.failures.join('\n'),
+ ).toMatch(/expected frames moved/);
+ expect(
+ busyWindowProof(frames, BLOCK, {presented: drawn()}).verdict.failures,
+ ).toEqual([]);
+ });
+
+ it('judges a gap at the edge of the judged part from the screencast alone', () => {
+ // Nothing delivered for the block's first 90 ms: a stall at its start,
+ // whatever the compositor drew, since no moved frame opens the gap.
+ const frames = moving().filter(
+ f => f.t < BLOCK.from || f.t > BLOCK.from + 90,
+ );
+ const proof = busyWindowProof(frames, BLOCK, {presented: drawn()});
+ expect(proof.recorderSkipped).toBe(0);
+ expect(proof.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ it('treats an empty record as no record, and says so', () => {
+ const frames = moving([at(1300), at(1300) + 1, at(1300) + 2, at(1300) + 3]);
+ const proof = busyWindowProof(frames, BLOCK, {presented: []});
+ expect(proof.verdict.failures).toEqual(
+ busyWindowProof(frames, BLOCK).verdict.failures,
+ );
+ expect(proof.summary).toMatch(/no compositor frames recorded/);
+ });
+});
+
+describe('inPresentationOrder', () => {
+ it('sorts frames delivered out of order, so motion stays monotonic', () => {
+ const frames = moving();
+ const k = at(1040);
+ const shuffled = [...frames];
+ [shuffled[k], shuffled[k + 1]] = [shuffled[k + 1], shuffled[k]];
+ expect(busyWindowProof(shuffled, BLOCK).monotonic).toBe(false);
+ const proof = busyWindowProof(inPresentationOrder(shuffled), BLOCK);
+ expect(proof.monotonic).toBe(true);
+ expect(proof.verdict.failures).toEqual([]);
+ });
+});
diff --git a/internal/interaction-harness/src/busy.ts b/internal/interaction-harness/src/busy.ts
new file mode 100644
index 0000000000000..55fd9d670d52a
--- /dev/null
+++ b/internal/interaction-harness/src/busy.ts
@@ -0,0 +1,579 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file busy.ts
+ * @input Uses a Playwright `Page`
+ * @output `blockMainThread` — a synchronous busy loop on the page's main thread
+ * that reports exactly when it ran — and `busyWindowProof`, which reads frame
+ * evidence for that window.
+ * @position The busy-main-thread proof: an animation that runs on the
+ * compositor keeps advancing at display rate while JavaScript holds the main
+ * thread; one driven from the main thread (rAF, style writes, layout
+ * properties) freezes for the whole block. Pair it with ./frames
+ * (`startScreencast` + `trackMarker`), which observes off the main thread.
+ *
+ * SYNC: Keep the README's busy-main-thread section equal to this contract.
+ */
+
+import type {Locator, Page} from '@playwright/test';
+import {frameStats, type FrameStats, type TrackedFrame} from './frames';
+
+export interface BusyWindow {
+ /** Epoch ms when the loop started and ended, on the page's own clock. */
+ readonly from: number;
+ readonly to: number;
+}
+
+/**
+ * Holds the page's main thread for `ms` (a synchronous loop: no task, frame,
+ * rAF, event or microtask runs meanwhile). Resolves with the window it held.
+ *
+ * Block MID-FLIGHT only: start the gesture or animation first. A touch that
+ * starts while the main thread is busy does not scroll or begin a gesture in
+ * headless Chromium, even with only passive listeners, and an animation that
+ * has not started cannot start (see `waitForAnimation`). Finger tracking
+ * under a busy main thread is a simulator proof, not a Playwright one.
+ *
+ * With `during`, the page itself waits until an animation on that element (or
+ * inside it) has run `minProgressMs`, then blocks from a task it queues in
+ * that frame. A round trip from the test would start the block later the
+ * busier the machine is, leaving less of a short animation to judge. The task
+ * runs after the frame's rendering update, which is where WebKit hands a newly
+ * started animation to its compositor: a loop inside the rAF callback itself
+ * holds that hand-off, and even a compositor animation freezes. To catch a
+ * settle near its start, call it before the release that starts the settle and
+ * await it after: the page is already waiting when the animation begins. Any
+ * animation inside `during` counts, so pick an element that runs nothing
+ * else meanwhile.
+ *
+ * An animation counts once it is no longer pending and has run at least one
+ * frame (`minProgressMs` below 16 ms is raised to 16). One created in the
+ * frame the page looks is still pending, not yet on the compositor
+ * (Chromium), and in WebKit its start time resolves before its layer is
+ * flushed: a block that started on it froze it.
+ */
+/** One display frame, ms: the least progress `blockMainThread` waits for. */
+const ONE_FRAME_MS = 16;
+
+export async function blockMainThread(
+ page: Page,
+ ms: number,
+ {
+ during,
+ minProgressMs = 16,
+ timeout = 5_000,
+ }: {during?: Locator; minProgressMs?: number; timeout?: number} = {},
+): Promise {
+ const minProgress = Math.max(minProgressMs, ONE_FRAME_MS);
+ if (during == null) {
+ return page.evaluate(duration => {
+ // The harness's own work: a trace sets it apart (trace.ts HARNESS_READ).
+ console.timeStamp('harness-read');
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + duration;
+ let spins = 0;
+ while (performance.now() < end) {
+ spins += 1;
+ }
+ return {from, to: performance.timeOrigin + performance.now(), spins};
+ }, ms);
+ }
+ return during.evaluate(
+ (element, {duration, minProgress, wait}) =>
+ new Promise((resolve, reject) => {
+ // The harness's own waits run on the real timers: a frozen timer gate
+ // (story.ts) holds only the page's.
+ const gate = (
+ window as unknown as {
+ __harnessTimerGate?: {
+ frame?: typeof requestAnimationFrame;
+ timeout?: typeof setTimeout;
+ };
+ }
+ ).__harnessTimerGate;
+ const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);
+ const later = gate?.timeout ?? window.setTimeout.bind(window);
+ const deadline = performance.now() + wait;
+ const tick = () => {
+ const running = element
+ .getAnimations({subtree: true})
+ .some(
+ a =>
+ a.playState === 'running' &&
+ !a.pending &&
+ Number(a.currentTime ?? 0) >= minProgress,
+ );
+ if (running) {
+ // The same loop as above, from a task queued in the frame that saw
+ // the animation: it runs once that frame's rendering update has
+ // handed the animation to the compositor.
+ later(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + duration;
+ while (performance.now() < end) {
+ // Busy: nothing else runs.
+ }
+ resolve({from, to: performance.timeOrigin + performance.now()});
+ }, 0);
+ } else if (performance.now() > deadline) {
+ reject(new Error('blockMainThread: no animation started'));
+ } else {
+ frame(tick);
+ }
+ };
+ frame(tick);
+ }),
+ {duration: ms, minProgress, wait: timeout},
+ );
+}
+
+export interface BusyVerdict {
+ readonly pass: boolean;
+ /** Each criterion the window missed, with its measured value and limit. */
+ readonly failures: readonly string[];
+}
+
+export interface BusyProof extends FrameStats {
+ readonly window: BusyWindow;
+ /**
+ * The part of the window judged: inside the margins, up to `settledWithin`,
+ * and from `onScreenFromMs` when that is set.
+ */
+ readonly judged: {readonly from: number; readonly to: number};
+ /**
+ * When the tracked value was seen at rest before the judged part (a frame
+ * there, no change in the 250 ms before it: a just-started animation not on
+ * screen yet), ms after the window's start of its first presented change
+ * inside the block, where judging starts; null otherwise.
+ */
+ readonly onScreenFromMs: number | null;
+ /**
+ * The cast's position step, CSS px: the largest of 0.5, 1 and 2 that every
+ * tracked position is a multiple of (WebKit's casts are 2: see the README).
+ */
+ readonly stepPx: number;
+ /** The tracked value's mean motion per screencast interval in the judged part, px. */
+ readonly pxPerFrame: number;
+ /** Facts worth reading beside the verdict, which never fail it. */
+ readonly notes: readonly string[];
+ /**
+ * With a compositor record (`presented`): frames the screencast skipped
+ * between two moved frames while the compositor presented them, which are
+ * neither stalls nor misses; 0 without one.
+ */
+ readonly recorderSkipped: number;
+ /**
+ * The compositor's frame interval around the window, ms, from `presented`;
+ * null without a usable record (the screencast alone is judged).
+ */
+ readonly compositorFrameMs: number | null;
+ /**
+ * The screencast's frame interval, from the frames around the window as well
+ * as inside it (a short window has few intervals; a frozen one has none).
+ */
+ readonly cadenceMs: number;
+ /**
+ * Whole frame intervals in the judged part at the measured cadence (the
+ * compositor's, when recorded): the `minJudgedFrames` floor reads it.
+ */
+ readonly expectedFrames: number;
+ /** Frames the screencast delivered in the judged part, with the marker found. */
+ readonly deliveredFrames: number;
+ /**
+ * Longest time inside the window with no presented change, the window's own
+ * edges included. A frozen animation presents no new frame at all (nothing
+ * on screen changed, so the compositor sends none): its stall is the whole
+ * window.
+ */
+ readonly longestStallMs: number;
+ /** Where the longest stall starts, ms after the window's start. */
+ readonly longestStallAtMs: number;
+ /**
+ * `longestStallMs` in screencast intervals, rounded: 1 is no frame missed,
+ * 2 is one dropped frame. Rounding absorbs timestamp jitter.
+ */
+ readonly longestStallFrames: number;
+ /**
+ * Frames in the window that presented a new position (the first compared
+ * with the last frame before the window).
+ */
+ readonly moved: number;
+ /**
+ * `moved` (and `recorderSkipped`) over the frames judged: the frames the
+ * screencast delivered in the judged part, or with a compositor record the
+ * compositor's frames from the first to the last moved frame;
+ * `expectedFrames` when nothing moved, or fewer than `minJudgedFrames`
+ * frames were delivered.
+ */
+ readonly movedFraction: number;
+ /** The judgment against the limits (see `busyWindowProof`). */
+ readonly verdict: BusyVerdict;
+ /** One line with the raw numbers, for an annotation or a failure message. */
+ readonly summary: string;
+}
+
+/**
+ * Frame evidence for a busy window: how many frames the screencast presented
+ * inside it, how many of them moved the tracked axis, and the longest stall.
+ * The window is trimmed by `marginMs` at both ends so the frame the block
+ * started on and the one it ended on are not counted.
+ *
+ * The verdict judges the frames the screencast delivered, whatever its rate
+ * (a loaded machine's screencast can deliver one frame in five or six), and
+ * tolerates nothing a main-thread animation does (it presents no frame for
+ * the whole block). It passes when:
+ * - the judged part presented at least one frame, and, only when a proof
+ * claims display rate and passes `maxMedianFrameMs`, their median interval
+ * is at most that;
+ * - no stall spans more than `maxStallFrames` screencast intervals;
+ * - at least `minMovedFraction` of the frames judged moved the tracked axis
+ * (a short window may still miss one): the frames the screencast delivered
+ * in the judged part, so an irregular cast is judged on what it delivered
+ * and a frame it did not deliver is a gap for the stall check, not a miss
+ * (unless it delivered fewer than `minJudgedFrames` there: then every frame
+ * of the judged part's span counts, so one late frame is not 1/1 moved);
+ * with a compositor record, the compositor's frames from the first to the
+ * last moved frame (the gaps before and after are the stall check's);
+ * - the judged part spans at least `minJudgedFrames` frames. Fewer means the
+ * animation under test was not moving during the block (it settled before
+ * the block, or the block caught another animation), so there is nothing to
+ * judge, and that fails rather than passes.
+ *
+ * A just-started animation can reach the screen after the block began (its
+ * hand-off to the compositor lags under load: 50–100 ms in WebKit). When the
+ * tracked value was seen at rest before the judged part (a frame there, and no
+ * change in the 250 ms before it), judging starts at its first presented
+ * change inside the block, which the
+ * proof reports as `onScreenFromMs`. The judged part still ends with the
+ * block and the `minJudgedFrames` floor applies to it, so a start the block
+ * itself delays fails; an animation that was already moving is judged from
+ * the block's start, and a stall there fails as before.
+ *
+ * `stepPx` and `pxPerFrame` say whether a frame's motion is resolvable at
+ * all: under two position steps per frame, a frame delivered early can show
+ * no step and read as not moved, which the proof notes (never a failure).
+ *
+ * A loaded machine's screencast can skip frames the compositor still presents
+ * (Chromium). Given the compositor's record (`presented`, from
+ * `startCompositorTrace`), a gap between two moved frames with no frame
+ * delivered inside it is measured between the compositor's own frames: it is
+ * a stall only where the compositor presented nothing, and the frames it did
+ * present there are neither stalls nor misses (`recorderSkipped`). A gap
+ * that opens or closes the judged part, or holds a delivered frame that did
+ * not move, is judged from the screencast as before, so a frozen element
+ * fails whatever else the compositor draws.
+ */
+export function busyWindowProof(
+ tracked: readonly TrackedFrame[],
+ window: BusyWindow,
+ {
+ axis = 'y',
+ marginMs = 20,
+ settledWithin,
+ settledAt,
+ maxMedianFrameMs = Infinity,
+ maxStallFrames = 3,
+ minMovedFraction = 0.9,
+ minJudgedFrames = 4,
+ presented,
+ }: {
+ axis?: 'x' | 'y' | 'width' | 'height';
+ marginMs?: number;
+ /**
+ * Opt-in, for a proof that claims display rate: the most the median frame
+ * interval may be, ms (20 at 60 Hz). Off by default, since it measures the
+ * screencast's own rate as much as the animation.
+ */
+ maxMedianFrameMs?: number;
+ /** The most screencast intervals one stall may span (3 = two dropped frames). */
+ maxStallFrames?: number;
+ /**
+ * The least fraction of the expected frames that must move. One missed
+ * frame is always allowed, so a window of under ten frames is not judged
+ * stricter than a long one.
+ */
+ minMovedFraction?: number;
+ /** The fewest whole frame intervals the judged part of the window may span. */
+ minJudgedFrames?: number;
+ /**
+ * Stop judging once the value is within this many px of where it ends.
+ * The screencast reports whole CSS pixels, so an easing tail that still
+ * moves shows plateaus (26, 26, 26 against a final 24) that would read
+ * as a stall: 2 is the usual value.
+ */
+ settledWithin?: number;
+ /**
+ * Where the value ends, for `settledWithin`: read it from the page once the
+ * animation has ended (`waitForRest`). Defaults to the last frame's value,
+ * which can be stale: once an accelerated animation ends while the main
+ * thread is still blocked, WebKit presents the layer's last committed
+ * position until the main thread commits the end state.
+ */
+ settledAt?: number;
+ /**
+ * When the compositor presented each frame, epoch ms on the page clock
+ * (`startCompositorTrace`; Chromium). Empty or absent, the screencast is
+ * judged alone.
+ */
+ presented?: readonly number[];
+ } = {},
+): BusyProof {
+ let end = window.to - marginMs;
+ if (settledWithin != null) {
+ const valued = tracked.flatMap(f =>
+ f.box == null ? [] : [{t: f.t, value: f.box[axis]}],
+ );
+ const final =
+ settledAt ?? (valued.length > 0 ? valued[valued.length - 1].value : null);
+ const arrived = valued.find(
+ f =>
+ f.t >= window.from &&
+ final != null &&
+ Math.abs(f.value - final) <= settledWithin,
+ );
+ if (arrived != null) {
+ end = Math.min(end, arrived.t);
+ }
+ }
+ const inner = {from: window.from + marginMs, to: end};
+ const values = tracked
+ .filter(f => f.t >= inner.from && f.t <= inner.to)
+ .map(f => ({t: f.t, value: f.box == null ? null : f.box[axis]}));
+ const before = [...tracked].reverse().find(f => f.t < inner.from);
+ let previous: number | null = before?.box == null ? null : before.box[axis];
+ const inWindow: number[] = [];
+ for (const v of values) {
+ if (
+ v.value != null &&
+ previous != null &&
+ Math.abs(v.value - previous) > 0.25
+ ) {
+ inWindow.push(v.t);
+ }
+ if (v.value != null) {
+ previous = v.value;
+ }
+ }
+ // Seen at rest before the judged part (a frame there, and no change in the
+ // 250 ms before it): the first presented change is the animation's on-screen
+ // start, and judging starts there. With no frame before, nothing is known,
+ // and the window is judged from its start.
+ const prior = tracked.filter(f => f.box != null && f.t < inner.from);
+ let leadFrom = 0;
+ prior.forEach((f, i) => {
+ if (f.t < inner.from - 250) {
+ leadFrom = i;
+ }
+ });
+ const lead = prior.flatMap(f => (f.box == null ? [] : [f.box[axis]]));
+ const movedBefore = lead.some(
+ (value, i) => i > leadFrom && Math.abs(value - lead[i - 1]) > 0.25,
+ );
+ const onScreenFrom =
+ prior.length > 0 && !movedBefore && inWindow.length > 0
+ ? inWindow[0]
+ : null;
+ const judged = {from: onScreenFrom ?? inner.from, to: inner.to};
+ const changes = inWindow.filter(t => t > judged.from || onScreenFrom == null);
+ const edges = [judged.from, ...changes, judged.to];
+ const around = tracked
+ .filter(f => f.t >= inner.from - 250 && f.t <= inner.to + 250)
+ .map(f => f.t);
+ const intervals = around
+ .slice(1)
+ .map((t, i) => t - around[i])
+ .sort((a, b) => a - b);
+ const stats = frameStats(
+ tracked.map(f => ({t: f.t, value: f.box == null ? null : f.box[axis]})),
+ judged,
+ );
+ const cadence =
+ intervals.length >= 4
+ ? intervals[Math.floor(intervals.length / 2)]
+ : stats.medianFrameMs || 1000 / 60;
+ // The compositor's own frames, when recorded: its interval, from the frames
+ // around the judged part.
+ const draws = [...(presented ?? [])]
+ .filter(t => t >= judged.from - 250 && t <= judged.to + 250)
+ .sort((a, b) => a - b);
+ const drawIntervals = draws
+ .slice(1)
+ .map((t, i) => t - draws[i])
+ .sort((a, b) => a - b);
+ const compositorFrameMs =
+ drawIntervals.length >= 4
+ ? drawIntervals[Math.floor(drawIntervals.length / 2)]
+ : null;
+ const changed = new Set(inWindow);
+ const delivered = tracked
+ .filter(f => f.box != null && f.t > judged.from && f.t < judged.to)
+ .map(f => f.t);
+ // Each gap between presented changes, in intervals of the channel that saw
+ // it: the screencast's, or, for a gap between two moved frames with no
+ // frame delivered inside it, the compositor's own longest interval there.
+ const gaps = edges.slice(1).map((to, i) => {
+ const from = edges[i];
+ const ms = to - from;
+ if (
+ compositorFrameMs == null ||
+ !changed.has(from) ||
+ !changed.has(to) ||
+ delivered.some(t => t > from && t < to)
+ ) {
+ return {from, ms, frames: Math.round(ms / cadence), skipped: 0};
+ }
+ const span = draws.filter(
+ t => t > from - compositorFrameMs / 2 && t < to + compositorFrameMs / 2,
+ );
+ const longest =
+ span.length >= 2
+ ? Math.min(ms, Math.max(...span.slice(1).map((t, j) => t - span[j])))
+ : ms;
+ const frames = Math.round(longest / compositorFrameMs);
+ return {
+ from,
+ ms: longest,
+ frames,
+ skipped: Math.max(0, Math.round(ms / compositorFrameMs) - frames),
+ };
+ });
+ const longestGap = gaps.reduce((a, b) =>
+ b.frames > a.frames || (b.frames === a.frames && b.ms > a.ms) ? b : a,
+ );
+ const longestStallMs = longestGap.ms;
+ // Where the longest stall starts, from the start of the window.
+ const longestStallAtMs = longestGap.from - window.from;
+ const longestStallFrames = longestGap.frames;
+ const skips = gaps.filter(g => g.skipped > 0);
+ const recorderSkipped = skips.reduce((sum, g) => sum + g.skipped, 0);
+ // With a compositor record, frames count in its intervals, and the frames
+ // it presented where the screencast skipped are presented frames.
+ const expectedFrames = Math.floor(
+ (judged.to - judged.from) / (compositorFrameMs ?? cadence),
+ );
+ const moved = changes.length;
+ // The frames judged for motion: the screencast's own frames in the judged
+ // part (each `changes` entry is one of them), or, with a compositor record,
+ // the compositor's frames from the first to the last moved frame (the gaps
+ // before and after them are the stall check's). After an on-screen start
+ // they count from the on-screen frame, which `changes` leaves out, so the
+ // frames credited as skipped after it are judged too. A part that moved
+ // nothing, or delivered fewer than `minJudgedFrames` frames, is judged
+ // against its span, so a frozen animation misses here too (one late frame
+ // from before the block is not 1/1 moved).
+ const deliveredFrames = tracked.filter(
+ f =>
+ f.box != null &&
+ (onScreenFrom == null ? f.t >= judged.from : f.t > judged.from) &&
+ f.t <= judged.to,
+ ).length;
+ const judgedFrames =
+ compositorFrameMs != null
+ ? changes.length > 0
+ ? Math.round(
+ (changes[changes.length - 1] - (onScreenFrom ?? changes[0])) /
+ compositorFrameMs,
+ ) + (onScreenFrom == null ? 1 : 0)
+ : expectedFrames
+ : deliveredFrames < minJudgedFrames
+ ? expectedFrames
+ : deliveredFrames;
+ const movedFraction = (moved + recorderSkipped) / Math.max(1, judgedFrames);
+ // The cast's position step, and the motion per interval it has to resolve.
+ const positions = tracked.flatMap(f => (f.box == null ? [] : [f.box[axis]]));
+ const stepPx =
+ [2, 1, 0.5].find(step =>
+ positions.every(p => Math.abs(p / step - Math.round(p / step)) < 0.01),
+ ) ?? 0.5;
+ const judgedValues = tracked.flatMap(f =>
+ f.box != null && f.t >= judged.from && f.t <= judged.to
+ ? [{t: f.t, value: f.box[axis]}]
+ : [],
+ );
+ const first = judgedValues[0];
+ const last = judgedValues[judgedValues.length - 1];
+ const pxPerFrame =
+ first == null || last == null || last.t <= first.t
+ ? 0
+ : Math.abs(last.value - first.value) / ((last.t - first.t) / cadence);
+ const notes: string[] = [];
+ if (presented != null && compositorFrameMs == null) {
+ notes.push(
+ 'no compositor frames recorded around the window: judged from the screencast alone',
+ );
+ }
+ if (recorderSkipped > 0) {
+ notes.push(
+ `the screencast skipped ${recorderSkipped} frames the compositor presented (at ${skips.map(g => `+${(g.from - window.from).toFixed(0)} ms`).join(', ')})`,
+ );
+ }
+ if (pxPerFrame > 0 && pxPerFrame < 2 * stepPx) {
+ notes.push(
+ `${pxPerFrame.toFixed(1)} px/frame is under two of the cast's ${stepPx} px position steps: a frame delivered early can show no step and read as not moved`,
+ );
+ }
+ const failures: string[] = [];
+ if (stats.frames === 0) {
+ failures.push('no frame presented in the judged part');
+ } else if (stats.medianFrameMs > maxMedianFrameMs) {
+ failures.push(
+ `median frame interval ${stats.medianFrameMs.toFixed(1)} ms > ${maxMedianFrameMs} ms (${stats.frames} frames presented)`,
+ );
+ }
+ if (longestStallFrames > maxStallFrames) {
+ failures.push(
+ `longest stall ${longestStallMs.toFixed(1)} ms = ${longestStallFrames} intervals > ${maxStallFrames}`,
+ );
+ }
+ if (expectedFrames < minJudgedFrames) {
+ failures.push(
+ `${(judged.to - judged.from).toFixed(0)} ms judged = ${expectedFrames} frames < ${minJudgedFrames}: the animation under test was not moving during the block`,
+ );
+ }
+ const allowedMisses = Math.max(
+ 1,
+ Math.floor((1 - minMovedFraction) * judgedFrames + 1e-9),
+ );
+ if (judgedFrames - moved - recorderSkipped > allowedMisses) {
+ failures.push(
+ `${moved} of ${judgedFrames} expected frames moved${recorderSkipped > 0 ? ` (and ${recorderSkipped} the screencast skipped)` : ''} (${(movedFraction * 100).toFixed(0)}% < ${(minMovedFraction * 100).toFixed(0)}%)`,
+ );
+ }
+ const onScreenFromMs =
+ onScreenFrom == null ? null : onScreenFrom - window.from;
+ const summary =
+ `${(judged.to - judged.from).toFixed(0)} ms judged at ${cadence.toFixed(1)} ms/frame: ${stats.frames} frames presented, ` +
+ `${moved}/${judgedFrames} moved${recorderSkipped > 0 ? ` and ${recorderSkipped} skipped by the screencast` : ''} (${(movedFraction * 100).toFixed(0)}%), ` +
+ `median ${stats.medianFrameMs.toFixed(1)} ms, ` +
+ `longest stall ${longestStallMs.toFixed(1)} ms (${longestStallFrames} intervals) at +${longestStallAtMs.toFixed(0)} ms, ` +
+ `${stats.monotonic ? 'monotonic' : 'not monotonic'}, ` +
+ `${pxPerFrame.toFixed(1)} px/frame in ${stepPx} px steps` +
+ (compositorFrameMs == null
+ ? ''
+ : `, compositor presenting every ${compositorFrameMs.toFixed(1)} ms`) +
+ (onScreenFromMs == null
+ ? ''
+ : `, on screen from +${onScreenFromMs.toFixed(0)} ms (nothing moved before the block)`) +
+ notes.map(note => `; note: ${note}`).join('');
+ return {
+ ...stats,
+ window,
+ judged,
+ onScreenFromMs,
+ stepPx,
+ pxPerFrame,
+ notes,
+ recorderSkipped,
+ compositorFrameMs,
+ cadenceMs: cadence,
+ longestStallMs,
+ longestStallAtMs,
+ expectedFrames,
+ deliveredFrames,
+ longestStallFrames,
+ moved,
+ movedFraction,
+ verdict: {pass: failures.length === 0, failures},
+ summary,
+ };
+}
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index 69b9908066f62..4a36629d1f0a7 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -134,17 +134,61 @@ function animationRecorder(): void {
return entry.startedAt == null && entry.animation.playState !== 'idle';
});
};
+ // While a rendering trace runs (traceRendering sets
+ // `__harnessRenderingTrace`), the recorder stands down. Its per-frame
+ // callback would make every frame a main-thread frame, in which Blink
+ // restyles each running animation's target, a composited one included (and
+ // lays out an anchored one), and document.getAnimations() flushes style:
+ // exactly what the trace counts. So it runs no frame callback, and a CSS
+ // animation or transition event reads only the animations of the element it
+ // names, once, at that animation's start (one that ends inside the trace is
+ // otherwise never seen). The animate() wrapper below still records script
+ // animations (it reads no style), and traceRendering resumes the recorder
+ // once the trace ends.
+ const tracing = () =>
+ (window as unknown as {__harnessRenderingTrace?: boolean})
+ .__harnessRenderingTrace === true;
+ let looping = false;
const tick = () => {
+ if (tracing()) {
+ looping = false;
+ return;
+ }
record();
frame(tick);
};
+ const loop = () => {
+ if (!looping) {
+ looping = true;
+ frame(tick);
+ }
+ };
// What already runs when the recorder starts (a spinner on a page the
// harness touches for the first time) is seen now, before any watch arms;
// first seen a frame later, it would read as started by the watched action.
+ // (A recorder that starts during a trace reads once here, then waits.)
record();
- frame(tick);
+ loop();
for (const type of ['animationstart', 'transitionrun', 'transitionstart']) {
- document.addEventListener(type, record, true);
+ document.addEventListener(
+ type,
+ event => {
+ if (!tracing()) {
+ record();
+ return;
+ }
+ const target = event.target;
+ if (target instanceof Element) {
+ // A pseudo-element's animation (`::backdrop`) is in the subtree.
+ const pseudo = (event as AnimationEvent | TransitionEvent)
+ .pseudoElement;
+ for (const animation of target.getAnimations({subtree: !!pseudo})) {
+ remember(animation);
+ }
+ }
+ },
+ true,
+ );
}
// A script animation is recorded as it is made: WebKit can start and finish
// a short one between two frames of a fresh page.
@@ -159,12 +203,36 @@ function animationRecorder(): void {
};
w.__harnessAnimations = {
log,
- record,
+ // A read from outside the recorder (a wait's poll) stands down while a
+ // trace runs, as the frame loop does: document.getAnimations() flushes
+ // style. CSS start events and the animate() wrapper still log what
+ // starts, and resume() catches up.
+ record: () => {
+ if (!tracing()) {
+ record();
+ }
+ },
+ // Catches up on what started during a trace, then runs its frames again.
+ resume: () => {
+ record();
+ loop();
+ },
// Record first, then stamp strictly after the newest entry: a step that
// changed style just before has its transition created by that read,
- // and it started before the arm.
- arm: () => {
- record();
+ // and it started before the arm. While a trace runs the page-wide read
+ // stands down, as record() does; the watched element's own animations
+ // are still read, which resolves its pending style change. That read
+ // restyles the element (and lays out an anchored one) in the task that
+ // takes the watch, so a traced proof takes its watch before the window
+ // it counts (README: No Layout / Paint).
+ arm: (element?: Element) => {
+ if (!tracing()) {
+ record();
+ } else if (element != null) {
+ for (const animation of element.getAnimations({subtree: true})) {
+ remember(animation);
+ }
+ }
const newest = log.length === 0 ? 0 : log[log.length - 1].seenAt;
armedAt = Math.max(performance.now(), newest + 0.001);
return armedAt;
@@ -197,10 +265,47 @@ async function installCurveEnd(page: Page): Promise {
await page.evaluate(() => {
const w = window as unknown as {
__harnessCurveEnd?: (animation: Animation) => number;
+ __harnessTiming?: (
+ effect: AnimationEffect | null | undefined,
+ ) => ComputedEffectTiming | null;
+ };
+ // An effect's timing as getComputedTiming() reports it. Inside a rendering
+ // trace it is worked out from getTiming() instead: getComputedTiming()
+ // updates a running animation on demand, which restyles its target in the
+ // next frame (and lays out an anchored one), exactly what a trace counts.
+ w.__harnessTiming ??= effect => {
+ if (effect == null) {
+ return null;
+ }
+ if (
+ (window as unknown as {__harnessRenderingTrace?: boolean})
+ .__harnessRenderingTrace !== true
+ ) {
+ return effect.getComputedTiming();
+ }
+ const timing = effect.getTiming();
+ const duration =
+ typeof timing.duration === 'number' ? timing.duration : 0;
+ const iterations = Number(timing.iterations ?? 1);
+ const delay = Number(timing.delay ?? 0);
+ const endDelay = Number(timing.endDelay ?? 0);
+ const activeDuration =
+ duration === 0 || iterations === 0 ? 0 : duration * iterations;
+ const derived: ComputedEffectTiming = {
+ ...timing,
+ duration,
+ iterations,
+ delay,
+ endDelay,
+ activeDuration,
+ endTime: Math.max(delay + activeDuration + endDelay, 0),
+ };
+ return derived;
};
if (w.__harnessCurveEnd) {
return;
}
+ const timingOf = w.__harnessTiming;
const timingKeys = new Set([
'offset',
'computedOffset',
@@ -216,7 +321,7 @@ async function installCurveEnd(page: Page): Promise {
);
w.__harnessCurveEnd = animation => {
const effect = animation.effect as KeyframeEffect | null;
- const timing = effect?.getComputedTiming();
+ const timing = timingOf(effect);
const delay = Number(timing?.delay ?? 0);
const active = Number(timing?.activeDuration ?? 0);
if (
@@ -826,6 +931,47 @@ export interface ActiveAnimation {
readonly finishedAt: number | null;
}
+/**
+ * Runs `fn` on `locator`'s element: through the locator, or, `quietly`,
+ * through a handle to the element it matches now (none yet: `[]`). Each
+ * locator.evaluate makes a main-thread frame, which a trace counts;
+ * `elementHandles()` and a handle's evaluate make none.
+ */
+async function readElement(
+ locator: Locator,
+ quietly: boolean,
+ fn: (element: Element, arg: A) => R[],
+ arg: A,
+ timeout: number,
+): Promise {
+ const run = fn as unknown as (element: Element, arg: unknown) => R[];
+ if (!quietly) {
+ return locator.evaluate(run, arg as unknown, {timeout});
+ }
+ const handles = await locator.elementHandles();
+ try {
+ if (handles.length > 1) {
+ throw new Error(
+ `waitForAnimation: ${String(locator)} matches ${handles.length} elements`,
+ );
+ }
+ return handles.length === 0
+ ? []
+ : await handles[0].evaluate(run, arg as unknown);
+ } finally {
+ await Promise.all(handles.map(handle => handle.dispose()));
+ }
+}
+
+/** The rejection for a wait whose element is not in the document. */
+function notInDocument(name: string, cause?: unknown): Error {
+ return new Error(
+ `${name}: the element is not in the document. An exit that removes ` +
+ 'its element is read through its container (watch the parent).',
+ cause === undefined ? undefined : {cause},
+ );
+}
+
/**
* Runs a locator read within the wait's own deadline. A locator waits for
* its element with no timeout of its own, so one the page removed (an exit
@@ -847,11 +993,7 @@ async function withinTimeout(
if ((await locator.count()) > 0) {
return null;
}
- throw new Error(
- `${name}: the element is not in the document. An exit that removes ` +
- 'its element is read through its container (watch the parent).',
- {cause: error},
- );
+ throw notInDocument(name, error);
}
throw error;
}
@@ -876,6 +1018,15 @@ async function withinTimeout(
* recorder keeps one entry per `Animation` object, so an animation reversed
* or replayed mid-run is misread: a watch taken before the reversal rejects,
* and an unwatched wait returns at once with a curve dated before it.
+ *
+ * Started inside a `traceRendering` body, it stands down as the recorder
+ * does, so it adds no frame the trace counts: it takes the element's
+ * animations from the recorder's log, judges a started one by its own times,
+ * and reaches the element through a handle to what the locator matches at
+ * each look. That holds for script animations and CSS transitions. On a CSS
+ * `@keyframes` animation (and, unwatched, a cancelled CSS transition) it reads
+ * the animation's timing, which flushes its style and adds Layouts to the
+ * trace: wait on one with `waitForRest`, or after the trace.
*/
export async function waitForAnimation(
locator: Locator,
@@ -891,17 +1042,34 @@ export async function waitForAnimation(
} = {},
): Promise {
const deadline = Date.now() + timeout;
- await installCurveEnd(locator.page());
+ const page = locator.page();
+ await installCurveEnd(page);
+ // Inside a rendering trace the wait stands down (see the page function),
+ // and it reads the element through handles: each locator.evaluate makes a
+ // main-thread frame (a Layout of an anchored element), where a handle's
+ // evaluate adds none.
+ const traced = await page.evaluate(
+ () =>
+ (window as unknown as {__harnessRenderingTrace?: boolean})
+ .__harnessRenderingTrace === true,
+ );
for (;;) {
const read = await withinTimeout(
'waitForAnimation',
locator,
deadline,
evaluateTimeout =>
- locator.evaluate(
+ readElement(
+ locator,
+ traced,
(element, {minProgress, since: watchedFrom}) => {
+ // The harness's own read: a trace sets it apart (trace.ts HARNESS_READ).
+ console.timeStamp('harness-read');
const w = window as unknown as {
__harnessCurveEnd: (a: Animation) => number;
+ __harnessTiming: (
+ effect: AnimationEffect | null | undefined,
+ ) => ComputedEffectTiming | null;
__harnessAnimations: {
log: {
animation: Animation;
@@ -916,6 +1084,13 @@ export async function waitForAnimation(
};
const curveEnd = w.__harnessCurveEnd;
const recorder = w.__harnessAnimations;
+ // Inside a rendering trace the wait stands down as the recorder does:
+ // record() reads nothing, the animations come from the recorder's log
+ // rather than getAnimations(), and a started one runs by its own
+ // times, since playState flushes a CSS animation's style.
+ const traced =
+ (window as unknown as {__harnessRenderingTrace?: boolean})
+ .__harnessRenderingTrace === true;
recorder.record();
const describe = (
a: Animation,
@@ -923,7 +1098,7 @@ export async function waitForAnimation(
recordedStart: number | null,
) => {
const effect = a.effect as KeyframeEffect | null;
- const timing = effect?.getComputedTiming();
+ const timing = w.__harnessTiming(effect);
// The recorded start stands in once the page has cancelled it. A
// run going backward began at its end: its startTime is where its
// current time would reach 0, a whole run later.
@@ -994,24 +1169,36 @@ export async function waitForAnimation(
// finished must not answer for it. Only document-timeline animations
// count, as for holdAnimations: a scroll- or view-timeline one moves
// only when something scrolls and never progresses on its own.
+ const runs = (a: Animation) => {
+ if (!(a.timeline instanceof DocumentTimeline)) {
+ return false;
+ }
+ if (!traced || a.startTime == null) {
+ return a.playState === 'running';
+ }
+ const time = Number(a.currentTime ?? 0);
+ return a.playbackRate < 0
+ ? time > 0
+ : time < Number(w.__harnessTiming(a.effect)?.endTime ?? 0);
+ };
+ const onElement = () =>
+ recorder.log.filter(
+ e => inside(e.animation) || e.ancestors.includes(element),
+ );
const live = (
- watchedFrom == null
+ watchedFrom == null && !traced
? element.getAnimations({subtree: true})
- : recorded
+ : (watchedFrom == null ? onElement() : recorded)
.filter(e => e.finishedAt == null)
.map(e => e.animation)
- ).filter(
- a =>
- a.playState === 'running' &&
- a.timeline instanceof DocumentTimeline,
- );
+ ).filter(runs);
const running = live.filter(a => a.startTime != null);
// Progress along the curve, on the timeline: a delay presents nothing
// (going backward, the end delay plays first), a run going backward
// (`reverse()`) progresses from its end, and a faster rate presents
// more curve per ms.
const progressed = running.filter(a => {
- const timing = a.effect?.getComputedTiming();
+ const timing = w.__harnessTiming(a.effect);
const time = Number(a.currentTime ?? 0);
const local =
a.playbackRate < 0
@@ -1036,13 +1223,20 @@ export async function waitForAnimation(
return e.finishedAt;
}
const a = e.animation;
- if (a.playState !== 'finished' || a.startTime == null) {
+ if (a.startTime == null) {
+ return null;
+ }
+ const end = Number(w.__harnessTiming(a.effect)?.endTime ?? 0);
+ // Traced, by its own times; otherwise by its state.
+ const time = Number(a.currentTime ?? 0);
+ const done = traced
+ ? a.playbackRate < 0
+ ? time <= 0
+ : time >= end
+ : a.playState === 'finished';
+ if (!done) {
return null;
}
- const end = Number(
- (a.effect as KeyframeEffect | null)?.getComputedTiming()
- .endTime ?? 0,
- );
return a.playbackRate < 0
? Number(a.startTime)
: Number(a.startTime) + end / Math.abs(a.playbackRate || 1);
@@ -1052,7 +1246,7 @@ export async function waitForAnimation(
.map(e => describe(e.animation, finishedAt(e), e.startedAt));
},
{minProgress: minProgressMs, since: since ?? null},
- {timeout: evaluateTimeout},
+ evaluateTimeout,
),
);
const found = read ?? [];
@@ -1061,6 +1255,12 @@ export async function waitForAnimation(
return found;
}
if (Date.now() > deadline) {
+ // A traced read goes through handles, which find no element rather
+ // than wait for one: a missing element is reported as missing, as the
+ // untraced read reports it.
+ if (traced && (await locator.count()) === 0) {
+ throw notInDocument('waitForAnimation');
+ }
throw new Error(
'waitForAnimation: no animation started on the element, none running ' +
'and none recorded since the last wait. If the action is the ' +
@@ -1072,13 +1272,31 @@ export async function waitForAnimation(
}
}
-/** Marks now as the point later waits count animations from. */
-async function armRecorder(page: Page): Promise {
- return page.evaluate(() =>
- (
- window as unknown as {__harnessAnimations: {arm: () => number}}
- ).__harnessAnimations.arm(),
- );
+/**
+ * Marks now as the point later waits count animations from. With a locator,
+ * its element's pending style change is resolved first, also inside a trace
+ * (reached through a handle, which adds no main-thread frame).
+ */
+async function armRecorder(page: Page, locator?: Locator): Promise {
+ const handles = locator == null ? [] : await locator.elementHandles();
+ try {
+ if (handles.length === 1) {
+ return await handles[0].evaluate(element =>
+ (
+ window as unknown as {
+ __harnessAnimations: {arm: (element?: Element) => number};
+ }
+ ).__harnessAnimations.arm(element as Element),
+ );
+ }
+ return await page.evaluate(() =>
+ (
+ window as unknown as {__harnessAnimations: {arm: () => number}}
+ ).__harnessAnimations.arm(),
+ );
+ } finally {
+ await Promise.all(handles.map(handle => handle.dispose()));
+ }
}
export interface AnimationWatch {
@@ -1096,7 +1314,9 @@ export interface AnimationWatch {
/**
* Starts watching `locator`'s element before an action, so the animation the
* action starts is caught even when it ends before the test looks (a short
- * entrance on a cold page):
+ * entrance on a cold page). Taking the watch reads the element's animations,
+ * which restyles it, inside a rendering trace too: take a traced watch before
+ * the window the proof counts:
*
* const watch = await watchAnimations(sheet);
* await driver.play(tap(button));
@@ -1106,7 +1326,7 @@ export async function watchAnimations(
locator: Locator,
): Promise {
await installCurveEnd(locator.page());
- const since = await armRecorder(locator.page());
+ const since = await armRecorder(locator.page(), locator);
return {
started: options => waitForAnimation(locator, {...options, since}),
};
@@ -1125,6 +1345,19 @@ export async function watchAnimations(
* forward run under a linear or cubic-bézier effect easing); under any other
* easing or direction, waitForRest waits the hold out, and a hold longer than
* `timeout` rejects with "still moving".
+ *
+ * While a rendering trace runs (`traceRendering`), it stands down as the
+ * animation recorder does: a per-frame callback would make every frame a
+ * main-thread frame, which the trace counts. It then waits on timers for the
+ * scheduled ends of the curves on the element instead (a run going backward,
+ * until it finishes), so motion that no animation drives (a script writing
+ * styles) is not seen until the trace ends. Its one read of the element's
+ * animations, as it is called, restyles the element (and lays out an anchored
+ * one) when an animation is already running there: await it right after the
+ * action that starts the motion, before the window a proof counts, not in its
+ * middle (README: No Layout / Paint). Finding no animation, it looks again `frames` times a frame
+ * apart before settling, so one the action starts a few frames later is
+ * waited for.
*/
export async function waitForRest(
locator: Locator,
@@ -1157,15 +1390,94 @@ export async function waitForRest(
backdrop,
].join(' | ');
};
- // The page's real frames, even while a timer gate holds its callbacks.
- const frame =
+ // The page's real frames and timers, even while a timer gate holds
+ // its callbacks: a frozen gate never holds the wait itself.
+ const gate = (
+ window as unknown as {
+ __harnessTimerGate?: {
+ frame: typeof requestAnimationFrame;
+ timeout?: typeof setTimeout;
+ };
+ }
+ ).__harnessTimerGate;
+ const frame = gate?.frame ?? requestAnimationFrame;
+ const timeout = gate?.timeout ?? setTimeout;
+ // Set by traceRendering while it traces (see the recorder above).
+ const tracing = () =>
+ (window as unknown as {__harnessRenderingTrace?: boolean})
+ .__harnessRenderingTrace === true;
+ const settle = () => {
+ // Later waits count animations from here.
(
- window as unknown as {
- __harnessTimerGate?: {frame: typeof requestAnimationFrame};
- }
- ).__harnessTimerGate?.frame ?? requestAnimationFrame;
- let last = read();
+ window as unknown as {__harnessAnimations?: {arm: () => number}}
+ ).__harnessAnimations?.arm();
+ resolve();
+ };
+ let last = '';
let still = 0;
+ const frames = () => {
+ last = read();
+ still = 0;
+ frame(tick);
+ };
+ // While traced: one look at the animations, then a timer to the latest
+ // scheduled curve end. One not started yet is looked at again a frame
+ // later; a trace that has ended hands over to the per-frame check.
+ // Finding nothing settles only after `frames` looks a frame apart, as
+ // the per-frame check needs `frames` still frames: an animation the
+ // action starts a frame or two later is still waited for.
+ let idle = 0;
+ const scheduled = () => {
+ let wait = 0;
+ for (const a of element.getAnimations({subtree: true})) {
+ // A scroll- or view-timeline animation moves only when something
+ // scrolls: it has no scheduled end to wait for (holdAnimations
+ // skips it the same way).
+ if (!(a.timeline instanceof DocumentTimeline)) {
+ continue;
+ }
+ if (
+ a.pending ||
+ (a.playState === 'running' && a.startTime == null)
+ ) {
+ wait = Math.max(wait, 16);
+ } else if (a.playState === 'running') {
+ // The curve's time left through the playback rate: forward, to
+ // its (held) end; backward (`reverse()`), to local time 0,
+ // where it finishes, as the untraced path waits it out.
+ const rate = a.playbackRate || 1;
+ const at = Number(a.currentTime ?? 0);
+ const left =
+ rate > 0 ? (curveEnd(a) - at) / rate : at / -rate;
+ wait = Math.max(wait, left);
+ }
+ }
+ if (wait <= 0) {
+ idle += 1;
+ if (idle >= need) {
+ settle();
+ return;
+ }
+ wait = 16;
+ } else {
+ idle = 0;
+ }
+ const room = deadline - performance.now();
+ timeout(
+ () => {
+ if (performance.now() > deadline) {
+ reject(
+ new Error('waitForRest: still moving at the deadline'),
+ );
+ } else if (tracing()) {
+ scheduled();
+ } else {
+ frames();
+ }
+ },
+ Math.min(wait, Math.max(0, room)) + 1,
+ );
+ };
const tick = () => {
const now = read();
const moving = element.getAnimations({subtree: true}).some(
@@ -1182,20 +1494,20 @@ export async function waitForRest(
still = !moving && now === last ? still + 1 : 0;
last = now;
if (still >= need) {
- // Later waits count animations from here.
- (
- window as unknown as {
- __harnessAnimations?: {arm: () => number};
- }
- ).__harnessAnimations?.arm();
- resolve();
+ settle();
} else if (performance.now() > deadline) {
reject(new Error(`waitForRest: still moving (${now})`));
+ } else if (tracing()) {
+ scheduled();
} else {
frame(tick);
}
};
- frame(tick);
+ if (tracing()) {
+ scheduled();
+ } else {
+ frames();
+ }
}),
{ms: timeout, need: frames},
{timeout: evaluateTimeout},
diff --git a/internal/interaction-harness/src/frames.ts b/internal/interaction-harness/src/frames.ts
new file mode 100644
index 0000000000000..83841d259c17f
--- /dev/null
+++ b/internal/interaction-harness/src/frames.ts
@@ -0,0 +1,531 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file frames.ts
+ * @input Uses a Playwright `Page`, a `Locator` for the element under test, and
+ * the engine's screencast (Chromium CDP `Page.startScreencast`; WebKit's
+ * `Screencast` domain)
+ * @output `startScreencast` (timestamped composited frames), `markElement`
+ * (a marker outline the frames can find), `trackMarker` (per-frame marker
+ * box), `sampleRects` (per-rAF rect sampling), `frameStats`.
+ * @position Frame evidence for motion proofs. The screencast is captured off
+ * the page's main thread, from what the compositor presents, so it keeps
+ * delivering frames while a script blocks the main thread: that is what makes
+ * the busy-main-thread proof possible. Rect sampling is the cheap path when
+ * the main thread is free.
+ *
+ * Marker tracking needs no image library: frames are decoded and scanned in a
+ * scratch page of the same browser (createImageBitmap + canvas), so the
+ * harness adds no dependency.
+ *
+ * SYNC: Keep the README's frame-evidence section equal to what this measures.
+ */
+
+import type {CDPSession, Locator, Page} from '@playwright/test';
+import {webkitPageSession} from './touch';
+
+export interface CastFrame {
+ /** Presentation time, epoch ms (the compositor's frame timestamp). */
+ readonly t: number;
+ /** Base64 PNG/JPEG. */
+ readonly data: string;
+ readonly format: 'png' | 'jpeg';
+ /** CSS px of the viewport the frame shows. */
+ readonly viewportWidth: number;
+ readonly viewportHeight: number;
+}
+
+export interface Screencast {
+ /**
+ * Frames captured so far: wait for the first one to know the cast saw the
+ * page before an animation starts (`busyWindowProof` then knows its at-rest
+ * position).
+ */
+ frameCount(): number;
+ /** Stops and returns every frame captured, in order. */
+ stop(): Promise;
+}
+
+export interface ScreencastOptions {
+ /** Lossless frames by default: marker colours survive PNG, not JPEG. */
+ readonly format?: 'png' | 'jpeg';
+ readonly quality?: number;
+ /**
+ * Keep one presented frame in this many (default 1, every frame): a slower
+ * evidence channel, like a loaded machine's screencast, for proving that a
+ * verdict does not depend on the screencast's rate.
+ */
+ readonly everyNthFrame?: number;
+}
+
+/**
+ * Starts capturing composited frames. Chromium delivers one per presented
+ * frame (16.7 ms at 60 Hz), timestamped by the compositor; WebKit's own
+ * screencast delivers one per composited update (about every 14 ms in the
+ * Linux build), stamped on CLOCK_MONOTONIC and rebased here onto the wall
+ * clock by that clock's measured offset, so both engines share the page's
+ * timeline. Both keep delivering while the page's main thread is blocked, and
+ * neither sends a frame when nothing on screen changed.
+ */
+export async function startScreencast(
+ page: Page,
+ options: ScreencastOptions = {},
+): Promise {
+ const name = page.context().browser()?.browserType().name();
+ const viewport = page.viewportSize() ?? {width: 0, height: 0};
+ if (name === 'chromium') {
+ return chromiumScreencast(page, viewport, options);
+ }
+ if (name === 'webkit') {
+ return webkitScreencast(page, viewport, options);
+ }
+ throw new Error(
+ `startScreencast: unsupported browser ${name ?? '(unknown)'}`,
+ );
+}
+
+async function chromiumScreencast(
+ page: Page,
+ viewport: {width: number; height: number},
+ {format = 'png', quality = 90, everyNthFrame = 1}: ScreencastOptions,
+): Promise {
+ const cdp: CDPSession = await page.context().newCDPSession(page);
+ const frames: CastFrame[] = [];
+ const onFrame = (frame: {
+ data: string;
+ sessionId: number;
+ metadata: {timestamp?: number; deviceWidth: number; deviceHeight: number};
+ }) => {
+ frames.push({
+ t: (frame.metadata.timestamp ?? Date.now() / 1000) * 1000,
+ data: frame.data,
+ format,
+ viewportWidth: frame.metadata.deviceWidth || viewport.width,
+ viewportHeight: frame.metadata.deviceHeight || viewport.height,
+ });
+ cdp
+ .send('Page.screencastFrameAck', {sessionId: frame.sessionId})
+ .catch(() => {});
+ };
+ cdp.on('Page.screencastFrame', onFrame);
+ // One CSS px per frame px keeps decoding cheap; everyNthFrame 1 = every presented frame.
+ await cdp.send('Page.startScreencast', {
+ format,
+ quality,
+ maxWidth: viewport.width,
+ maxHeight: viewport.height,
+ everyNthFrame,
+ });
+ return {
+ frameCount: () => frames.length,
+ async stop() {
+ await cdp.send('Page.stopScreencast');
+ cdp.off('Page.screencastFrame', onFrame);
+ await cdp.detach().catch(() => {});
+ return inPresentationOrder(frames);
+ },
+ };
+}
+
+async function webkitScreencast(
+ page: Page,
+ viewport: {width: number; height: number},
+ {quality = 90, everyNthFrame = 1}: ScreencastOptions,
+): Promise {
+ const session = webkitPageSession(page);
+ const frames: CastFrame[] = [];
+ let generation = 0;
+ let delivered = 0;
+ const onFrame = (payload: unknown) => {
+ const frame = payload as {data: string; timestamp: number};
+ // WebKit's screencast has no everyNthFrame: keep one frame in N here.
+ delivered += 1;
+ if ((delivered - 1) % everyNthFrame !== 0) {
+ session
+ .send('Screencast.screencastFrameAck', {generation})
+ .catch(() => {});
+ return;
+ }
+ frames.push({
+ // WebKit stamps frames in seconds on the monotonic clock; rebased below.
+ t: frame.timestamp * 1000,
+ data: frame.data,
+ format: 'jpeg',
+ viewportWidth: viewport.width,
+ viewportHeight: viewport.height,
+ });
+ session.send('Screencast.screencastFrameAck', {generation}).catch(() => {});
+ };
+ session.on('Screencast.screencastFrame', onFrame);
+ const started = (await session.send('Screencast.startScreencast', {
+ width: viewport.width,
+ height: viewport.height,
+ toolbarHeight: 0,
+ quality,
+ })) as {generation: number};
+ generation = started.generation;
+ // WebKit stamps frames in seconds on CLOCK_MONOTONIC, which this process
+ // shares: rebase them by the wall clock's offset from that clock, sampled
+ // together. (Taking the first frame as the start shifted every frame earlier
+ // by however long that frame took to come, 60–100 ms on a busy page.)
+ const wallMinusMonotonic = Date.now() - Number(process.hrtime.bigint()) / 1e6;
+ return {
+ frameCount: () => frames.length,
+ async stop() {
+ await session.send('Screencast.stopScreencast');
+ session.off?.('Screencast.screencastFrame', onFrame);
+ if (frames.length === 0) {
+ return frames;
+ }
+ return inPresentationOrder(frames).map(f => ({
+ ...f,
+ t: f.t + wallMinusMonotonic,
+ }));
+ },
+ };
+}
+
+/**
+ * Frames sorted by their presentation timestamp. A loaded machine can deliver
+ * screencast frames out of order (a frame stamped 35 ms arriving after one
+ * stamped 46 ms); judged in arrival order, a steadily moving element would
+ * appear to step backwards.
+ */
+export function inPresentationOrder(
+ frames: readonly T[],
+): T[] {
+ return [...frames].sort((a, b) => a.t - b.t);
+}
+
+/** The marker colour: magenta never occurs in Astryx themes. */
+export const MARKER_RGB: readonly [number, number, number] = [255, 0, 255];
+
+export interface MarkerOptions {
+ readonly rgb?: readonly [number, number, number];
+ /**
+ * `chip` (default): a small square child pinned inside the element's
+ * top-left corner, above every sibling (z-index max), so nothing the
+ * component paints can cover it. The element must be its containing block:
+ * a static element is made `position: relative` while marked.
+ * `outline`: an inset outline on the element itself (no DOM insertion), for
+ * elements that cannot take a child; children with their own layers can
+ * cover parts of it.
+ */
+ readonly mode?: 'chip' | 'outline';
+ /** Chip size or outline width, CSS px. */
+ readonly size?: number;
+ /** Chip inset from the element's top-left corner, CSS px. */
+ readonly inset?: number;
+}
+
+/**
+ * Marks the element so screencast frames can find it: the mark moves, scales
+ * and fades with the element's own layer and never changes its layout.
+ * Returns an undo.
+ */
+export async function markElement(
+ locator: Locator,
+ options: MarkerOptions = {},
+): Promise<() => Promise> {
+ const {
+ rgb = MARKER_RGB,
+ mode = 'chip',
+ size = mode === 'chip' ? 16 : 6,
+ inset = 8,
+ } = options;
+ const id = `m${Math.random().toString(36).slice(2, 8)}`;
+ await locator.evaluate(
+ (element, {id: markerId, color, size: px, inset: offset, mode: kind}) => {
+ const el = element as HTMLElement;
+ el.setAttribute('data-harness-marker', markerId);
+ if (kind === 'outline') {
+ const style = document.createElement('style');
+ style.setAttribute('data-harness-marker-style', markerId);
+ style.textContent = `[data-harness-marker="${markerId}"]{outline:${px}px solid rgb(${color.join(',')}) !important;outline-offset:-${px}px !important;}`;
+ document.head.append(style);
+ return;
+ }
+ if (getComputedStyle(el).position === 'static') {
+ el.setAttribute('data-harness-marker-position', el.style.position);
+ el.style.position = 'relative';
+ }
+ const chip = document.createElement('div');
+ chip.setAttribute('data-harness-marker-chip', markerId);
+ chip.setAttribute('aria-hidden', 'true');
+ chip.style.cssText = `position:absolute;top:${offset}px;left:${offset}px;width:${px}px;height:${px}px;background:rgb(${color.join(',')});z-index:2147483647;pointer-events:none;`;
+ el.append(chip);
+ },
+ {id, color: [...rgb], size, inset, mode},
+ );
+ return async () => {
+ await locator.page().evaluate(markerId => {
+ const el = document.querySelector(
+ `[data-harness-marker="${markerId}"]`,
+ );
+ if (el?.hasAttribute('data-harness-marker-position')) {
+ el.style.position =
+ el.getAttribute('data-harness-marker-position') ?? '';
+ el.removeAttribute('data-harness-marker-position');
+ }
+ el?.removeAttribute('data-harness-marker');
+ document
+ .querySelector(`[data-harness-marker-chip="${markerId}"]`)
+ ?.remove();
+ document
+ .querySelector(`[data-harness-marker-style="${markerId}"]`)
+ ?.remove();
+ }, id);
+ };
+}
+
+export interface Box {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface TrackedFrame {
+ /** Epoch ms. */
+ readonly t: number;
+ /** The marker's bounding box in CSS px, or null when it is not on screen. */
+ readonly box: Box | null;
+ /** Marker pixels found (a fading element finds fewer at the same tolerance). */
+ readonly pixels: number;
+}
+
+/**
+ * Finds the marker in every frame. Decoding runs in a scratch page of the same
+ * browser, so neither the page under test nor Node needs an image decoder.
+ */
+export async function trackMarker(
+ page: Page,
+ frames: readonly CastFrame[],
+ {
+ rgb = MARKER_RGB,
+ tolerance = 40,
+ }: {rgb?: readonly [number, number, number]; tolerance?: number} = {},
+): Promise {
+ const scratch = await page.context().newPage();
+ try {
+ const out: TrackedFrame[] = [];
+ // Batches keep each evaluate payload moderate.
+ for (let i = 0; i < frames.length; i += 12) {
+ const batch = frames.slice(i, i + 12);
+ const boxes = await scratch.evaluate(
+ async ({batch: items, color, tol}) => {
+ const results: {
+ box: {x: number; y: number; width: number; height: number} | null;
+ pixels: number;
+ }[] = [];
+ for (const item of items) {
+ const blob = await (
+ await fetch(`data:image/${item.format};base64,${item.data}`)
+ ).blob();
+ const bitmap = await createImageBitmap(blob);
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const {data, width, height} = context.getImageData(
+ 0,
+ 0,
+ bitmap.width,
+ bitmap.height,
+ );
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let pixels = 0;
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const o = (y * width + x) * 4;
+ if (
+ Math.abs(data[o] - color[0]) <= tol &&
+ Math.abs(data[o + 1] - color[1]) <= tol &&
+ Math.abs(data[o + 2] - color[2]) <= tol
+ ) {
+ pixels += 1;
+ if (x < minX) {
+ minX = x;
+ }
+ if (x > maxX) {
+ maxX = x;
+ }
+ if (y < minY) {
+ minY = y;
+ }
+ if (y > maxY) {
+ maxY = y;
+ }
+ }
+ }
+ }
+ const scale = width / item.viewportWidth;
+ results.push({
+ box:
+ pixels === 0
+ ? null
+ : {
+ x: minX / scale,
+ y: minY / scale,
+ width: (maxX - minX + 1) / scale,
+ height: (maxY - minY + 1) / scale,
+ },
+ pixels,
+ });
+ }
+ return results;
+ },
+ {
+ batch: batch.map(f => ({
+ data: f.data,
+ format: f.format,
+ viewportWidth: f.viewportWidth,
+ })),
+ color: [...rgb],
+ tol: tolerance,
+ },
+ );
+ boxes.forEach((result, k) =>
+ out.push({t: batch[k].t, box: result.box, pixels: result.pixels}),
+ );
+ }
+ return out;
+ } finally {
+ await scratch.close();
+ }
+}
+
+export interface RectSample {
+ /** Epoch ms of the rAF callback. */
+ readonly t: number;
+ readonly box: Box | null;
+ readonly transform: string;
+ readonly opacity: number;
+}
+
+/**
+ * Samples the element's rect, transform and opacity on every animation frame
+ * for `durationMs`. Main-thread sampling: it stops while the main thread is
+ * blocked, which is the point of the screencast path above.
+ */
+export async function sampleRects(
+ locator: Locator,
+ durationMs: number,
+): Promise {
+ return locator.evaluate(
+ (element, duration) =>
+ new Promise<
+ {
+ t: number;
+ box: {x: number; y: number; width: number; height: number} | null;
+ transform: string;
+ opacity: number;
+ }[]
+ >(resolve => {
+ // The harness's own waits run on the real timers: a frozen timer gate
+ // (story.ts) holds only the page's.
+ const gate = (
+ window as unknown as {
+ __harnessTimerGate?: {
+ frame?: typeof requestAnimationFrame;
+ };
+ }
+ ).__harnessTimerGate;
+ const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);
+ const samples: {
+ t: number;
+ box: {x: number; y: number; width: number; height: number} | null;
+ transform: string;
+ opacity: number;
+ }[] = [];
+ const end = performance.now() + duration;
+ const tick = (now: number) => {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ samples.push({
+ t: performance.timeOrigin + now,
+ box: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
+ transform: style.transform,
+ opacity: Number(style.opacity),
+ });
+ if (now < end) {
+ frame(tick);
+ } else {
+ resolve(samples);
+ }
+ };
+ frame(tick);
+ }),
+ durationMs,
+ );
+}
+
+export interface FrameStats {
+ readonly frames: number;
+ /** Frames whose tracked value differs from the frame before. */
+ readonly changed: number;
+ /** Longest stretch without a change inside the window (an open stall at its end included), ms. */
+ readonly longestStallMs: number;
+ /** Median spacing between frames, ms. */
+ readonly medianFrameMs: number;
+ readonly monotonic: boolean;
+ readonly first: number | null;
+ readonly last: number | null;
+}
+
+/** Summarises per-frame values (e.g. the marker's y) inside a time window. */
+export function frameStats(
+ samples: readonly {readonly t: number; readonly value: number | null}[],
+ window: {readonly from: number; readonly to: number} = {
+ from: -Infinity,
+ to: Infinity,
+ },
+ epsilon = 0.25,
+): FrameStats {
+ const inside = samples.filter(
+ s => s.t >= window.from && s.t <= window.to && s.value != null,
+ ) as {t: number; value: number}[];
+ let changed = 0;
+ let increasing = 0;
+ let decreasing = 0;
+ let stallStart = inside[0]?.t ?? 0;
+ let longestStallMs = 0;
+ for (let i = 1; i < inside.length; i += 1) {
+ const delta = inside[i].value - inside[i - 1].value;
+ if (Math.abs(delta) > epsilon) {
+ changed += 1;
+ if (delta > 0) {
+ increasing += 1;
+ } else {
+ decreasing += 1;
+ }
+ longestStallMs = Math.max(longestStallMs, inside[i].t - stallStart);
+ stallStart = inside[i].t;
+ }
+ }
+ // A stall still open when the window closes counts too: a frozen animation never changes at all.
+ if (inside.length > 0) {
+ longestStallMs = Math.max(
+ longestStallMs,
+ inside[inside.length - 1].t - stallStart,
+ );
+ }
+ const gaps = inside
+ .slice(1)
+ .map((s, i) => s.t - inside[i].t)
+ .sort((a, b) => a - b);
+ return {
+ frames: inside.length,
+ changed,
+ longestStallMs,
+ medianFrameMs: gaps.length ? gaps[Math.floor(gaps.length / 2)] : 0,
+ monotonic: increasing === 0 || decreasing === 0,
+ first: inside[0]?.value ?? null,
+ last: inside[inside.length - 1]?.value ?? null,
+ };
+}
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index 7e47af95b2c81..b1a50ebc8c9e3 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -3,32 +3,52 @@
/**
* @file harness.interaction.browser.spec.ts
* @input Fixture pages written inline (no Storybook), real Chromium/WebKit
- * @output Proof that each harness instrument measures what it claims:
- * scripted timestamps reach the page; a flick flings natively (Chromium);
- * a second finger and a pinch arrive as distinct pointers; sampled curves
- * match the oracles; the animation-state waits report a running transition
- * and its end, and judge rest by presented values even while an animation
- * holds its end, and a watch taken on first contact ignores an animation
- * already running and keeps the start of one the page cancels when it ends; individual transform properties are sampled; a sample at
+ * @output Proof that each harness instrument measures what it claims (the
+ * busy-main-thread proof and the rendering-trace counts with a negative
+ * control beside their positive checks): scripted timestamps reach the
+ * page; a flick flings natively (Chromium); a second finger and a pinch
+ * arrive as distinct pointers; the screencast shows a compositor animation
+ * advancing through a blocked main thread while a rAF animation freezes;
+ * the trace counts zero Layout for a transform animation and one per frame
+ * for a `top` animation, and none from the harness's own animation recorder
+ * while an anchored element's composited animation runs (a page that asks
+ * for a frame every frame lays it out in each); the long-task log records
+ * the page's own long task but not a DevTools evaluate, which the trace
+ * counts; sampled curves
+ * match the oracles, individual transform properties included; a sample at
* an end reports the time it was read at; holding takes only running
* document-timeline animations, each at its own offset, holds each where it
* was read, adds a second hold to the held set without moving the first
- * hold's times, drops one the page cancels, and releases only them;
- * storyboards write a sheet and a trace that follows the curve, an endless
- * animation does not set their length, and a photograph Chromium returns
- * empty is taken again two frames later; a touch filmstrip keeps scripted
- * event times while a handler clock sees its pacing; the timer gate holds a
- * component timer until the filmstrip is done, drops callbacks the page
- * cancels, stamps held frames with the time they run, and leaves the
- * harness its own frames.
+ * hold's times, drops one the page cancels, and releases only them; the
+ * animation-state waits report a running transition and its end, and judge
+ * rest by presented values even while an animation holds its end, and a
+ * watch taken on first contact ignores an animation already running and
+ * keeps the start of one the page cancels when it ends, and the recorder
+ * reads only at CSS starts while a rendering trace runs and catches up
+ * after it;
+ * storyboards write a
+ * sheet and a trace that follows the curve, an endless animation does not
+ * set their length, and a photograph Chromium returns empty is taken again
+ * two frames later; a touch filmstrip keeps scripted event times while a
+ * handler clock sees its pacing; the timer gate holds a component timer
+ * until the filmstrip is done, drops callbacks the page cancels, stamps held
+ * frames with the time they run, and leaves the harness its own frames; a
+ * cast filmstrip keeps exactly the presented frames of its window, labelled
+ * from its zero, as PNG.
* @position The harness's own test. A component spec trusts these
* instruments; this file is why it may.
*/
+import fs from 'node:fs';
+import path from 'node:path';
import {expect, test, type Page} from '@playwright/test';
import {
animationStoryboard,
+ castStoryboard,
+ blockMainThread,
+ busyWindowProof,
compareCurve,
+ countBetween,
cubicBezier,
curveOf,
drag,
@@ -37,28 +57,46 @@ import {
freezeTimers,
holdAnimations,
installInputLog,
+ installLongTaskLog,
installTimerGate,
+ markElement,
merge,
parseTransform,
PARTIAL_LIFT_SKIP,
pinch,
readInputLog,
+ readLongTasks,
releaseAnimations,
sampleCurve,
+ sampleRects,
seekAnimations,
springStep,
+ startCompositorTrace,
+ startScreencast,
Storyboard,
tap,
thawTimers,
timeline,
touchDriver,
touchStoryboard,
+ traceRendering,
+ trackMarker,
waitForAnimation,
waitForRest,
watchAnimations,
withFinger,
} from './index';
+// An element positioned against an anchor: a composited animation of it lays
+// out in every main-thread frame, so it shows any per-frame main-thread work.
+const ANCHORED = `
+
+open
`;
+
const FIXTURE = `
+
`;
+
+async function busyFixture(page: Page) {
+ await page.route('http://busy.test/', route =>
+ route.fulfill({contentType: 'text/html', body: BUSY_FIXTURE}),
+ );
+ await page.goto('http://busy.test/');
+}
+
// A real navigation (not setContent, whose document.open() erases the window
// listeners the input log installs).
async function fixture(page: Page) {
@@ -242,6 +298,894 @@ test.describe('touch input', () => {
});
});
+test.describe('frame evidence', () => {
+ test('a compositor animation advances every frame through a blocked main thread; a rAF one freezes, whatever the screencast rate', async ({
+ page,
+ }, testInfo) => {
+ await busyFixture(page);
+ const box = page.locator('#box');
+ await markElement(box, {mode: 'outline'});
+
+ const run = async (driver: 'compositor' | 'raf', everyNthFrame = 1) => {
+ await box.evaluate((el, how) => {
+ el.getAnimations().forEach(a => a.cancel());
+ el.style.transform = 'none';
+ if (how === 'compositor') {
+ el.animate(
+ [{transform: 'translateY(0px)'}, {transform: 'translateY(560px)'}],
+ {duration: 1600, easing: 'linear'},
+ );
+ } else {
+ const start = performance.now();
+ const step = (now: number) => {
+ const p = Math.min(1, (now - start) / 1600);
+ el.style.transform = `translateY(${560 * p}px)`;
+ if (p < 1) {
+ requestAnimationFrame(step);
+ }
+ };
+ requestAnimationFrame(step);
+ }
+ }, driver);
+ const cast = await startScreencast(page, {everyNthFrame});
+ await page.waitForTimeout(200);
+ const window = await blockMainThread(page, 700);
+ await page.waitForTimeout(200);
+ const tracked = await trackMarker(page, await cast.stop());
+ return busyWindowProof(tracked, window, {axis: 'y'});
+ };
+
+ const compositor = await run('compositor');
+ testInfo.annotations.push({
+ type: 'busy-main-thread compositor',
+ description: compositor.summary,
+ });
+ expect(compositor.verdict.failures, compositor.summary).toEqual([]);
+ expect(compositor.monotonic).toBe(true);
+ // Resolvable on the cast's grid: two position steps or more per frame.
+ expect(compositor.notes, compositor.summary).toEqual([]);
+ expect(compositor.pxPerFrame).toBeGreaterThanOrEqual(2 * compositor.stepPx);
+
+ const raf = await run('raf');
+ testInfo.annotations.push({
+ type: 'busy-main-thread rAF control',
+ description: raf.summary,
+ });
+ // Frozen for the whole block: no presented frame moved (the compositor
+ // sends none at all when nothing on screen changes), and the verdict that
+ // passes the compositor animation fails it on every criterion.
+ expect(raf.changed).toBe(0);
+ expect(raf.longestStallMs).toBeGreaterThan(600);
+ expect(raf.verdict.pass).toBe(false);
+ expect(raf.verdict.failures.join('\n')).toMatch(/longest stall/);
+ expect(raf.verdict.failures.join('\n')).toMatch(/expected frames moved/);
+
+ // The verdict judges the frames the screencast delivered, not its rate:
+ // at one frame in six (a loaded machine's ~100 ms), the compositor
+ // animation still passes and the rAF one still fails.
+ const slow = await run('compositor', 6);
+ expect(slow.cadenceMs, slow.summary).toBeGreaterThan(60);
+ expect(slow.verdict.failures, slow.summary).toEqual([]);
+ const slowRaf = await run('raf', 6);
+ expect(slowRaf.verdict.pass, slowRaf.summary).toBe(false);
+ expect(slowRaf.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ test('frames the screencast skips while the compositor presents them are not a stall; a frozen animation still fails with the compositor record', async ({
+ page,
+ browserName,
+ }, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'compositor traces are Chromium-only (README: engine limits)',
+ );
+ await busyFixture(page);
+ const box = page.locator('#box');
+ await markElement(box, {mode: 'outline'});
+ const run = async (driver: 'compositor' | 'raf') => {
+ await box.evaluate((el, how) => {
+ el.getAnimations().forEach(a => a.cancel());
+ el.style.transform = 'none';
+ if (how === 'compositor') {
+ el.animate(
+ [{transform: 'translateY(0px)'}, {transform: 'translateY(560px)'}],
+ {duration: 1600, easing: 'linear'},
+ );
+ } else {
+ const start = performance.now();
+ const step = (now: number) => {
+ const p = Math.min(1, (now - start) / 1600);
+ el.style.transform = `translateY(${560 * p}px)`;
+ if (p < 1) {
+ requestAnimationFrame(step);
+ }
+ };
+ requestAnimationFrame(step);
+ }
+ }, driver);
+ const cast = await startScreencast(page);
+ const compositor = await startCompositorTrace(page);
+ await page.waitForTimeout(200);
+ const window = await blockMainThread(page, 700);
+ await page.waitForTimeout(200);
+ const presented = await compositor.stop();
+ const tracked = await trackMarker(page, await cast.stop());
+ return {window, tracked, presented};
+ };
+
+ const moving = await run('compositor');
+ expect(moving.presented.length).toBeGreaterThan(0);
+ // The screencast as a loaded machine delivers it: four frames in a row
+ // skipped mid-block, which the compositor still presented.
+ const mid = moving.tracked.findIndex(f => f.t > moving.window.from + 350);
+ const skipped = moving.tracked.filter((_, i) => i < mid || i >= mid + 4);
+ const alone = busyWindowProof(skipped, moving.window, {axis: 'y'});
+ expect(alone.verdict.failures.join('\n'), alone.summary).toMatch(
+ /longest stall/,
+ );
+ const proof = busyWindowProof(skipped, moving.window, {
+ axis: 'y',
+ presented: moving.presented,
+ });
+ testInfo.annotations.push({
+ type: 'busy-main-thread compositor record',
+ description: proof.summary,
+ });
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.recorderSkipped).toBeGreaterThanOrEqual(4);
+
+ // A rAF animation presents no change for the whole block: the record
+ // excuses nothing, whatever the compositor drew meanwhile.
+ const frozen = await run('raf');
+ const still = busyWindowProof(frozen.tracked, frozen.window, {
+ axis: 'y',
+ presented: frozen.presented,
+ });
+ testInfo.annotations.push({
+ type: 'busy-main-thread rAF control, compositor record',
+ description: `${still.summary}; compositor frames inside the block: ${frozen.presented.filter(t => t > frozen.window.from && t < frozen.window.to).length}`,
+ });
+ expect(still.verdict.pass).toBe(false);
+ expect(still.recorderSkipped).toBe(0);
+ expect(still.verdict.failures.join('\n')).toMatch(/longest stall/);
+ });
+
+ test('a block that starts during a just-started transition still lets the compositor advance it', async ({
+ page,
+ }, testInfo) => {
+ // `during` blocks in the frame the transition has run 16 ms. In WebKit
+ // the transition reaches the compositor in that frame's rendering update,
+ // so a loop inside the rAF callback froze it (2 of 29 frames moved).
+ // Linear and longer than the block, so every frame of the block moves two
+ // position steps or more and the transition is still running when it
+ // ends. The cast shows the box at rest first, so a transition that reaches
+ // the screen after the block began is judged from there (onScreenFromMs).
+ await busyFixture(page);
+ const box = page.locator('#box');
+ await markElement(box, {mode: 'outline'});
+ const cast = await startScreencast(page);
+ await expect.poll(() => cast.frameCount()).toBeGreaterThan(0);
+ await box.evaluate(el => {
+ el.style.transition = 'transform 1600ms linear';
+ el.getBoundingClientRect();
+ el.style.transform = 'translateY(560px)';
+ });
+ const window = await blockMainThread(page, 700, {
+ during: box,
+ minProgressMs: 16,
+ });
+ await waitForRest(box);
+ const tracked = await trackMarker(page, await cast.stop());
+ const proof = busyWindowProof(tracked, window, {axis: 'y'});
+ testInfo.annotations.push({
+ type: 'busy-main-thread transition',
+ description: proof.summary,
+ });
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.monotonic).toBe(true);
+ });
+
+ test('a block never starts on an animation that is not on the compositor yet', async ({
+ page,
+ }, testInfo) => {
+ // An animation created in the frame the helper looks is still pending (not
+ // committed to the compositor). A block that started on it then froze it
+ // in Chromium: no presented frame moved.
+ await busyFixture(page);
+ const box = page.locator('#box');
+ await markElement(box, {mode: 'outline'});
+ await box.evaluate(el => {
+ el.style.willChange = 'transform';
+ });
+ const cast = await startScreencast(page);
+ // A rAF loop registered before the helper's tick runs ahead of it in every
+ // frame; on its 12th frame it creates the animation, and the helper's tick
+ // looks in that same frame.
+ await box.evaluate(el => {
+ let n = 0;
+ const loop = () => {
+ n += 1;
+ if (n === 12) {
+ el.animate(
+ [{transform: 'translateY(0px)'}, {transform: 'translateY(560px)'}],
+ {duration: 1600, easing: 'linear'},
+ );
+ return;
+ }
+ requestAnimationFrame(loop);
+ };
+ requestAnimationFrame(loop);
+ });
+ const window = await blockMainThread(page, 700, {
+ during: box,
+ minProgressMs: 0,
+ });
+ await waitForRest(box);
+ const tracked = await trackMarker(page, await cast.stop());
+ const proof = busyWindowProof(tracked, window, {axis: 'y'});
+ testInfo.annotations.push({
+ type: 'busy-main-thread pending animation',
+ description: proof.summary,
+ });
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.monotonic).toBe(true);
+ });
+
+ test('in the WebKit container, compiled shaders outlive the run', async ({
+ browser,
+ }, testInfo) => {
+ // The official Playwright image keeps its browsers here.
+ test.skip(
+ testInfo.project.name !== 'webkit' ||
+ process.env.PLAYWRIGHT_BROWSERS_PATH !== '/ms-playwright',
+ 'runs inside webkit-container.mjs',
+ );
+ // A cache inside the container dies with it: every run then compiled each
+ // shader again, 450–700 ms in the first frame of a blurred layer.
+ const dir = process.env.MESA_SHADER_CACHE_DIR;
+ expect(dir, 'MESA_SHADER_CACHE_DIR names the host-kept cache').toBeTruthy();
+ // Written on the host by the script before the container starts.
+ expect(
+ fs.readFileSync(path.join(dir ?? '', 'ASTRYX-SHADER-CACHE'), 'utf8'),
+ ).toContain('playwright');
+ // Mesa writes what it compiles there once a page draws a blurred layer.
+ // Earlier runs have filled the cache already, so this run's browser gets
+ // an empty directory beside them, in the same host-kept mount, and the
+ // test watches its own writes arrive.
+ const fresh = fs.mkdtempSync(path.join(dir ?? '', 'self-test-'));
+ try {
+ const own = await browser.browserType().launch({
+ env: {...process.env, MESA_SHADER_CACHE_DIR: fresh},
+ });
+ try {
+ const page = await own.newPage();
+ await page.setContent(
+ '
',
+ );
+ await page.evaluate(
+ () =>
+ document
+ .getElementById('glass')
+ ?.animate([{scale: '1'}, {scale: '0.9'}], {duration: 200})
+ .finished,
+ );
+ } finally {
+ await own.close();
+ }
+ expect(fs.readdirSync(fresh, {recursive: true})).not.toEqual([]);
+ } finally {
+ fs.rmSync(fresh, {recursive: true, force: true});
+ }
+ });
+
+ test('rect sampling reads one rect per animation frame while the main thread is free', async ({
+ page,
+ browserName,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ await box.evaluate(el => {
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(200px)'}],
+ {duration: 600, easing: 'linear'},
+ );
+ });
+ const samples = await sampleRects(box, 400);
+ const xs = samples.map(s => s.box?.x ?? NaN);
+ const gaps = samples
+ .slice(1)
+ .map((s, i) => s.t - samples[i].t)
+ .sort((a, b) => a - b);
+ const cadence = gaps[Math.floor(gaps.length / 2)];
+ expect(cadence).toBeLessThan(34);
+ expect(samples.length).toBeGreaterThanOrEqual(10);
+ if (browserName === 'chromium') {
+ // One sample per presented frame at 60 Hz. (Headless WebKit's animation
+ // frames are irregular, so only the cadence is checked there.)
+ expect(samples.length).toBeGreaterThanOrEqual(20);
+ }
+ expect(xs.every((x, i) => i === 0 || x >= xs[i - 1])).toBe(true);
+ expect(xs.at(-1) ?? 0).toBeGreaterThan(xs[0] + 80);
+ });
+
+ test('the trace counts no Layout for a transform animation and one per frame for `top`', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await fixture(page);
+ const box = page.locator('#box');
+ // Count the animation's steady middle: starting and ending it may lay out once each.
+ const animate = async (property: 'transform' | 'top') => {
+ let started = 0;
+ const trace = await traceRendering(page, async () => {
+ started = await box.evaluate((el, prop) => {
+ const keyframes =
+ prop === 'transform'
+ ? [
+ {transform: 'translateY(0px)'},
+ {transform: 'translateY(200px)'},
+ ]
+ : [{top: '360px'}, {top: '560px'}];
+ el.animate(keyframes, {duration: 600});
+ return performance.timeOrigin + performance.now();
+ }, property);
+ await page.waitForTimeout(700);
+ });
+ return countBetween(trace, started + 100, started + 500);
+ };
+ const transform = await animate('transform');
+ const top = await animate('top');
+ expect(transform.Layout ?? 0).toBe(0);
+ expect(transform.Paint ?? 0).toBe(0);
+ // ~24 frames in 400 ms: one layout per frame.
+ expect(top.Layout ?? 0).toBeGreaterThan(18);
+ });
+
+ test("the trace counts no Layout from the harness's own animation recorder, which stands down while it runs", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ // The recorder runs, as in any spec that waited for an animation first.
+ await waitForRest(pop);
+ const watch = await watchAnimations(pop);
+ const middle = async (askEveryFrame: boolean) => {
+ let started = 0;
+ const trace = await traceRendering(page, async () => {
+ started = await pop.evaluate((el, every) => {
+ const w = window as unknown as {stop?: boolean};
+ w.stop = false;
+ if (every) {
+ const ask = () => {
+ if (!w.stop) {
+ requestAnimationFrame(ask);
+ }
+ };
+ requestAnimationFrame(ask);
+ }
+ el.animate(
+ [
+ {transform: 'translateY(0px)', opacity: 1},
+ {transform: 'translateY(100px)', opacity: 0.5},
+ ],
+ {duration: 600},
+ );
+ return performance.timeOrigin + performance.now();
+ }, askEveryFrame);
+ await page.waitForTimeout(700);
+ await page.evaluate(() => {
+ (window as unknown as {stop?: boolean}).stop = true;
+ });
+ });
+ // The steady middle: starting and ending it may lay out once each.
+ return countBetween(trace, started + 100, started + 500);
+ };
+ expect((await middle(false)).Layout ?? 0).toBe(0);
+ // Control: a page that asks for a frame every frame lays it out in each.
+ expect((await middle(true)).Layout ?? 0).toBeGreaterThan(18);
+ // Nothing the traces ran went unrecorded.
+ const started = await watch.started();
+ expect(started.map(a => a.durationMs)).toEqual([600, 600]);
+ });
+
+ test('a waitForRest awaited inside a traced body stands down too, so the trace counts no Layout from it', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ let started = 0;
+ const trace = await traceRendering(page, async () => {
+ started = await pop.evaluate(el => {
+ el.animate(
+ [
+ {transform: 'translateY(0px)', opacity: 1},
+ {transform: 'translateY(100px)', opacity: 0.5},
+ ],
+ {duration: 600},
+ );
+ return performance.timeOrigin + performance.now();
+ });
+ // A per-frame wait here would make every frame a main-thread frame.
+ await waitForRest(pop);
+ });
+ expect(countBetween(trace, started + 100, started + 500).Layout ?? 0).toBe(
+ 0,
+ );
+ // It still waited for the curve to end.
+ expect(trace.window.to - started).toBeGreaterThanOrEqual(590);
+ });
+
+ test('a waitForAnimation or watch.started() awaited inside a traced body stands down too, so the trace counts no Layout from it', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ const watch = await watchAnimations(pop);
+ let started = 0;
+ let waited: {durationMs: number}[] = [];
+ let watched: {durationMs: number}[] = [];
+ const trace = await traceRendering(page, async () => {
+ started = await pop.evaluate(el => {
+ el.animate(
+ [
+ {transform: 'translateY(0px)', opacity: 1},
+ {transform: 'translateY(100px)', opacity: 0.5},
+ ],
+ {duration: 600},
+ );
+ return performance.timeOrigin + performance.now();
+ });
+ // Both poll until 450 ms of the curve has played, across the steady
+ // middle; a read of the page's animations each time would lay it out.
+ waited = await waitForAnimation(pop, {minProgressMs: 450});
+ watched = await watch.started({minProgressMs: 450});
+ await page.waitForTimeout(200);
+ });
+ expect(countBetween(trace, started + 100, started + 500).Layout ?? 0).toBe(
+ 0,
+ );
+ // Each still answered with the animation once 450 ms of it had played.
+ expect(waited.map(a => a.durationMs)).toEqual([600]);
+ expect(watched.map(a => a.durationMs)).toEqual([600]);
+ expect(trace.window.to - started).toBeGreaterThanOrEqual(590);
+ });
+
+ test('a waitForRest awaited inside a traced body waits for an animation the action starts two frames later', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ const trace = await traceRendering(page, async () => {
+ // The action starts the animation two frames later, as a component's
+ // effect often does.
+ await pop.evaluate(el => {
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ (window as unknown as {__started: number}).__started =
+ performance.timeOrigin + performance.now();
+ el.animate(
+ [
+ {transform: 'translateY(0px)'},
+ {transform: 'translateY(100px)'},
+ ],
+ {duration: 600},
+ );
+ }),
+ );
+ });
+ await waitForRest(pop);
+ });
+ const started = await page.evaluate(
+ () => (window as unknown as {__started?: number}).__started ?? null,
+ );
+ // The traced window holds the whole animation.
+ expect(started).not.toBeNull();
+ expect(trace.window.to - (started as number)).toBeGreaterThanOrEqual(590);
+ });
+
+ test('a waitForRest awaited inside a traced body waits for a run going backward to its end, and no longer', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ // How long a traced waitForRest holds after a 600 ms move starts.
+ const traced = async (reverse: boolean, endDelay = 0) => {
+ let started = 0;
+ const trace = await traceRendering(page, async () => {
+ started = await pop.evaluate(
+ (el, {reverse, endDelay}) => {
+ const run = el.animate(
+ [
+ {transform: 'translateY(0px)'},
+ {transform: 'translateY(100px)'},
+ ],
+ {duration: 600, endDelay},
+ );
+ if (reverse) {
+ // Its current time falls from its end time to 0.
+ run.reverse();
+ }
+ return performance.timeOrigin + performance.now();
+ },
+ {reverse, endDelay},
+ );
+ await waitForRest(pop);
+ });
+ await waitForRest(pop);
+ return trace.window.to - started;
+ };
+ // Reversed with a 200 ms end delay: the move plays from 200 to 800 ms.
+ expect(await traced(true, 200)).toBeGreaterThanOrEqual(790);
+ // A reversed run is waited for as long as the same run forward, not
+ // twice as long.
+ const forward = await traced(false);
+ const backward = await traced(true);
+ expect(backward).toBeGreaterThanOrEqual(590);
+ expect(backward).toBeLessThan(forward * 1.5);
+ });
+
+ test('a waitForRest awaited inside a traced body runs on the real timers, so a frozen timer gate cannot hold it', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ const pop = page.locator('#pop');
+ await waitForRest(pop);
+ await installTimerGate(page);
+ await freezeTimers(page);
+ let outcome = '';
+ await traceRendering(page, async () => {
+ await pop.evaluate(el => {
+ el.animate(
+ [{transform: 'translateY(0px)'}, {transform: 'translateY(100px)'}],
+ {duration: 300},
+ );
+ });
+ // Held by the gate, the wait would neither resolve nor reach its
+ // deadline: the race reads that as "held".
+ outcome = await Promise.race([
+ waitForRest(pop, {timeout: 2000}).then(
+ () => 'rested',
+ () => 'rejected',
+ ),
+ new Promise(resolve => setTimeout(() => resolve('held'), 4000)),
+ ]);
+ });
+ await thawTimers(page);
+ expect(outcome).toBe('rested');
+ });
+
+ test('inside a trace, waitForRest rests beside a scroll-timeline animation', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await fixture(page);
+ const scroller = page.locator('#scroller');
+ await waitForRest(scroller);
+ let outcome = '';
+ await traceRendering(page, async () => {
+ // A row driven by its scroller's timeline: it moves only on scroll.
+ await scroller.evaluate(el => {
+ const row = el.firstElementChild as HTMLElement;
+ row.animate([{opacity: 0.5}, {opacity: 1}], {
+ timeline: new ScrollTimeline({source: el}),
+ });
+ });
+ outcome = await waitForRest(scroller, {timeout: 2000}).then(
+ () => 'rested',
+ (error: Error) => error.message,
+ );
+ });
+ expect(outcome).toBe('rested');
+ });
+
+ test('a CSS transition and animation that start and end inside a trace are reported, and lay out nothing in between', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await page.route('http://anchored.test/', route =>
+ route.fulfill({contentType: 'text/html', body: ANCHORED}),
+ );
+ await page.goto('http://anchored.test/');
+ await page.addStyleTag({
+ content:
+ '@keyframes harness-fade { from { opacity: 1 } to { opacity: 0.6 } }',
+ });
+ const pop = page.locator('#pop');
+ // The recorder runs, and a watch is taken before the trace.
+ await waitForRest(pop);
+ const watch = await watchAnimations(pop);
+ let started = 0;
+ const trace = await traceRendering(page, async () => {
+ started = await pop.evaluate(el => {
+ const pop = el as HTMLElement;
+ pop.style.transition = 'transform 400ms linear';
+ void pop.offsetWidth;
+ pop.style.transform = 'translateY(100px)';
+ pop.style.animation = 'harness-fade 400ms linear';
+ return performance.timeOrigin + performance.now();
+ });
+ await page.waitForTimeout(600);
+ });
+ // Its reads at the two starts fall before the steady middle.
+ expect(countBetween(trace, started + 100, started + 300).Layout ?? 0).toBe(
+ 0,
+ );
+ const ended = await watch.started({timeout: 1_000});
+ expect(ended.map(a => a.kind).sort()).toEqual([
+ 'CSSAnimation',
+ 'CSSTransition',
+ ]);
+ expect(ended.every(a => a.finishedAt != null)).toBe(true);
+ });
+
+ test('the compositor record refuses another open page, whose frames it could not tell apart', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'the compositor record is a Chromium trace (README: engine limits)',
+ );
+ await fixture(page);
+ // Another page animating: its presented frames would be credited to
+ // this one, so the record refuses to start.
+ const other = await page.context().newPage();
+ await other.setContent(
+ '
',
+ );
+ await expect(startCompositorTrace(page)).rejects.toThrow(
+ /another page is open as the trace starts/,
+ );
+ await other.close();
+ // A page opened mid-trace: stop() refuses too, whether it is still open
+ // or closed again before the record stops.
+ const record = await startCompositorTrace(page);
+ const late = await page.context().newPage();
+ await expect(record.stop()).rejects.toThrow(
+ /another page opened during the record/,
+ );
+ await late.close();
+ const brief = await startCompositorTrace(page);
+ const spinner = await page.context().newPage();
+ await spinner.setContent(
+ '
',
+ );
+ await page.waitForTimeout(200);
+ await spinner.close();
+ await expect(brief.stop()).rejects.toThrow(
+ /another page opened during the record/,
+ );
+ // In another context too.
+ const browser = page.context().browser();
+ if (browser != null) {
+ const elsewhere = await startCompositorTrace(page);
+ const context = await browser.newContext();
+ await (await context.newPage()).close();
+ await context.close();
+ await expect(elsewhere.stop()).rejects.toThrow(
+ /another page opened during the record/,
+ );
+ }
+ // Alone, it records.
+ const alone = await startCompositorTrace(page);
+ await page.waitForTimeout(100);
+ await expect(alone.stop()).resolves.toBeInstanceOf(Array);
+ });
+
+ test('the long-task log fails closed when it never ran on the document', async ({
+ page,
+ }) => {
+ // No installLongTaskLog before navigating: an empty answer would read as
+ // "no long task", so it throws instead.
+ await fixture(page);
+ await expect(readLongTasks(page)).rejects.toThrow(
+ /not running on this document/,
+ );
+ });
+
+ test("the long-task log records the page's own long task but not a DevTools evaluate, which the trace reports apart", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'the Long Tasks API and rendering traces are Chromium-only',
+ );
+ await installLongTaskLog(page);
+ await fixture(page);
+ // The page's own task: a timer that spins 120 ms.
+ const own = await page.evaluate(
+ () =>
+ new Promise<{from: number; to: number}>(resolve => {
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 120;
+ while (performance.now() < end) {
+ // spin
+ }
+ resolve({from, to: performance.timeOrigin + performance.now()});
+ }, 0);
+ }),
+ );
+ await frames(page, 2);
+ const recorded = await readLongTasks(page, own);
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0].durationMs).toBeGreaterThanOrEqual(110);
+ // A DevTools evaluate that spins 300 ms: the trace reports it apart from
+ // the page's long tasks, and the log never sees it.
+ let block = {from: 0, to: 0};
+ const trace = await traceRendering(page, async () => {
+ block = await blockMainThread(page, 300);
+ });
+ await frames(page, 2);
+ const inBlock = (t: {start: number}) =>
+ t.start < block.to && t.start >= block.from - 20;
+ expect(
+ trace.devtoolsTasks.some(t => t.durationMs >= 290 && inBlock(t)),
+ ).toBe(true);
+ expect(trace.longTasks.filter(inBlock)).toEqual([]);
+ expect(await readLongTasks(page, block)).toEqual([]);
+ });
+
+ test("a harness read inside a trace is not the page's long task, while a test's own evaluate is, whether it calls the page directly or sets it off", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ // Enough animated rows that describing their keyframes takes a DevTools
+ // task over 50 ms.
+ const rows = Array.from(
+ {length: 1200},
+ (_, i) => `row ${i}
`,
+ ).join('');
+ await page.setContent(
+ `slow ${rows}
`,
+ );
+ const slow = page.locator('#slow');
+ await slow.evaluate(el =>
+ el.addEventListener('click', () => {
+ const end = performance.now() + 60;
+ while (performance.now() < end) {
+ // spin
+ }
+ }),
+ );
+ // Page code a test can call directly, as through a story's own API.
+ await page.evaluate(() => {
+ (window as unknown as {pageWork: (ms: number) => void}).pageWork = (
+ ms: number,
+ ) => {
+ const end = performance.now() + ms;
+ while (performance.now() < end) {
+ // spin
+ }
+ };
+ });
+ await frames(page, 3);
+ const now = () =>
+ page.evaluate(() => performance.timeOrigin + performance.now());
+ const read = {from: 0, to: 0};
+ const click = {from: 0, to: 0};
+ const direct = {from: 0, to: 0};
+ let timer = {from: 0, to: 0};
+ const trace = await traceRendering(page, async () => {
+ read.from = await now();
+ await waitForAnimation(page.locator('#list'));
+ read.to = await now();
+ // On a slow machine each frame of 1,200 running rows is a long task of
+ // the page's own; the windows below hold only their own work.
+ await page.evaluate(() => document.getElementById('list')?.remove());
+ await frames(page, 2);
+ // The page's own task: a timer that spins 60 ms.
+ timer = await page.evaluate(
+ () =>
+ new Promise<{from: number; to: number}>(resolve => {
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 60;
+ while (performance.now() < end) {
+ // spin
+ }
+ resolve({from, to: performance.timeOrigin + performance.now()});
+ }, 0);
+ }),
+ );
+ // Page script run inside a DevTools evaluate: a 60 ms click handler.
+ click.from = await now();
+ await slow.evaluate(el => (el as HTMLElement).click());
+ click.to = await now();
+ // Page code a test's evaluate calls directly: 60 ms of the page's work.
+ direct.from = await now();
+ await page.evaluate(() =>
+ (window as unknown as {pageWork: (ms: number) => void}).pageWork(60),
+ );
+ direct.to = await now();
+ });
+ const within = (w: {from: number; to: number}) => (t: {start: number}) =>
+ t.start >= w.from - 20 && t.start < w.to;
+ // The read itself is set apart. The rows' frames around it may be long
+ // tasks too, the page's own: they stay in longTasks.
+ expect(trace.devtoolsTasks.some(within(read))).toBe(true);
+ expect(
+ trace.longTasks.some(t => within(timer)(t) && t.durationMs >= 55),
+ ).toBe(true);
+ expect(
+ trace.longTasks.some(t => within(click)(t) && t.durationMs >= 55),
+ ).toBe(true);
+ expect(
+ trace.longTasks.some(t => within(direct)(t) && t.durationMs >= 55),
+ ).toBe(true);
+ expect(trace.devtoolsTasks.filter(within(direct))).toEqual([]);
+ });
+});
+
test.describe('curve sampling', () => {
test('a CSS transition samples onto its cubic-bezier to 0.05 px', async ({
page,
@@ -961,6 +1905,91 @@ test.describe('animation state', () => {
expect(started.map(a => a.durationMs)).toEqual([300]);
});
+ test('while a rendering trace runs the recorder reads only at CSS starts, and catches up after it', async ({
+ page,
+ }) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ const watch = await watchAnimations(box);
+ // Counts the recorder's reads of the page's animations (each one flushes
+ // style): the whole document's, and one element's. Then flags a trace, as
+ // traceRendering does.
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __reads: number;
+ __elementReads: number;
+ __harnessRenderingTrace?: boolean;
+ };
+ w.__reads = 0;
+ w.__elementReads = 0;
+ const read = document.getAnimations.bind(document);
+ document.getAnimations = () => {
+ w.__reads += 1;
+ return read();
+ };
+ const readElement = Element.prototype.getAnimations;
+ Element.prototype.getAnimations = function (
+ this: Element,
+ ...args: Parameters
+ ) {
+ w.__elementReads += 1;
+ return readElement.apply(this, args);
+ };
+ w.__harnessRenderingTrace = true;
+ });
+ // During the trace: a CSS transition and a CSS animation that both end
+ // inside it, and a script animation still running after it.
+ await page.addStyleTag({
+ content:
+ '@keyframes harness-fade { from { opacity: 1 } to { opacity: 0.6 } }',
+ });
+ await box.evaluate(el => {
+ const box = el as HTMLElement;
+ box.style.transition = 'transform 120ms linear';
+ void box.offsetWidth;
+ box.style.transform = 'translateX(100px)';
+ box.style.animation = 'harness-fade 120ms linear';
+ box.animate([{scale: '1'}, {scale: '0.9'}], {duration: 600});
+ });
+ await page.waitForTimeout(300);
+ const reads = () =>
+ page.evaluate(() => (window as unknown as {__reads: number}).__reads);
+ // No frame loop: no document-wide read. One element read per CSS start
+ // event (transitionrun, transitionstart, animationstart), not per frame.
+ expect(await reads()).toBe(0);
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {__elementReads: number}).__elementReads,
+ ),
+ ).toBeLessThanOrEqual(3);
+ // The trace ends: traceRendering clears the flag and resumes the recorder,
+ // which reads again, every frame.
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __harnessRenderingTrace?: boolean;
+ __harnessAnimations: {resume: () => void};
+ };
+ w.__harnessRenderingTrace = false;
+ w.__harnessAnimations.resume();
+ });
+ await frames(page, 3);
+ expect(await reads()).toBeGreaterThan(2);
+ // All three are reported, the two CSS ones that ended inside the trace
+ // with the time they finished.
+ await waitForRest(box);
+ const started = await watch.started();
+ expect(started.map(a => a.kind).sort()).toEqual([
+ 'Animation',
+ 'CSSAnimation',
+ 'CSSTransition',
+ ]);
+ expect(
+ started
+ .filter(a => a.kind !== 'Animation')
+ .map(a => a.finishedAt != null),
+ ).toEqual([true, true]);
+ });
+
test('a wait answers with the animation the action started, not one that finished before it', async ({
page,
}) => {
@@ -1025,6 +2054,28 @@ test.describe('animation state', () => {
await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));
});
+ test('inside a rendering trace too, a watch taken right after a style change does not report that change', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ await fixture(page);
+ const box = page.locator('#box');
+ await waitForRest(box);
+ await traceRendering(page, async () => {
+ // The step: a transition the next style read creates.
+ await box.evaluate(el => {
+ el.style.transition = 'opacity 300ms linear';
+ el.style.opacity = '0.5';
+ });
+ const watch = await watchAnimations(box);
+ await expect(watch.started({timeout: 200})).rejects.toThrow(
+ /waitForAnimation/,
+ );
+ });
+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));
+ });
+
test('an exit whose element the page removes at its end is still reported', async ({
page,
}) => {
@@ -1076,6 +2127,43 @@ test.describe('animation state', () => {
}
});
+ test('inside a rendering trace too, a wait on an element no longer in the document rejects as missing', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'rendering traces are Chromium-only (README: engine limits)',
+ );
+ await fixture(page);
+ await page.evaluate(() => {
+ const gone = document.createElement('div');
+ gone.id = 'gone';
+ document.body.append(gone);
+ });
+ const gone = page.locator('#gone');
+ const watch = await watchAnimations(gone);
+ await page.evaluate(() => document.getElementById('gone')?.remove());
+ const outcomes: string[] = [];
+ await traceRendering(page, async () => {
+ for (const wait of [
+ () => watch.started({timeout: 300}),
+ () => waitForAnimation(gone, {timeout: 300}),
+ ]) {
+ outcomes.push(
+ await wait().then(
+ () => 'resolved',
+ (error: Error) => error.message,
+ ),
+ );
+ }
+ });
+ expect(outcomes).toHaveLength(2);
+ for (const outcome of outcomes) {
+ expect(outcome).toMatch(/not in the document/);
+ }
+ });
+
test('a watch reports only what started after it', async ({page}) => {
await fixture(page);
const box = page.locator('#box');
@@ -1429,6 +2517,34 @@ test.describe('storyboards', {tag: '@storyboard'}, () => {
}
});
+ test("the harness's own waits run on the real timers: a frozen timer gate holds neither blockMainThread's block nor sampleRects", async ({
+ page,
+ }) => {
+ await fixture(page);
+ await installTimerGate(page);
+ const box = page.locator('#box');
+ await box.evaluate(el => {
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(200px)'}],
+ {duration: 1_500, easing: 'linear'},
+ );
+ });
+ await freezeTimers(page);
+ // Settled, or still held after 5 s.
+ const within = (work: Promise) =>
+ Promise.race([
+ work.then(() => 'settled'),
+ new Promise(resolve =>
+ setTimeout(() => resolve('held'), 5_000),
+ ),
+ ]);
+ expect(
+ await within(blockMainThread(page, 100, {during: box, timeout: 2_000})),
+ ).toBe('settled');
+ expect(await within(sampleRects(box, 200))).toBe('settled');
+ await thawTimers(page);
+ });
+
test('the timer gate holds a component timer until the filmstrip is done', async ({
page,
}, testInfo) => {
@@ -1614,4 +2730,58 @@ test.describe('storyboards', {tag: '@storyboard'}, () => {
expect(state).toMatchObject({timer: false, frame: false});
expect(state.heldFor).toBeGreaterThanOrEqual(140);
});
+
+ test('a cast filmstrip keeps exactly the presented frames of its window, labelled from its zero', async ({
+ page,
+ }, testInfo) => {
+ await fixture(page);
+ const box = page.locator('#box');
+ // JPEG frames (WebKit's are always JPEG) take the conversion path.
+ const cast = await startScreencast(page, {format: 'jpeg'});
+ await box.evaluate(el =>
+ el.animate(
+ [{transform: 'translateX(0px)'}, {transform: 'translateX(200px)'}],
+ {duration: 600},
+ ),
+ );
+ await page.waitForTimeout(500);
+ const presented = await cast.stop();
+ expect(presented.length).toBeGreaterThan(8);
+ // A window of the middle frames, zeroed on one of them.
+ const zero = presented[2].t;
+ const from = presented[3].t;
+ const to = presented[presented.length - 3].t;
+ const inside = presented.filter(f => f.t >= from && f.t <= to);
+ const seen: number[] = [];
+ const film = await castStoryboard(page, presented, {
+ name: 'harness-self-test-cast',
+ zero,
+ from,
+ to,
+ data: t => {
+ seen.push(t);
+ return {t};
+ },
+ });
+ expect(film.frames.map(f => f.t)).toEqual(inside.map(f => f.t - zero));
+ expect(film.frames.map(f => f.label)).toEqual(
+ inside.map(f => `t=${(f.t - zero).toFixed(1)} ms`),
+ );
+ expect(seen).toEqual(inside.map(f => f.t));
+ // Every cell is a PNG, whatever the screencast delivered.
+ for (const frame of film.frames) {
+ expect([...frame.png.subarray(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]);
+ }
+ const files = await film.write(testInfo);
+ expect(files['sheet.png']).toMatch(/sheet\.png$/);
+ // A window with no presented frame in it films nothing.
+ const empty = await castStoryboard(page, presented, {
+ name: 'harness-self-test-cast-empty',
+ zero,
+ from: to + 1,
+ to: to + 2,
+ });
+ expect(empty.frames).toEqual([]);
+ await expect(empty.write(testInfo)).rejects.toThrow(/no frames/);
+ });
});
diff --git a/internal/interaction-harness/src/index.ts b/internal/interaction-harness/src/index.ts
index 537bfc4d4beca..7a45ff45dfe41 100644
--- a/internal/interaction-harness/src/index.ts
+++ b/internal/interaction-harness/src/index.ts
@@ -12,10 +12,13 @@
* SYNC: When a module is added, export it here and describe it in README.md.
*/
+export * from './busy';
export * from './curves';
+export * from './frames';
export * from './math';
export * from './output';
export * from './scripts';
export * from './story';
export * from './storyboard';
export * from './touch';
+export * from './trace';
diff --git a/internal/interaction-harness/src/story.ts b/internal/interaction-harness/src/story.ts
index 598f75d852cfe..cb57d59b50be2 100644
--- a/internal/interaction-harness/src/story.ts
+++ b/internal/interaction-harness/src/story.ts
@@ -6,7 +6,8 @@
* static server over a built Storybook
* @output `phone` (the touch-phone browser context every interaction proof
* runs in), `withStorybook` (serve the built Storybook for a spec file), and
- * `openStory` (load one story and wait until it has rendered).
+ * `openStory` (load one story, with Storybook's highlight module off, and
+ * wait until it has rendered).
* @position Stories are the reproduction path, as for every other browser
* check in this repository: a scenario used for verification is checked in,
* not built in a one-off page.
@@ -59,13 +60,47 @@ export function withStorybook(test: TestType): () => string {
};
}
-/** Loads a story in the page and waits for its first render, its fonts and two frames. */
+/** Pages whose Storybook highlight module `openStory` turned off. */
+const highlightOff = new WeakSet();
+
+export interface OpenStoryOptions {
+ /**
+ * Keeps Storybook's highlight module on. It is off by default: when on, it
+ * observes `#storybook-root` and, on every insertion, reads the computed
+ * style of every element on the page inside the inserting task, so a proof
+ * would measure Storybook as well as the component.
+ */
+ readonly storybookHighlight?: boolean;
+}
+
+/**
+ * Loads a story in the page and waits for its first render, its fonts and two
+ * frames. Storybook's highlight module is off (see `OpenStoryOptions`), and
+ * that is checked: its root element must be absent once the story renders.
+ */
export async function openStory(
page: Page,
origin: string,
storyId: string,
args?: Readonly>,
+ {storybookHighlight = false}: OpenStoryOptions = {},
): Promise {
+ if (storybookHighlight) {
+ if (highlightOff.has(page)) {
+ throw new Error(
+ "openStory: this page already turned Storybook's highlight module off; open the story in a new page to keep it on",
+ );
+ }
+ } else if (!highlightOff.has(page)) {
+ highlightOff.add(page);
+ // Storybook's highlight module returns at once when this is set before
+ // its preview runs.
+ await page.addInitScript(() => {
+ (
+ globalThis as unknown as {__STORYBOOK_HIGHLIGHT_INITIALIZED?: boolean}
+ ).__STORYBOOK_HIGHLIGHT_INITIALIZED = true;
+ });
+ }
const params = new URLSearchParams({id: storyId, viewMode: 'story'});
if (args != null) {
params.set(
@@ -86,6 +121,14 @@ export async function openStory(
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
});
+ if (
+ !storybookHighlight &&
+ (await page.locator('#storybook-highlights-root').count()) > 0
+ ) {
+ throw new Error(
+ "openStory: Storybook's highlight module is on (#storybook-highlights-root exists), so every insertion would also read the style of every element on the page; this Storybook may no longer read __STORYBOOK_HIGHLIGHT_INITIALIZED",
+ );
+ }
}
/** Resolves after `count` animation frames have been presented in the page. */
@@ -110,8 +153,9 @@ export async function frames(page: Page, count = 2): Promise {
// A held callback is queued under its timer or frame id, so the page's own
// clearTimeout and cancelAnimationFrame still cancel it while frozen; a held
-// frame callback gets the time it actually runs at. `frame` stays the real
-// requestAnimationFrame, for the harness's own waits.
+// frame callback gets the time it actually runs at. `frame` and `timeout`
+// stay the real requestAnimationFrame and setTimeout, for the harness's own
+// waits.
const TIMER_GATE = `(() => {
if (window.__harnessTimerGate) return;
const realTimeout = window.setTimeout.bind(window);
@@ -119,7 +163,7 @@ const TIMER_GATE = `(() => {
const realInterval = window.setInterval.bind(window);
const realFrame = window.requestAnimationFrame.bind(window);
const realCancelFrame = window.cancelAnimationFrame.bind(window);
- const gate = {frozen: false, queue: [], frame: realFrame};
+ const gate = {frozen: false, queue: [], frame: realFrame, timeout: realTimeout};
window.__harnessTimerGate = gate;
const drop = key => { gate.queue = gate.queue.filter(entry => entry.key !== key); };
window.setTimeout = (fn, ms, ...args) => {
diff --git a/internal/interaction-harness/src/storyboard.ts b/internal/interaction-harness/src/storyboard.ts
index 2dc22fdc8cf04..a49207c4f81c4 100644
--- a/internal/interaction-harness/src/storyboard.ts
+++ b/internal/interaction-harness/src/storyboard.ts
@@ -336,7 +336,8 @@ export interface TouchStoryboardOptions extends StoryboardOptions {
* photograph per event, about 100 ms between moves instead of the script's
* 16.7. Its release velocity is that much lower, so a flick that dismisses
* when played can settle back when filmed: a storyboard cannot show such a
- * gesture; record it in real time instead.
+ * gesture; record it in real time instead (`startScreencast`,
+ * `castStoryboard`).
*/
export async function touchStoryboard(
page: Page,
@@ -364,3 +365,65 @@ export async function touchStoryboard(
});
return storyboard;
}
+
+/**
+ * A filmstrip of screencast frames (real presented frames, e.g. the frames of
+ * a busy-main-thread window), labelled with their time relative to `zero`.
+ * Evidence for what the compositor presented, not a deterministic storyboard.
+ */
+export async function castStoryboard(
+ page: Page,
+ frames: readonly {
+ readonly t: number;
+ readonly data: string;
+ readonly format: 'png' | 'jpeg';
+ }[],
+ // A cast is already the screen's frames: no clip is applied to them.
+ options: Omit & {
+ readonly zero: number;
+ readonly from?: number;
+ readonly to?: number;
+ readonly data?: (t: number) => Readonly>;
+ },
+): Promise {
+ const storyboard = new Storyboard(page, options);
+ for (const frame of frames) {
+ if (options.from != null && frame.t < options.from) {
+ continue;
+ }
+ if (options.to != null && frame.t > options.to) {
+ continue;
+ }
+ const png =
+ frame.format === 'png'
+ ? Buffer.from(frame.data, 'base64')
+ : await toPng(page, frame.data);
+ const t = frame.t - options.zero;
+ storyboard.frames.push({
+ label: `t=${t.toFixed(1)} ms`,
+ t,
+ data: options.data?.(frame.t) ?? {},
+ png,
+ });
+ }
+ return storyboard;
+}
+
+async function toPng(page: Page, jpegBase64: string): Promise {
+ const scratch = await page.context().newPage();
+ try {
+ const url = await scratch.evaluate(async data => {
+ const bitmap = await createImageBitmap(
+ await (await fetch(`data:image/jpeg;base64,${data}`)).blob(),
+ );
+ const canvas = document.createElement('canvas');
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ canvas.getContext('2d')?.drawImage(bitmap, 0, 0);
+ return canvas.toDataURL('image/png');
+ }, jpegBase64);
+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');
+ } finally {
+ await scratch.close();
+ }
+}
diff --git a/internal/interaction-harness/src/storybook.interaction.browser.spec.ts b/internal/interaction-harness/src/storybook.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..a711feb62cb84
--- /dev/null
+++ b/internal/interaction-harness/src/storybook.interaction.browser.spec.ts
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file storybook.interaction.browser.spec.ts
+ * @input The built Storybook (`withStorybook`) and one of its stories
+ * @output `openStory` turns Storybook's highlight module off, so an insertion
+ * in a story carries no `getComputedStyle` scan of the page; with the module
+ * on (the control), every insertion carries one. Both engines; Chromium's
+ * trace also counts the style recalculations the scan forces
+ * @position Self-test for story.ts; it needs the built Storybook, as every
+ * component proof does
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {openStory, withStorybook} from './story';
+import {countBetween, traceRendering} from './trace';
+
+const storybook = withStorybook(test);
+
+/** Counts the page's `getComputedStyle` calls, from before Storybook loads. */
+function countStyleReads(): void {
+ const w = window as unknown as {__styleReads: number};
+ w.__styleReads = 0;
+ const read = window.getComputedStyle.bind(window);
+ window.getComputedStyle = ((element: Element, pseudo?: string | null) => {
+ w.__styleReads += 1;
+ return read(element, pseudo);
+ }) as typeof window.getComputedStyle;
+}
+
+/**
+ * Inserts an exit copy of the story's first element into `#storybook-root`,
+ * as an exit animation's copy is, lets the insertion's mutation microtasks run,
+ * and reports what ran between its marks.
+ */
+async function insertCopy(page: Page) {
+ return page.evaluate(async () => {
+ const w = window as unknown as {__styleReads: number};
+ const root = document.getElementById('storybook-root') as HTMLElement;
+ const reads = w.__styleReads;
+ const from =
+ performance.timeOrigin + performance.mark('copy:start').startTime;
+ const copy = (root.firstElementChild as HTMLElement).cloneNode(
+ true,
+ ) as HTMLElement;
+ copy.setAttribute('aria-hidden', 'true');
+ root.appendChild(copy);
+ // A MutationObserver's callback is a microtask the insertion queued:
+ // these run after it.
+ await Promise.resolve();
+ await Promise.resolve();
+ const to = performance.timeOrigin + performance.mark('copy:end').startTime;
+ const scanned = w.__styleReads - reads;
+ const elements = document.body.querySelectorAll('*').length;
+ copy.remove();
+ return {from, to, scanned, elements};
+ });
+}
+
+test("openStory turns Storybook's highlight module off: an insertion in a story carries no getComputedStyle scan of the page", async ({
+ page,
+ browserName,
+}) => {
+ // The insertion's reads in every engine, and in Chromium (whose trace the
+ // harness reads) the style recalculations between its marks.
+ const measure = async (p: Page) => {
+ if (browserName !== 'chromium') {
+ return {copy: await insertCopy(p), styleRecalc: null};
+ }
+ let copy = {from: 0, to: 0, scanned: 0, elements: 0};
+ const trace = await traceRendering(p, async () => {
+ copy = await insertCopy(p);
+ });
+ return {
+ copy,
+ styleRecalc:
+ countBetween(trace, copy.from, copy.to).UpdateLayoutTree ?? 0,
+ };
+ };
+ // The harness default.
+ await page.addInitScript(countStyleReads);
+ await openStory(page, storybook(), 'core-button--primary');
+ expect(await page.locator('#storybook-highlights-root').count()).toBe(0);
+ const off = await measure(page);
+ expect(off.copy.scanned).toBe(0);
+ if (off.styleRecalc != null) {
+ expect(off.styleRecalc).toBe(0);
+ }
+
+ // Control: Storybook's module kept on reads the style of every element on
+ // the page inside the inserting task.
+ const control = await page.context().newPage();
+ await control.addInitScript(countStyleReads);
+ await openStory(control, storybook(), 'core-button--primary', undefined, {
+ storybookHighlight: true,
+ });
+ expect(await control.locator('#storybook-highlights-root').count()).toBe(1);
+ const on = await measure(control);
+ expect(on.copy.scanned).toBeGreaterThanOrEqual(on.copy.elements);
+ if (on.styleRecalc != null) {
+ expect(on.styleRecalc).toBeGreaterThan(0);
+ }
+ await control.close();
+});
diff --git a/internal/interaction-harness/src/trace.ts b/internal/interaction-harness/src/trace.ts
new file mode 100644
index 0000000000000..ce6a3d853d2cd
--- /dev/null
+++ b/internal/interaction-harness/src/trace.ts
@@ -0,0 +1,466 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file trace.ts
+ * @input Uses a Playwright `Page` (Chromium: CDP `Tracing`) and the page's
+ * PerformanceObserver for long tasks
+ * @output `traceRendering` — counts of the main thread's rendering work
+ * (Layout, Paint, UpdateLayoutTree, PrePaint, …) between two marks — and
+ * `installLongTaskLog` / `readLongTasks`.
+ * @position The "no Layout/Paint during a transform/opacity animation" proof.
+ * A compositor animation costs the main thread nothing per frame; one that
+ * animates a layout property, or writes styles from JavaScript each frame,
+ * shows a Layout (and usually a Paint) per frame. Chromium only: WebKit
+ * exposes no comparable trace to Playwright.
+ *
+ * Counting is scoped to the renderer main thread that ran the page's own
+ * `performance.mark` calls, and to the time between the start and end marks,
+ * so other pages, the browser process and setup work are excluded.
+ *
+ * SYNC: Keep RENDERING_EVENTS equal to the README's list.
+ */
+
+import type {CDPSession, Page} from '@playwright/test';
+
+/**
+ * The mark a harness function puts on its own page-side work
+ * (`console.timeStamp('harness-read')` at the start of the function it
+ * evaluates in the page), so a trace can tell the harness's reads from page
+ * code a test's own evaluate runs.
+ */
+export const HARNESS_READ = 'harness-read';
+
+/** Trace events that run page script: a listener, a timer, a frame callback. */
+const PAGE_SCRIPT_EVENTS = new Set([
+ 'EventDispatch',
+ 'FunctionCall',
+ 'TimerFire',
+ 'FireAnimationFrame',
+ 'FireIdleCallback',
+]);
+
+/** Main-thread trace events that are rendering work, by their trace names. */
+export const RENDERING_EVENTS = [
+ 'UpdateLayoutTree', // style recalculation
+ 'Layout',
+ 'PrePaint',
+ 'Paint',
+ 'Layerize',
+ 'UpdateLayer',
+ 'ScrollLayer',
+ 'HitTest',
+] as const;
+
+export interface RenderingTrace {
+ /** Count per trace event name inside the window, on the page's main thread. */
+ readonly counts: Readonly>;
+ /** Shorthand for the four that matter most. */
+ readonly layout: number;
+ readonly paint: number;
+ readonly styleRecalc: number;
+ readonly prePaint: number;
+ /** Window length, ms. */
+ readonly durationMs: number;
+ /**
+ * The page's own main-thread tasks longer than 50 ms inside the window (long
+ * tasks), epoch ms. A task that ran a test's own DevTools command (a
+ * `page.evaluate`) is one, whether it calls page code directly or sets it
+ * off; only the harness's own marked reads are in `devtoolsTasks`.
+ */
+ readonly longTasks: readonly {
+ readonly start: number;
+ readonly durationMs: number;
+ }[];
+ /**
+ * Main-thread tasks longer than 50 ms inside the window that ran a DevTools
+ * command the harness marked as its own read (`HARNESS_READ`) and no page
+ * script, epoch ms: `waitForAnimation` describing every animation's
+ * keyframes, or `blockMainThread(page, ms)` without `during`.
+ */
+ readonly devtoolsTasks: readonly {
+ readonly start: number;
+ readonly durationMs: number;
+ }[];
+ /** Every counted rendering event with its epoch-ms time, for sub-window counts. */
+ readonly events: readonly {readonly name: string; readonly t: number}[];
+ /** The window, epoch ms on the page's clock. */
+ readonly window: {readonly from: number; readonly to: number};
+}
+
+/** Counts rendering events by name inside `[from, to]` (epoch ms). */
+export function countBetween(
+ trace: RenderingTrace,
+ from: number,
+ to: number,
+): Record {
+ const counts: Record = {};
+ for (const e of trace.events) {
+ if (e.t >= from && e.t <= to) {
+ counts[e.name] = (counts[e.name] ?? 0) + 1;
+ }
+ }
+ return counts;
+}
+
+interface TraceEvent {
+ name: string;
+ cat: string;
+ ph: string;
+ ts: number;
+ dur?: number;
+ pid: number;
+ tid: number;
+ args?: Record;
+}
+
+/**
+ * Traces the page while `body` runs and counts the rendering work its main
+ * thread did between a start mark (placed just before `body`) and an end mark
+ * (just after). The harness's animation recorder, `waitForRest`,
+ * `waitForAnimation` and a watch's `started()` stand down meanwhile, so a body
+ * may wait with any of them and add no frame of its own, with one gap: on a
+ * CSS `@keyframes` animation (and, for an unwatched `waitForAnimation`, a
+ * cancelled CSS transition) the wait reads its timing, which flushes that
+ * animation's style, so wait on such an animation with `waitForRest`, or
+ * after the trace. Taking a watch, or calling `waitForRest` while an
+ * animation already runs on the element, reads its animations once, which
+ * restyles it: do either before the window a proof counts.
+ */
+export async function traceRendering(
+ page: Page,
+ body: () => Promise,
+): Promise {
+ const cdp: CDPSession = await page.context().newCDPSession(page);
+ const events: TraceEvent[] = [];
+ cdp.on('Tracing.dataCollected', ({value}) => {
+ events.push(...(value as unknown as TraceEvent[]));
+ });
+ const complete = new Promise(resolve =>
+ cdp.once('Tracing.tracingComplete', () => resolve()),
+ );
+ await cdp.send('Tracing.start', {
+ transferMode: 'ReportEvents',
+ traceConfig: {
+ includedCategories: [
+ 'devtools.timeline',
+ 'disabled-by-default-devtools.timeline',
+ 'blink.user_timing',
+ 'toplevel',
+ ],
+ excludedCategories: ['*'],
+ },
+ });
+ const tag = `harness-${Math.random().toString(36).slice(2, 8)}`;
+ const mark = (name: string) =>
+ page.evaluate(
+ n => performance.timeOrigin + performance.mark(n).startTime,
+ name,
+ );
+ // The harness's animation recorder (curves.ts) runs a callback every frame,
+ // which makes each frame a main-thread one where Blink restyles every running
+ // animation's target (and lays out an anchored one), and it reads the page's
+ // animations, which flushes style: exactly what this counts. It stands down
+ // while this flag is set, a recorder the body itself starts included, and
+ // resumes once the trace ends.
+ const standDown = (on: boolean) =>
+ page.evaluate(value => {
+ const w = window as unknown as {
+ __harnessRenderingTrace?: boolean;
+ __harnessAnimations?: {resume?: () => void};
+ };
+ w.__harnessRenderingTrace = value;
+ if (!value) {
+ w.__harnessAnimations?.resume?.();
+ }
+ }, on);
+ await standDown(true);
+ let fromEpoch: number;
+ let toEpoch: number;
+ try {
+ fromEpoch = await mark(`${tag}:start`);
+ await body();
+ toEpoch = await mark(`${tag}:end`);
+ } finally {
+ // Its catch-up read lands after the end mark, outside the counted window.
+ // A failure here would hide the body's own error, which is the one to see.
+ await standDown(false).catch(() => {});
+ }
+ await cdp.send('Tracing.end');
+ await complete;
+ await cdp.detach().catch(() => {});
+
+ const start = events.find(e => e.name === `${tag}:start`);
+ const end = events.find(e => e.name === `${tag}:end`);
+ if (start == null || end == null) {
+ throw new Error('traceRendering: the window marks were not traced');
+ }
+ const onMain = (e: TraceEvent) =>
+ e.pid === start.pid &&
+ e.tid === start.tid &&
+ e.ts >= start.ts &&
+ e.ts <= end.ts;
+ // Trace time (µs, monotonic) -> epoch ms, anchored on the start mark.
+ const toEpochMs = (ts: number) => fromEpoch + (ts - start.ts) / 1000;
+ const counts: Record = {};
+ const counted: {name: string; t: number}[] = [];
+ for (const e of events) {
+ if (!onMain(e) || e.ph === 'E') {
+ continue;
+ }
+ if ((RENDERING_EVENTS as readonly string[]).includes(e.name)) {
+ counts[e.name] = (counts[e.name] ?? 0) + 1;
+ counted.push({name: e.name, t: toEpochMs(e.ts)});
+ }
+ }
+ // A task that ran a DevTools command received it over the DevTools
+ // session's pipe; page script it set off shows as its listener, timer or
+ // frame callback.
+ const main = events.filter(e => onMain(e) && e.ph !== 'E');
+ const longTasks: {start: number; durationMs: number}[] = [];
+ const devtoolsTasks: {start: number; durationMs: number}[] = [];
+ for (const task of main) {
+ if (task.name !== 'RunTask' || (task.dur ?? 0) <= 50_000) {
+ continue;
+ }
+ const end = task.ts + (task.dur ?? 0);
+ const inside = main.filter(
+ e => e !== task && e.ts >= task.ts && e.ts <= end,
+ );
+ const devtools = inside.some(
+ e =>
+ e.name === 'Receive mojo message' &&
+ (
+ e.args?.chrome_mojo_event_info as
+ {mojo_interface_tag?: unknown} | undefined
+ )?.mojo_interface_tag === 'blink.mojom.DevToolsSession',
+ );
+ // Only the harness's own reads are set apart: a test's evaluate may call
+ // page code directly, which leaves no listener or timer in the trace.
+ const harnessRead = inside.some(
+ e =>
+ e.name === 'TimeStamp' &&
+ (e.args?.data as {message?: unknown} | undefined)?.message ===
+ HARNESS_READ,
+ );
+ const pageScript = inside.some(e => PAGE_SCRIPT_EVENTS.has(e.name));
+ (devtools && harnessRead && !pageScript ? devtoolsTasks : longTasks).push({
+ start: toEpochMs(task.ts),
+ durationMs: (task.dur ?? 0) / 1000,
+ });
+ }
+ return {
+ counts,
+ layout: counts.Layout ?? 0,
+ paint: counts.Paint ?? 0,
+ styleRecalc: counts.UpdateLayoutTree ?? 0,
+ prePaint: counts.PrePaint ?? 0,
+ durationMs: (end.ts - start.ts) / 1000,
+ longTasks,
+ devtoolsTasks,
+ events: counted,
+ window: {from: fromEpoch, to: toEpoch},
+ };
+}
+
+/**
+ * The browser's open pages. The compositor record is browser-wide: its
+ * `Display::FrameDisplayed` events carry no page identity.
+ */
+function openPages(page: Page): Page[] {
+ const browser = page.context().browser();
+ return browser == null
+ ? page.context().pages()
+ : browser.contexts().flatMap(context => context.pages());
+}
+
+/**
+ * Watches for a page that opens while the record runs, in any context (it
+ * may close again before the record stops). Returns whether one opened.
+ */
+async function watchForOtherPages(
+ page: Page,
+): Promise<{stop(): Promise}> {
+ let opened = false;
+ const onPage = (other: Page) => {
+ if (other !== page) {
+ opened = true;
+ }
+ };
+ // The page's own context, through Playwright (a persistent context has no
+ // browser to ask).
+ page.context().on('page', onPage);
+ // Every context, through the browser's target discovery: a page in a
+ // context created during the record is a new target too.
+ let targets: CDPSession | null = null;
+ const browser = page.context().browser();
+ if (browser != null) {
+ try {
+ targets = await browser.newBrowserCDPSession();
+ const {targetInfos} = await targets.send('Target.getTargets');
+ const known = new Set(targetInfos.map(info => info.targetId));
+ targets.on('Target.targetCreated', ({targetInfo}) => {
+ if (targetInfo.type === 'page' && !known.has(targetInfo.targetId)) {
+ opened = true;
+ }
+ });
+ await targets.send('Target.setDiscoverTargets', {discover: true});
+ } catch {
+ targets = null;
+ }
+ }
+ return {
+ async stop() {
+ page.context().off('page', onPage);
+ await targets?.detach().catch(() => {});
+ return opened;
+ },
+ };
+}
+
+function assertOnlyPage(page: Page, when: string): void {
+ if (openPages(page).some(other => other !== page && !other.isClosed())) {
+ throw new Error(
+ `startCompositorTrace: another page is open ${when}; the compositor record is browser-wide (its frames carry no page identity), so another page's frames would be credited to this one`,
+ );
+ }
+}
+
+/**
+ * Records when the compositor presents each frame, for `busyWindowProof`'s
+ * `presented`: a Chromium trace of `Display::FrameDisplayed`, on the page
+ * clock. Start it with the screencast, before the block, and stop it after.
+ * Engines without a CDP trace (WebKit) resolve `stop()` to [], and the
+ * verdict then judges the screencast alone. It runs its own trace, so not
+ * inside `traceRendering`. The record is browser-wide, so it throws when
+ * another page is open as it starts or stops, or opened while it ran.
+ */
+export async function startCompositorTrace(
+ page: Page,
+): Promise<{stop(): Promise}> {
+ let cdp: CDPSession;
+ try {
+ cdp = await page.context().newCDPSession(page);
+ } catch {
+ return {stop: async () => []};
+ }
+ try {
+ assertOnlyPage(page, 'as the trace starts');
+ } catch (error) {
+ await cdp.detach().catch(() => {});
+ throw error;
+ }
+ const others = await watchForOtherPages(page);
+ const events: TraceEvent[] = [];
+ cdp.on('Tracing.dataCollected', ({value}) => {
+ events.push(...(value as unknown as TraceEvent[]));
+ });
+ const complete = new Promise(resolve =>
+ cdp.once('Tracing.tracingComplete', () => resolve()),
+ );
+ await cdp.send('Tracing.start', {
+ transferMode: 'ReportEvents',
+ traceConfig: {
+ includedCategories: [
+ 'disabled-by-default-display.framedisplayed',
+ 'blink.user_timing',
+ ],
+ excludedCategories: ['*'],
+ },
+ });
+ const tag = `harness-compositor-${Math.random().toString(36).slice(2, 8)}`;
+ const epoch = await page.evaluate(
+ n => performance.timeOrigin + performance.mark(n).startTime,
+ tag,
+ );
+ return {
+ async stop() {
+ await cdp.send('Tracing.end');
+ await complete;
+ await cdp.detach().catch(() => {});
+ if (await others.stop()) {
+ throw new Error(
+ "startCompositorTrace: another page opened during the record; the compositor record is browser-wide (its frames carry no page identity), so that page's frames would be credited to this one",
+ );
+ }
+ assertOnlyPage(page, 'as the trace stops');
+ const mark = events.find(e => e.name === tag);
+ if (mark == null) {
+ throw new Error('startCompositorTrace: the clock mark was not traced');
+ }
+ // Trace time (µs, monotonic) -> epoch ms, anchored on the mark.
+ return events
+ .filter(e => e.name === 'Display::FrameDisplayed')
+ .map(e => epoch + (e.ts - mark.ts) / 1000)
+ .sort((a, b) => a - b);
+ },
+ };
+}
+
+const LONG_TASK_SCRIPT = `(() => {
+ if (window.__harnessLongTasks) return;
+ const tasks = [];
+ const log = {tasks, supported: false};
+ window.__harnessLongTasks = log;
+ if (typeof PerformanceObserver === 'undefined' || !(PerformanceObserver.supportedEntryTypes || []).includes('longtask')) return;
+ try {
+ new PerformanceObserver(list => {
+ for (const entry of list.getEntries()) tasks.push({start: performance.timeOrigin + entry.startTime, durationMs: entry.duration, name: entry.name});
+ }).observe({type: 'longtask', buffered: true});
+ log.supported = true;
+ } catch {}
+})()`;
+
+/**
+ * Records every long task (> 50 ms) the page runs (install before navigation;
+ * Chromium), through the Long Tasks API. That sees the tasks of the page's own
+ * event loop: a timer, an event handler, `blockMainThread(page, ms, {during})`.
+ * A DevTools `page.evaluate`, such as `blockMainThread(page, ms)` without
+ * `during`, is not one of them and is never recorded here; `traceRendering`
+ * reports it in `devtoolsTasks`, apart from the page's `longTasks`.
+ */
+export async function installLongTaskLog(page: Page): Promise {
+ await page.addInitScript(LONG_TASK_SCRIPT);
+}
+
+export interface LongTask {
+ /** Epoch ms. */
+ readonly start: number;
+ readonly durationMs: number;
+ readonly name: string;
+}
+
+/**
+ * Long tasks recorded since navigation, optionally only those overlapping a
+ * window. Fails closed: it throws when the log never ran on this document
+ * (installed after the page navigated) or the engine has no Long Tasks API
+ * (WebKit), so an empty answer is evidence of no long task, never of no log.
+ */
+export async function readLongTasks(
+ page: Page,
+ range?: {from: number; to: number},
+): Promise {
+ const log = await page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __harnessLongTasks?: {tasks: LongTask[]; supported: boolean};
+ }
+ ).__harnessLongTasks ?? null,
+ );
+ if (log == null) {
+ throw new Error(
+ 'readLongTasks: the long-task log is not running on this document; call installLongTaskLog(page) before navigating',
+ );
+ }
+ if (!log.supported) {
+ throw new Error(
+ 'readLongTasks: this engine has no Long Tasks API, so the log records nothing',
+ );
+ }
+ const tasks = log.tasks;
+ return range == null
+ ? tasks
+ : tasks.filter(
+ t => t.start < range.to && t.start + t.durationMs > range.from,
+ );
+}
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index b09c556e1629f..1f38ccae31297 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3744,6 +3744,11 @@
"path": "examples/visually-hidden/supplementary-context",
"aliases": []
},
+ {
+ "name": "hook-create-context-menu",
+ "path": "hooks/create-context-menu",
+ "aliases": []
+ },
{
"name": "hook-use-animated-layout",
"path": "hooks/use-animated-layout",
@@ -3789,6 +3794,11 @@
"path": "hooks/use-container-reveal",
"aliases": []
},
+ {
+ "name": "hook-use-context-menu",
+ "path": "hooks/use-context-menu",
+ "aliases": []
+ },
{
"name": "hook-use-dev-warning",
"path": "hooks/use-dev-warning",
diff --git a/packages/build/__fixtures__/stylex-consts/App.tsx b/packages/build/__fixtures__/stylex-consts/App.tsx
new file mode 100644
index 0000000000000..5e839e5372912
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/App.tsx
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Reads `defineConsts` values from other files, as a media-query key and as a
+ * plain value, from both sides of the layer split and from a file compiled
+ * with the library class-name prefix. Only the constants are
+ * imported: once StyleX compiles `stylex.create`, nothing in this file uses
+ * the imports at runtime any more.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {appConsts} from './appConsts.stylex';
+import {libraryConsts} from './library/libraryConsts.stylex';
+import {packageConsts} from './packages/core/packageConsts.stylex';
+
+const styles = stylex.create({
+ row: {
+ minHeight: appConsts.rowHeight,
+ transitionProperty: {default: 'color', [appConsts.narrow]: 'none'},
+ },
+ panel: {
+ paddingTop: libraryConsts.inset,
+ paddingBottom: packageConsts.gap,
+ maxWidth: {default: null, [libraryConsts.wide]: '640px'},
+ },
+});
+
+export function App() {
+ return (
+
+ );
+}
diff --git a/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts
new file mode 100644
index 0000000000000..5e41328b69880
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/appConsts.stylex.ts
@@ -0,0 +1,9 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/** Constants the app defines itself, beside the file that reads them. */
+export const appConsts = stylex.defineConsts({
+ narrow: '@media (max-width: 599px)',
+ rowHeight: '52px',
+});
diff --git a/packages/build/__fixtures__/stylex-consts/index.html b/packages/build/__fixtures__/stylex-consts/index.html
new file mode 100644
index 0000000000000..ba86fc975ff35
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/index.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+ stylex-consts fixture — defineConsts imported across files
+
+
+
+
+
+
diff --git a/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts
new file mode 100644
index 0000000000000..92dda6955e61f
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/library/libraryConsts.stylex.ts
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Constants on the library side of the layer split (the build test points
+ * `libraryPattern` at this folder), read by an app file on the product side.
+ */
+export const libraryConsts = stylex.defineConsts({
+ wide: '@media (min-width: 900px)',
+ inset: '13px',
+});
diff --git a/packages/build/__fixtures__/stylex-consts/main.tsx b/packages/build/__fixtures__/stylex-consts/main.tsx
new file mode 100644
index 0000000000000..5811fe017bb3e
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/main.tsx
@@ -0,0 +1,6 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createRoot} from 'react-dom/client';
+import {App} from './App';
+
+createRoot(document.getElementById('root')!).render( );
diff --git a/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts b/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts
new file mode 100644
index 0000000000000..b4be85d7a3505
--- /dev/null
+++ b/packages/build/__fixtures__/stylex-consts/packages/core/packageConsts.stylex.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Constants as an Astryx package defines them: the path holds `packages/core/`,
+ * so the babel wrapper compiles this file with the library class-name prefix
+ * (`astryx`), as it does a real package. The app file reading them compiles
+ * with its own prefix (`x`).
+ */
+export const packageConsts = stylex.defineConsts({
+ gap: '17px',
+});
diff --git a/packages/build/src/vite.build.test.ts b/packages/build/src/vite.build.test.ts
index ee860275a2752..b0907675792c1 100644
--- a/packages/build/src/vite.build.test.ts
+++ b/packages/build/src/vite.build.test.ts
@@ -31,7 +31,7 @@
*/
import {describe, it, expect, beforeAll, afterAll} from 'vitest';
-import {build} from 'vite';
+import {build, createLogger} from 'vite';
import react from '@vitejs/plugin-react';
import {
mkdirSync,
@@ -70,6 +70,21 @@ type Built = {
async function buildFixture(
name: string,
htmlNames: string[] = ['index.html'],
+ {
+ libraryPattern = 'packages/core/',
+ zeroConfig = false,
+ stylexOverrides,
+ warnings = [],
+ }: {
+ /** Which source paths land in the library layer. */
+ libraryPattern?: string;
+ /** Use `astryxStylex({...})` instead of the legacy `{stylexOptions}` form. */
+ zeroConfig?: boolean;
+ /** Zero-config form only: `stylexOverrides`. */
+ stylexOverrides?: Record;
+ /** Receives every warning the build logs. */
+ warnings?: string[];
+ } = {},
): Promise {
const root = path.join(FIXTURES, name);
const outDir = mkdtempSync(path.join(tmpdir(), `astryx-${name}-`));
@@ -77,6 +92,11 @@ async function buildFixture(
await build({
root,
logLevel: 'error',
+ customLogger: {
+ ...createLogger('error'),
+ warn: (message: string) => void warnings.push(message),
+ warnOnce: (message: string) => void warnings.push(message),
+ },
build: {
outDir,
emptyOutDir: true,
@@ -94,17 +114,27 @@ async function buildFixture(
resolve: {alias: {'@astryxdesign/core': CORE_SRC}},
plugins: [
react(),
- ...astryxStylex({
- stylexOptions: {
- dev: false,
- unstable_moduleResolution: {type: 'commonJS', rootDir: REPO_ROOT},
- aliases: {
- '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
- '@astryxdesign/core': [CORE_SRC],
- },
- },
- libraryPattern: 'packages/core/',
- }),
+ ...(zeroConfig
+ ? astryxStylex({
+ dev: false,
+ rootDir: REPO_ROOT,
+ libraryPattern,
+ stylexOverrides,
+ })
+ : astryxStylex({
+ stylexOptions: {
+ dev: false,
+ unstable_moduleResolution: {
+ type: 'commonJS',
+ rootDir: REPO_ROOT,
+ },
+ aliases: {
+ '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
+ '@astryxdesign/core': [CORE_SRC],
+ },
+ },
+ libraryPattern,
+ })),
],
});
} catch (error) {
@@ -338,6 +368,67 @@ describe('a production build separates Astryx and product styles by layer', () =
});
});
+// `defineConsts` values are compiled into the reading file as placeholders,
+// `var(--)`, and the defining file contributes the values; the
+// final CSS pass substitutes one for the other. Both halves must reach that
+// pass. Storybook builds through the legacy `{stylexOptions}` form, whose
+// StyleX instance ran without `treeshakeCompensation`: once `stylex.create`
+// was compiled, nothing used the import at runtime, the TypeScript transform
+// dropped it, and the defining module was never loaded. A media-query key was
+// left as `var(--x…){…}` and failed the build ("Invalid empty selector"); a
+// value shipped as a custom property nothing defines. And a constant defined
+// on one side of the layer split and read on the other was substituted only
+// within its own side, and one an Astryx package defines (compiled with the
+// library class-name prefix) never matched an app file's placeholder (written
+// with the product prefix).
+describe('a production build resolves defineConsts imported across files', () => {
+ /** A constant reference StyleX left unsubstituted. */
+ const PLACEHOLDER = /var\(--(?:astryx|x)[a-z0-9]{4,}\)/;
+
+ for (const zeroConfig of [false, true]) {
+ describe(
+ zeroConfig ? 'zero-config form' : 'legacy stylexOptions form (Storybook)',
+ () => {
+ let built: Built;
+ beforeAll(async () => {
+ built = await buildFixture('stylex-consts', ['index.html'], {
+ libraryPattern: '__fixtures__/stylex-consts/library/',
+ zeroConfig,
+ });
+ }, 180_000);
+ afterAll(
+ () => built && rmSync(built.outDir, {recursive: true, force: true}),
+ );
+
+ it('substitutes a constant read as a value', () => {
+ expect(built.css).toMatch(/min-height:\s*52px/);
+ });
+
+ it('substitutes a constant read as a media-query key', () => {
+ expect(built.css).toMatch(
+ /@media \((?:max-width: ?599px|width ?<= ?599px)\)\s*\{[^}]*transition-property:\s*none/,
+ );
+ });
+
+ it('substitutes a library-side constant read from the product side', () => {
+ expect(built.css).toMatch(/padding-top:\s*13px/);
+ expect(built.css).toMatch(
+ /@media \((?:min-width: ?900px|width ?>= ?900px)\)\s*\{[^}]*max-width:\s*640px/,
+ );
+ });
+
+ it('substitutes a constant an Astryx package defines under the library prefix', () => {
+ expect(built.css).toMatch(/padding-bottom:\s*17px/);
+ });
+
+ it('leaves no constant placeholder behind', () => {
+ expect(built.css).not.toMatch(PLACEHOLDER);
+ });
+ },
+ );
+ }
+});
+
describe('a production build validates StyleX declarations', () => {
it('fails with longhand guidance instead of dropping a border shorthand', async () => {
await expect(buildFixture('invalid-border')).rejects.toThrow(
diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts
index 0581b58675edb..edaa88ca55a1d 100644
--- a/packages/build/src/vite.ts
+++ b/packages/build/src/vite.ts
@@ -136,6 +136,12 @@ export function astryxStylex(
const libraryLayer = layers.library ?? 'astryx-base';
const productLayer = layers.product ?? 'product';
+ // Library files compile with `stylexPrefix`, product files with StyleX's
+ // `classNamePrefix` (the babel wrapper routes them).
+ const classNamePrefixes = [
+ stylexPrefix,
+ (stylexOverrides as {classNamePrefix?: string}).classNamePrefix ?? 'x',
+ ];
const overrideLightningcssOptions = (
stylexOverrides as {lightningcssOptions?: Record}
@@ -284,6 +290,7 @@ export function astryxStylex(
libraryPattern,
libraryLayer,
productLayer,
+ classNamePrefixes,
}),
);
},
@@ -302,6 +309,7 @@ export function astryxStylex(
libraryLayer,
productLayer,
lightningcssOptions: stylexOptions.lightningcssOptions,
+ classNamePrefixes,
}),
];
}
@@ -330,24 +338,43 @@ function renderSplitLayers(
libraryPattern: string;
libraryLayer: string;
productLayer: string;
+ /** The StyleX class-name prefixes in play: library, then product. */
+ classNamePrefixes: readonly string[];
},
): string {
if (!rulesById || rulesById.size === 0) return '';
const libraryRules: unknown[] = [];
const productRules: unknown[] = [];
+ // `defineConsts` values. A file that reads a constant compiles it to a
+ // placeholder, `var(--)`, and `processStylexRules` substitutes
+ // the value from the defining file's rules, but only among the rules it is
+ // given. The defining file and the reading one can sit on opposite sides of
+ // the split, so every layer gets every constant, under every class-name
+ // prefix (see constantRulesForEveryPrefix). Constant rules emit no CSS of
+ // their own, so repeating them adds nothing to the output.
+ const collectedConstants: unknown[] = [];
for (const [filePath, rules] of rulesById.entries()) {
- if (filePath.includes(options.libraryPattern)) {
- libraryRules.push(...rules);
- } else {
- productRules.push(...rules);
+ const own = filePath.includes(options.libraryPattern)
+ ? libraryRules
+ : productRules;
+ for (const rule of rules) {
+ if (isConstantRule(rule)) {
+ collectedConstants.push(rule);
+ } else {
+ own.push(rule);
+ }
}
}
+ const constantRules = constantRulesForEveryPrefix(
+ collectedConstants,
+ options.classNamePrefixes,
+ );
const render = (rules: unknown[], layer: string) =>
rules.length
- ? `@layer ${layer} {\n${stylexBabelPlugin.processStylexRules(rules as never, {useLayers: true})}\n}`
+ ? `@layer ${layer} {\n${stylexBabelPlugin.processStylexRules([...constantRules, ...rules] as never, {useLayers: true})}\n}`
: '';
return [
@@ -358,6 +385,56 @@ function renderSplitLayers(
.join('\n\n');
}
+/**
+ * Each `defineConsts` rule once under every class-name prefix in play.
+ *
+ * StyleX keys a constant by its defining file's prefix, `` (or
+ * `-` with debug class names), where the hash depends on
+ * the export and key alone, and a file that reads it writes the placeholder
+ * with its own prefix. An Astryx package compiles with the library prefix and
+ * an app with the product one, so an app reading a package's constant writes
+ * `var(--x)` while the package's rule is keyed `astryx`; the
+ * copies make every prefix's placeholder resolve. A key StyleX took verbatim
+ * (`'--name'`) carries no prefix and is kept as it is.
+ */
+function constantRulesForEveryPrefix(
+ rules: readonly unknown[],
+ prefixes: readonly string[],
+): unknown[] {
+ const ordered = [...new Set(prefixes)]
+ .filter(Boolean)
+ .sort((a, b) => b.length - a.length);
+ const out: unknown[] = [];
+ const keys = new Set();
+ const add = (rule: unknown[], key: string) => {
+ if (keys.has(key)) return;
+ keys.add(key);
+ const [, body, ...rest] = rule;
+ out.push([key, {...(body as object), constKey: key}, ...rest]);
+ };
+ for (const rule of rules as unknown[][]) {
+ const key = String((rule[1] as {constKey: unknown}).constKey);
+ add(rule, key);
+ for (const prefix of ordered) {
+ const match = new RegExp(`^(|.*-)${prefix}([0-9a-z]+)$`).exec(key);
+ if (match == null) continue;
+ for (const other of ordered) {
+ add(rule, `${match[1]}${other}${match[2]}`);
+ }
+ break;
+ }
+ }
+ return out;
+}
+
+/** A `defineConsts` value as StyleX collects it: a rule with `constKey`/`constVal`. */
+function isConstantRule(rule: unknown): boolean {
+ const body = Array.isArray(rule)
+ ? (rule[1] as {constKey?: unknown; constVal?: unknown} | undefined)
+ : undefined;
+ return body?.constKey != null && body?.constVal != null;
+}
+
/**
* The build half of the split. StyleX appends one merged block of CSS to the
* build's stylesheet, in its own top-level `@layer priority1…priorityN` — which
@@ -387,6 +464,8 @@ function buildLayerSplitPlugin(
libraryLayer: string;
productLayer: string;
lightningcssOptions?: unknown;
+ /** The StyleX class-name prefixes in play: library, then product. */
+ classNamePrefixes: readonly string[];
},
): Plugin {
const stylex = basePlugin as {
@@ -586,12 +665,25 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
).lightningcssOptions;
const validatedStylexOptions = {
propertyValidationMode: 'throw',
+ // The unplugin applies its Vite default (true) only to its own StyleX
+ // instance, which runs after the babel wrapper below has already compiled
+ // every StyleX call. Without it here, a file that reads only `defineConsts`
+ // from a `.stylex.ts` module loses that import once `stylex.create` is
+ // compiled (the TypeScript transform drops it as unused), the module is
+ // never loaded, and its constants never reach the CSS: a media-query key
+ // fails the build and a value ships as an undefined custom property.
+ treeshakeCompensation: true,
...(stylexOptions as any),
lightningcssOptions: {
targets: LIGHTNINGCSS_TARGETS,
...legacyLightningcssOptions,
},
};
+ const classNamePrefixes = [
+ stylexPrefix,
+ (validatedStylexOptions as {classNamePrefix?: string}).classNamePrefix ??
+ 'x',
+ ];
const astryxBabelPlugin = path.resolve(__dirname, 'babel.js');
const existingPlugins = validatedStylexOptions.babelConfig?.plugins ?? [];
@@ -658,6 +750,7 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
libraryPattern,
libraryLayer,
productLayer,
+ classNamePrefixes,
}),
);
},
@@ -677,6 +770,7 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
lightningcssOptions: (
validatedStylexOptions as {lightningcssOptions?: unknown}
).lightningcssOptions,
+ classNamePrefixes,
}),
];
}
diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjs
index f690a79b2fcb4..89dee0b30588c 100644
--- a/packages/cli/foundation/doc-compiler/inputs.test.mjs
+++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs
@@ -96,6 +96,7 @@ describe('collectDocInputs over what this repo ships', () => {
'NavMenu',
'Resizable',
'SyntaxTheme',
+ 'createContextMenu',
]);
});
diff --git a/packages/core/package.json b/packages/core/package.json
index 295c3d98433c4..3bba9ae4f24ac 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -864,6 +864,7 @@
"devDependencies": {
"@astryxdesign/a11y-spec": "workspace:*",
"@astryxdesign/cli": "workspace:*",
+ "@astryxdesign/interaction-harness": "workspace:*",
"@babel/cli": "catalog:",
"@babel/core": "catalog:",
"@babel/preset-react": "catalog:",
diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
index f8ee2c5659074..80d646501d402 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, on every touch device, a held finger opens it with iOS timing: the trigger starts to grow at 150 ms, and the menu opens at 735 ms, or as soon as the finger lifts after 400 ms. A block trigger then lifts out of the page, as on iOS: it grows about 13% over a tinted backdrop, and the menu grows out of the finger to sit beside it, below when it fits and above otherwise.',
bestPractices: [
{
guidance: true,
@@ -187,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 6%, and it lifts about 13% larger while the menu is open.',
+ },
{
guidance: false,
description:
@@ -224,7 +228,7 @@ export const docs = {
export const docsZh = {
usage: {
description:
- '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。',
+ '右键点击时在光标位置出现的上下文菜单。用于为特定元素或区域提供上下文操作,而不使 UI 杂乱。在所有触摸设备上,按住手指即可打开,时序与 iOS 相同:150 毫秒时触发区域开始放大,735 毫秒时菜单打开;若手指在 400 毫秒后抬起,菜单在抬起时立即打开。随后块级触发区域会像 iOS 一样从页面中浮起:它在着色背景上放大约 13%,菜单从手指处展开并位于其旁边,空间足够时在下方,否则在上方。',
bestPractices: [
{guidance: true, description: '保持菜单项简洁和面向操作。'},
{guidance: true, description: '有很多项时使用分组和分隔线。'},
@@ -242,6 +246,11 @@ export const docsZh = {
description:
'重要的移动端操作还应提供可见的 MoreMenu 或同等入口,不要只依赖长按。',
},
+ {
+ guidance: true,
+ description:
+ '块级触发区域周围请留出少量空间:按住时它会从中心放大约 6%,菜单打开期间它浮起时约大 13%。',
+ },
{
guidance: false,
description: '将上下文菜单作为访问重要操作的唯一方式。',
@@ -260,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.',
+ 'A right-click context menu that appears at the cursor position. Use to provide contextual actions for specific elements or regions. Under a finger (any touch device): a held finger opens it at 735 ms, or on a lift after 400 ms; the trigger grows from 150 ms, then a block trigger lifts (about 13%) over a tint with the menu below or above it.',
bestPractices: [
{guidance: true, description: 'Keep items concise and action-oriented.'},
{
@@ -281,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 6%, and it lifts about 13% larger.',
+ },
{
guidance: false,
description: 'Use as the only way to access important actions.',
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index 4c4bbfc5d8e6f..bcc7ec2a2b9a3 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -207,17 +207,18 @@ 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` pointer, long-press, bottom-sheet, adaptive, compound, and drill-in suites | Pointer data/compound and touch data/compound | Collapsing presentation-specific parts or content owners fails structure, role, or behavior tests. | `audit:ContextMenu/anatomy` |
-| FR2 | ContextMenu target tests, source inspection, and theming target inventories | Pointer and touch menu surfaces | Moving `context-menu` to the trigger or removing it from a painted branch fails evidence. | `audit:ContextMenu/theming` |
-| FR3 | ContextMenu, DropdownMenu, BottomSheet, and List owner tests | Pointer rows, touch frame, touch list/rows | A composed part loses its owner target or is documented as a new ContextMenu target. | `audit:ContextMenu/theming` |
-| Layer relationships | `ContextMenu.test.tsx` nested-layer case and current layer/dismissal architecture records | Outside click, Escape, nested context layers, sheet | A Pointer menu bypassing the shared stack or dismissing with its nested child fails. | `audit:ContextMenu/behavior` |
-| FR5 | `ContextMenu.test.tsx` press model case; `module:DropdownMenu/useMenuPress` map | Finger slide across rows, stray click | A row acting on the press row or the stray click fails. | `audit:ContextMenu/behavior` |
-| FR6 | `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | wrap at both ends | Clamping arrows fail. | `audit:ContextMenu/behavior` |
-| FR10 | ContextMenu tests over `createContextMenu` and a source check | a right click, a long press, Shift+F10; open, close, unmount while open | A context request that bypasses the factory, open state ContextMenu keeps on its own, or a listener left after unmount fails | `audit:ContextMenu/behavior` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` |
-| FR6, AR1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" suite | `span` in a paragraph, default `div` | A block trigger inside prose, or a lost invocation path, fails. | `audit:ContextMenu/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
+| FR1, FR4 | `ContextMenu.test.tsx` pointer, long-press, bottom-sheet, adaptive, compound, and drill-in suites | Pointer data/compound and touch data/compound | Collapsing presentation-specific parts or content owners fails structure, role, or behavior tests. | `audit:ContextMenu/anatomy` |
+| FR2 | ContextMenu target tests, source inspection, and theming target inventories | Pointer and touch menu surfaces | Moving `context-menu` to the trigger or removing it from a painted branch fails evidence. | `audit:ContextMenu/theming` |
+| FR3 | ContextMenu, DropdownMenu, BottomSheet, and List owner tests | Pointer rows, touch frame, touch list/rows | A composed part loses its owner target or is documented as a new ContextMenu target. | `audit:ContextMenu/theming` |
+| Layer relationships | `ContextMenu.test.tsx` nested-layer case and current layer/dismissal architecture records | Outside click, Escape, nested context layers, sheet | A Pointer menu bypassing the shared stack or dismissing with its nested child fails. | `audit:ContextMenu/behavior` |
+| FR5 | `ContextMenu.test.tsx` press model case; `module:DropdownMenu/useMenuPress` map | Finger slide across rows, stray click | A row acting on the press row or the stray click fails. | `audit:ContextMenu/behavior` |
+| FR6 | `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | wrap at both ends | Clamping arrows fail. | `audit:ContextMenu/behavior` |
+| FR10 | ContextMenu tests over `createContextMenu` and a source check | a right click, a long press, Shift+F10; open, close, unmount while open | A context request that bypasses the factory, open state ContextMenu keeps on its own, or a listener left after unmount fails | `audit:ContextMenu/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` |
+| FR6, AR1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" suite | `span` in a paragraph, default `div` | A block trigger inside prose, or a lost invocation path, fails. | `audit:ContextMenu/behavior` |
+| DEC-2 | `ContextMenuLift.interaction.browser.spec.ts` element-count case; `ContextMenu.test.tsx` lift suite | Touch story at rest and lifted, fine and coarse | 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. | `audit:ContextMenu/anatomy` |
## Decision log
@@ -240,6 +241,43 @@ Rejected: styling a block `div` as inline because it remains invalid inside a
Rejected: `display: contents` because a box-less wrapper has no rect for pointer
or keyboard anchoring.
+### DEC-2 — The lift adds four elements while open, each with one job
+
+**Reference:** `component:ContextMenu/DEC-2`
+
+**Status:** proposed; pending owner review.
+
+Under a finger, a touch-opened menu on a block trigger lifts the trigger
+itself above the tinted page (`spec:AST-094` FR33), through the lift module
+(`packages/core/src/liftFromTrigger/`). While the menu is up, the page has four
+elements more than under a fine pointer, within the open-layer allowance of
+`spec:AST-017` FR60 and DEC-29, and each has one job:
+
+- the lift layer covers the viewport from the top layer, takes the page's
+ touches and paints the tint as its `::backdrop`;
+- the shadow, a box in the layer, follows the trigger's lift as one
+ compositor animation (an animated `::backdrop` of the trigger restyles
+ and lays out the page on every frame);
+- an empty box in the layer, at the lifted rect, is what the menu is placed
+ against (anchor positioning follows transforms, so the trigger's own cursor
+ anchor would move with the lifted trigger);
+- an empty placeholder after the trigger holds the trigger's spot, so the
+ page does not move while the trigger is in the top layer.
+
+None of the four is themeable or part of the anatomy, none is mounted at rest, and no content is mounted
+twice: the trigger lifts itself, with no copy. The input hold's shield
+joins while the lift grows, and the layer runtime's exit copy while the menu
+closes.
+
+Element counts (`document.body.querySelectorAll('*').length`, story
+`core-contextmenu--touch-long-press`, Chromium and WebKit): fine pointer 138
+at rest and 138 open; coarse pointer 138 at rest and 142 lifted, whatever the
+trigger holds.
+
+Rejected: a copy of the trigger above the tint, because it mounts the
+trigger's content twice and its count grows with the trigger (a list row's
+8 to 15 elements).
+
## Open questions
None.
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index d3d00b8417338..08afc37cfcff1 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,
@@ -21,7 +29,6 @@ import {
createEvent,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {readFileSync} from 'node:fs';
import {ContextMenu} from './ContextMenu';
import {ContextMenuGroup} from './index';
import {
@@ -34,9 +41,14 @@ import {
import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';
import {DropdownMenuSubMenu} from '../DropdownMenu/DropdownMenuSubMenu';
import {Divider} from '../Divider';
+import {LayerProvider} from '../Layer/LayerProvider';
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';
+import {disarmClickGuard} from '../utils/clickGuard';
// The touch sheet is loaded lazily; resolve its modules once up front, so
// ContextMenu's own lazy sheet renders within the cases' waitFor.
@@ -345,7 +357,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(),
@@ -528,114 +544,779 @@ describe('ContextMenu', () => {
fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0});
expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
});
+});
- it('opens on touch long-press', () => {
- vi.useFakeTimers();
- try {
+/**
+ * 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;
+}
+
+/** The fingers `finger()` holds down: the first of them is the primary. */
+const fingersDown = new Set();
+afterEach(() => {
+ // A finger a case left down lifts, so the gesture host starts the next case
+ // with none.
+ for (const id of [...fingersDown]) {
+ const contact = {id, x: 0, y: 0};
+ dispatchFingerPointer('pointerup', document.body, contact);
+ dispatchTouch('touchend', document.body, [contact], []);
+ }
+ fingersDown.clear();
+});
+
+/** A finger's pointer event, sent before its touch event as a browser does. */
+function dispatchFingerPointer(
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ target: EventTarget,
+ contact: Contact,
+): void {
+ const event = new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: contact.id,
+ pointerType: 'touch',
+ isPrimary:
+ type === 'pointerdown'
+ ? fingersDown.size === 0
+ : [...fingersDown][0] === contact.id,
+ clientX: contact.x,
+ clientY: contact.y,
+ button: type === 'pointermove' ? -1 : 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ });
+ Object.defineProperty(event, 'timeStamp', {value: performance.now()});
+ target.dispatchEvent(event);
+}
+
+/**
+ * A finger as a browser reports it: each step's pointer event, then its touch
+ * event. The context request reads whichever the gesture host takes the
+ * finger from.
+ */
+function finger(target: EventTarget, id = 1, x = 20, y = 20) {
+ const contact = {id, x, y};
+ return {
+ down: () => {
+ dispatchFingerPointer('pointerdown', target, contact);
+ fingersDown.add(contact.id);
+ return dispatchTouch('touchstart', target, [contact], [contact]);
+ },
+ moveTo: (nx: number, ny: number) => {
+ contact.x = nx;
+ contact.y = ny;
+ dispatchFingerPointer('pointermove', target, contact);
+ return dispatchTouch('touchmove', target, [contact], [contact]);
+ },
+ up: () => {
+ dispatchFingerPointer('pointerup', target, contact);
+ fingersDown.delete(contact.id);
+ return 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;
+
+/**
+ * How many times the menu's popover was shown (a touch-opened menu also shows
+ * the lift layer and the lifted trigger).
+ */
+const menuShows = () =>
+ vi.mocked(HTMLElement.prototype.showPopover).mock.contexts.filter(
+ // The popover that holds the menu: not the lift layer, the hold's shield
+ // inside it, or the lifted trigger.
+ el => (el as HTMLElement).querySelector('[role="menu"]') != null,
+ ).length;
+
+// 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',
+ ],
+ });
+ clockEpoch += 100_000;
+ vi.advanceTimersByTime(clockEpoch);
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ function renderMenu(
+ props: {
+ isDisabled?: boolean;
+ presentation?: 'popover';
+ triggerAs?: 'div' | 'span';
+ onTouchStart?: (event: React.TouchEvent) => void;
+ onTouchEnd?: (event: React.TouchEvent) => void;
+ } = {},
+ ) {
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();
+ return screen.getByTestId('ctx');
+ }
+
+ 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(menuShows()).toBe(0);
+ advance(1);
+ expect(menuShows()).toBe(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(menuShows()).toBe(0);
act(() => {
- vi.advanceTimersByTime(500);
+ press.up();
});
- expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
- } finally {
- vi.useRealTimers();
- }
- });
+ expect(menuShows()).toBe(1);
+ });
- it('composes consumer touch handlers with long-press detection', () => {
- vi.useFakeTimers();
- try {
+ 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(menuShows()).toBe(0);
+ });
+
+ 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();
- render(
+ const trigger = renderMenu({onTouchStart});
+ const press = finger(trigger);
+ press.down();
+ expect(onTouchStart).toHaveBeenCalledTimes(1);
+ advance(contextMenu.press.menuDisplayMs - 1);
+ expect(menuShows()).toBe(0);
+ advance(1);
+ expect(menuShows()).toBe(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(menuShows()).toBe(0);
+ });
+
+ 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(
- Long-press me
+ triggerAs="span">
+ Long-press me
,
);
+ const press = finger(screen.getByTestId('ctx'));
+ press.down();
+ advance(contextMenu.press.menuDisplayMs);
+ expect(menuShows()).toBe(1);
+ press.up();
+ });
+
+ 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(menuShows()).toBe(0);
+ });
+
+ 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(menuShows()).toBe(0);
+ 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(menuShows()).toBe(1);
+ press.up();
+ });
- fireEvent.touchStart(screen.getByTestId('ctx'), {
- touches: [{clientX: 20, clientY: 20}],
+ 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(menuShows()).toBe(0);
+ 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,
+ });
+ trigger.dispatchEvent(native);
+ expect(native.defaultPrevented).toBe(true);
+ expect(menuShows()).toBe(0);
+ advance(contextMenu.press.menuDisplayMs - 380);
+ expect(menuShows()).toBe(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,
});
- expect(onTouchStart).toHaveBeenCalledOnce();
+ 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(menuShows()).toBe(0);
+ 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('holds the page still while a menu a finger opened is up, and lets it go when the menu closes', () => {
+ 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).toHaveBeenCalledOnce();
- } finally {
- vi.useRealTimers();
- }
- });
+ expect(document.body.style.position).toBe('fixed');
+ act(() => {
+ fireEvent.keyDown(screen.getByRole('menu', {hidden: true}), {
+ key: 'Escape',
+ });
+ });
+ expect(document.body.style.position).toBe('');
+ });
- it('clears a pending long-press when a consumer prevents default on touch end', () => {
- vi.useFakeTimers();
- try {
+ it('leaves the page alone for a menu a right-click opened', () => {
+ const trigger = renderMenu();
+ fireEvent.contextMenu(trigger, {clientX: 20, clientY: 20});
+ expect(menuShows()).toBe(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('makes the trigger a pressable surface of core’s one press machine, which starts and ends its growth', () => {
+ 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 = () =>
+ 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(menuShows()).toBe(0);
+ press.up();
+ });
+
+ it('lifts the block trigger itself, no copy, and closes when a finger lifts on the backdrop (UIKit ends at that lift)', () => {
+ const onOpenChange = vi.fn();
render(
event.preventDefault()}>
+ onOpenChange={onOpenChange}>
Long-press me
,
);
-
+ const press = finger(screen.getByTestId('ctx'));
+ press.down();
+ advance(contextMenu.press.menuDisplayMs);
+ press.up();
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ // The trigger is in the top layer itself, and an empty placeholder
+ // after it holds its spot.
const trigger = screen.getByTestId('ctx');
- fireEvent.touchStart(trigger, {
- touches: [{clientX: 20, clientY: 20}],
+ expect(trigger.getAttribute('popover')).toBe('manual');
+ expect(
+ trigger.nextElementSibling?.hasAttribute(
+ 'data-astryx-context-menu-lift-placeholder',
+ ),
+ ).toBe(true);
+ // The layer takes the tint's touches (its ::backdrop paints the tint).
+ const backdrop = document.querySelector(
+ '[data-astryx-context-menu-lift]',
+ );
+ if (backdrop == null) {
+ throw new Error('no lift layer');
+ }
+ // A lift there of a finger that went down elsewhere is not a tap there.
+ fireEvent.pointerUp(backdrop, {
+ isPrimary: true,
+ pointerId: 7,
+ pointerType: 'touch',
+ });
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ fireEvent.pointerDown(backdrop, {
+ isPrimary: true,
+ pointerId: 8,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerUp(backdrop, {
+ isPrimary: true,
+ pointerId: 8,
+ pointerType: 'touch',
});
- fireEvent.touchEnd(trigger);
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
- act(() => {
- vi.advanceTimersByTime(500);
+ it('leaves no timer of the lift behind when it unmounts while the lift is still growing (AST-094 FR24)', () => {
+ const view = render(
+
+ Long-press me
+ ,
+ );
+ const press = finger(screen.getByTestId('ctx'));
+ press.down();
+ advance(contextMenu.press.menuDisplayMs);
+ press.up();
+ expect(
+ document.querySelector('[data-astryx-context-menu-lift]'),
+ ).not.toBeNull();
+ // The menu's own focus move (one frame) is not the lift's, and the
+ // click guard's window after the lift is the page's, not the lift's.
+ advance(20);
+ disarmClickGuard(document);
+ const beforeUnmount = vi.getTimerCount();
+ view.unmount();
+ expect(
+ document.querySelector('[data-astryx-context-menu-lift]'),
+ ).toBeNull();
+ expect(beforeUnmount).toBeGreaterThan(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('mounts nothing of the lift at rest, and the lift layer only while lifted (INV7)', async () => {
+ render(
+
+
+ Long-press me
+
+ ,
+ );
+ expect(
+ document.querySelector('[data-astryx-context-menu-lift]'),
+ ).toBeNull();
+ const press = finger(screen.getByTestId('ctx'));
+ press.down();
+ advance(contextMenu.press.menuDisplayMs);
+ press.up();
+ const layer = document.querySelector(
+ '[data-astryx-context-menu-lift]',
+ );
+ expect(layer).not.toBeNull();
+ // While the lift grows the layer is held (AST-094 FR35): the hold's
+ // shield is its third child. Once it has grown, the shadow and the box
+ // the menu is placed against are the layer's only content (the trigger
+ // lifts itself).
+ expect(layer?.children).toHaveLength(3);
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
});
- expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
- } finally {
- vi.useRealTimers();
- }
+ expect(layer?.children).toHaveLength(2);
+ });
+
+ it('keeps an inline trigger’s menu at the finger: no lift', () => {
+ const trigger = renderMenu({triggerAs: 'span'});
+ const press = finger(trigger);
+ press.down();
+ advance(contextMenu.press.menuDisplayMs);
+ expect(menuShows()).toBe(1);
+ expect(
+ document.querySelector('[data-astryx-context-menu-lift]'),
+ ).toBeNull();
+ 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', () => {
+ // The menu's popover only (not the lift layer or its hold's shield).
+ const shows = menuShows;
+ 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();
});
});
@@ -977,8 +1658,8 @@ describe('ContextMenu compound mode', () => {
width: 60,
height: 20,
}) as DOMRect;
- // Keyboard-initiated contextmenu: coords (0,0), detail 0 -> local (0, height).
- fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0});
+ // A key's request (Shift+F10, read from its keydown): local (0, height).
+ fireEvent.keyDown(trigger, {key: 'F10', shiftKey: true});
const anchor = getCursorAnchor(trigger);
expect(anchor.style.left).toBe('0px');
// The 1px anchor steps back into the trigger's last pixel row, so its
@@ -1439,29 +2120,38 @@ describe('ContextMenu inline trigger (triggerAs)', () => {
});
});
+const fingerOn = finger;
+
describe('ContextMenu outside dismissal', () => {
const finger = (pointerId: number) => ({pointerType: 'touch', pointerId});
- // Holds a finger on the trigger until the long-press opens the menu. Only
- // the long-press delay is faked.
+ // The long press's timer and the clock the gesture host reads are faked
+ // for the whole case, moving on from the last case's clock, so a finger's
+ // event times only move forward.
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'],
+ });
+ clockEpoch += 100_000;
+ vi.advanceTimersByTime(clockEpoch);
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // Holds a finger on the trigger, as a browser reports it (its pointer and
+ // touch events), until the long-press opens the menu.
function longPress(trigger: HTMLElement, pointerId: number) {
- vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
- try {
- fireEvent.pointerDown(trigger, finger(pointerId));
- fireEvent.touchStart(trigger, {touches: [{clientX: 20, clientY: 20}]});
- act(() => {
- vi.advanceTimersByTime(500);
- });
- } finally {
- vi.useRealTimers();
- }
+ fingerOn(trigger, pointerId).down();
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
}
// What a browser sends after a touch: the lift, then compatibility mouse
// events aimed at the element the finger held.
function lift(target: HTMLElement, pointerId: number) {
- fireEvent.pointerUp(target, finger(pointerId));
- fireEvent.touchEnd(target);
+ fingerOn(target, pointerId).up();
fireEvent.mouseDown(target);
fireEvent.mouseUp(target);
fireEvent.click(target);
@@ -1502,10 +2192,10 @@ describe('ContextMenu outside dismissal', () => {
expect(onOpenChange).toHaveBeenLastCalledWith(false);
});
- it('a finger long press that opens the menu through a pointer contextmenu (Chromium) does not close it as it lifts', () => {
+ it('a finger long press whose pointer contextmenu (Chromium) the context request refuses does not close the menu as it lifts', () => {
const onOpenChange = vi.fn<(isOpen: boolean) => void>();
const {trigger, outside} = renderMenu(onOpenChange);
- fireEvent.pointerDown(trigger, finger(8));
+ longPress(trigger, 8);
const contextmenu = createEvent.contextMenu(trigger, {
clientX: 20,
clientY: 15,
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index 322a6c7c85059..745fb731aa1ee 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -3,10 +3,15 @@
/**
* @file ContextMenu.tsx
- * @input Uses React, StyleX, useLayer, shared layer dismissal, BottomSheet,
- * useListFocus, and the shared menu-presentation resolver
- * @output Exports ContextMenu with cursor-popover and touch-sheet presentations
- * @position Core implementation; consumed by index.ts
+ * @input Uses React, StyleX, the headless context menu (createContextMenu.tsx,
+ * which ContextMenu is built on, and contextMenuRows.tsx for its rows),
+ * useLayer, shared layer dismissal, BottomSheet, useListFocus, the
+ * presentation resolver (usePresentation), and the touch layer
+ * (ContextMenuTouchLayer: the press feedback and the lift presentation)
+ * @output Exports ContextMenu with cursor-popover, touch-lift and touch-sheet
+ * presentations, and, internally, ContextMenuView: the menu createContextMenu
+ * renders for its element
+ * @position Core implementation; consumed by index.ts and createContextMenu.tsx
*
* Right-click context menu positioned at the cursor. The cursor point is
* captured as an offset *inside the trigger* and materialized as a 1px
@@ -16,6 +21,30 @@
* under the cursor.
* Reuses DropdownMenu item rendering and keyboard navigation.
*
+ * ContextMenu is built on createContextMenu (spec:AST-107 FR8, FR7). It renders
+ * its trigger and attaches the factory to it: the factory opens the menu on
+ * the trigger's context request (a held finger or pen, a right click,
+ * Shift+F10 or the context-menu key, once per gesture), runs the touch model
+ * on it, and renders it through ContextMenu's own tree, as a portal into a
+ * container beside the trigger, so the caller's contexts reach it and it
+ * unmounts with ContextMenu. `items` go to the factory as they are;
+ * `menuContent` is portaled into the menu from ContextMenu's tree.
+ *
+ * Under a finger (a coarse primary pointer: one touch model on every touch
+ * device, iOS and Android alike) the trigger behaves like UIKit's
+ * UIContextMenuInteraction: the request's hold runs on UIKit's timeline
+ * (`contextMenu.press`: the commit, then the menu at its moment or at a lift
+ * after the commit, a drift tolerance on each axis), with the press feedback,
+ * the page stays put while that menu is up, and the press sends no click. When the
+ * menu shows, a block trigger lifts itself as UIKit's preview does
+ * (ContextMenuLift.tsx, on the lift module) and the menu sits beside it
+ * (`contextMenu.lift`); an inline trigger keeps the menu at the finger. The
+ * touch layer, the lift included, is part of ContextMenu, so it runs from the
+ * first render under the touch model (a phone pays no extra request for it).
+ * A fine primary pointer keeps the right-click menu and the request's own long
+ * press for a finger (500 ms), as `presentation="popover"` does; UIKit's
+ * timeline applies only under the touch model.
+ *
* Supports two content modes with a single keyboard/focus path:
* - **Data-driven**: pass `items` array (converted to components internally)
* - **Compound-component**: pass `menuContent` JSX directly
@@ -29,6 +58,12 @@
* 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/createContextMenu.tsx (the factory it is built on)
+ * - /packages/core/src/ContextMenu/contextMenuRows.tsx (its rows in the menu)
+ * - /packages/core/src/ContextMenu/contextMenuRequests.ts (the request core)
+ * - /packages/core/src/ContextMenu/contextMenuPressFeedback.ts (press feedback)
+ * - /packages/core/src/ContextMenu/ContextMenuLift.tsx (lift presentation)
* - /packages/core/src/ContextMenu/index.ts
* - /apps/storybook/stories/ContextMenu.stories.tsx
* - /packages/cli/assets/templates/blocks/components/ContextMenu/ (showcase blocks)
@@ -38,6 +73,7 @@ import React, {
useCallback,
useEffect,
useId,
+ useImperativeHandle,
lazy,
useMemo,
useRef,
@@ -45,10 +81,12 @@ import React, {
Suspense,
} from 'react';
import type {ReactNode} from 'react';
+import {createPortal, flushSync} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button';
import {Heading} from '../Heading';
import {Icon} from '../Icon';
+import {addAnchorName, removeAnchorName} from '../Layer/anchorName';
import {useLayer} from '../Layer/useLayer';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
@@ -70,9 +108,38 @@ import {
import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn';
import {useListFocus} from '../hooks/useListFocus';
+import type {ContextRequestOptions} from '../gestures/contextRequest';
+import {contextMenu} from '../motion/uikit/contextMenu';
+import {PRESSABLE_ATTRIBUTE} from '../utils/pressFeedback';
import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
-import {useLongPress} from '../hooks/useLongPress';
+import {useScrollLock} from '../hooks/useScrollLock';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {readPresentation, usePresentation} from '../utils/presentation';
+import {useCompactDefinition} from '../utils/touchPresentation';
+import {
+ ContextMenuTouchLayer,
+ type ContextMenuTouchHandle,
+ type LiftedMenuPlacement,
+} from './ContextMenuTouchLayer';
+import type {
+ ContextMenuForwarded,
+ ContextMenuRequestOptions,
+} from './contextMenuRequests';
+import type {ContextMenuLiftResult} from './ContextMenuLift';
+import {
+ createMenuRowsSlot,
+ MenuRows,
+ type MenuRowsSlot,
+} from './contextMenuRows';
+import {
+ createContextMenu,
+ hostContextMenuInReact,
+ updateContextMenu,
+ viewContextMenu,
+ type ContextMenuController,
+ type CreateContextMenuOptions,
+} from './createContextMenu';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {
colorVars,
@@ -95,39 +162,89 @@ import type {
} from '../DropdownMenu/DropdownMenu';
import {useMergedRefs} from '../hooks/useMergedRefs';
-import {
- useAdaptivePresentation,
- type AdaptivePresentation,
-} from '../hooks/useAdaptivePresentation';
+import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';
+
+/**
+ * @internal UIContextMenuInteraction's hold (contextMenu.press, measured on
+ * iOS 26.2): the commit at 400 ms, the menu at 735 ms or at a lift after the
+ * commit, and a drift tolerance on each axis.
+ */
+export const CONTEXT_MENU_TOUCH_HOLD = {
+ commitMs: contextMenu.press.commitMs,
+ requestMs: contextMenu.press.menuDisplayMs,
+ requestOnLift: true,
+ allowableMovement: contextMenu.press.allowableMovement,
+ isPerAxis: true,
+};
const LazyMenuBottomSheet = lazy(async () =>
import('../DropdownMenu/MenuBottomSheet').then(module => ({
default: module.MenuBottomSheet,
})),
);
+/**
+ * The `left` and `top` that put a fixed box's corner at a client point. A
+ * fixed box's containing block is the viewport unless an ancestor sets one
+ * up (a transform, a filter, `contain: paint`), as a Drawer's dialog does
+ * while it is open: the box is placed at two offsets, where it lands is
+ * measured, and the point is mapped through that block's offset and scale.
+ */
+function fixedOffsetOfClientPoint(
+ box: HTMLElement,
+ point: {x: number; y: number},
+): {x: number; y: number} {
+ box.style.left = '0px';
+ box.style.top = '0px';
+ const origin = box.getBoundingClientRect();
+ box.style.left = '100px';
+ box.style.top = '100px';
+ const shifted = box.getBoundingClientRect();
+ const scaleX = (shifted.left - origin.left) / 100 || 1;
+ const scaleY = (shifted.top - origin.top) / 100 || 1;
+ return {
+ x: (point.x - origin.left) / scaleX,
+ y: (point.y - origin.top) / scaleY,
+ };
+}
+
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` 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. The iOS
+ // callout and text selection stay off, as they always have, so a long press
+ // or a right-click opens our menu instead of selecting the trigger's text
+ // (spec:AST-017 FR59); the gesture host adds its own lock for a held press.
trigger: {
position: 'relative',
WebkitTouchCallout: 'none',
WebkitUserSelect: 'none',
userSelect: 'none',
},
+ // Where ContextMenu's menu lives: beside its trigger, in its own tree, so
+ // the menu takes what the trigger's place gives it (the theme, the
+ // direction, an enclosing dialog, popover or shadow root). It has no box.
+ menuSlot: {
+ display: 'contents',
+ },
// 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
// relative to the trigger's context — it follows the content on scroll and
// the browser can auto-flip it against the viewport edges. It owns a box
// because WebKit counts an empty anchor box as clipped, and the default
- // `position-visibility: anchors-visible` then hides the menu.
+ // `position-visibility: anchors-visible` then hides the menu. It paints
+ // nothing. While the trigger is lifted, the menu is placed against the
+ // lift's own box instead (openLifted).
cursorAnchor: {
position: 'absolute',
width: '1px',
height: '1px',
pointerEvents: 'none',
+ visibility: 'visible',
+ },
+ // The headless context menu's anchor, at a client point: it lives in the
+ // factory's own container, outside the element (createContextMenu.tsx).
+ cursorAnchorAttached: {
+ position: 'fixed',
},
menu: {
boxSizing: 'border-box',
@@ -148,6 +265,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 DropdownMenu's held finger): an internal focus target,
+ // not a control, so no browser ring; keyboard focus moves to an item
+ // instead.
+ outline: 'none',
},
// Scroll ownership by the browser's own signal; see DropdownMenu.
touchPinchZoom: {
@@ -265,11 +387,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;
@@ -316,44 +440,266 @@ export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps;
*
* ```
*/
-export function ContextMenu({
- children,
+export function ContextMenu(props: ContextMenuProps) {
+ const {
+ children,
+ triggerAs = 'div',
+ triggerXstyle,
+ ref,
+ label,
+ isDisabled,
+ onOpenChange,
+ presentation,
+ size,
+ menuWidth,
+ className,
+ style,
+ xstyle,
+ 'data-testid': testId,
+ ...rest
+ } = props;
+ // The union means exactly one of items/menuContent exists in rest; take
+ // both out so the trigger gets DOM attributes only.
+ const {items, menuContent, ...triggerProps} = rest as {
+ items?: ContextMenuOption[];
+ menuContent?: ReactNode;
+ } & Omit;
+ const hasContent = menuContent !== undefined;
+ const triggerRef = useRef(null);
+ const triggerElementRef = useMergedRefs(ref, triggerRef);
+ // The 1px cursor anchor lives inside the trigger, so the menu follows the
+ // content on scroll (#3465); the menu places it.
+ const cursorAnchorRef = useRef(null);
+ // The menu's container lives here, beside the trigger.
+ const [menuSlot, setMenuSlot] = useState(null);
+ // The factory's menu, which renders here, in ContextMenu's own tree, as a
+ // portal into its container: the caller's contexts reach it, and it
+ // unmounts with ContextMenu.
+ const [menu, setMenu] = useState(null);
+ // `menuContent` renders here, in ContextMenu's own tree (so the caller's
+ // contexts reach it), into a host the menu's container adopts. The host is
+ // a detached element, made once the menu has a place to live.
+ const slot = useMemo(
+ () =>
+ hasContent && menuSlot != null
+ ? createMenuRowsSlot(menuSlot.ownerDocument)
+ : null,
+ [hasContent, menuSlot],
+ );
+ const controllerRef = useRef(null);
+ const onOpenChangeRef = useRef(onOpenChange);
+ const handleOpenChange = useCallback((isOpen: boolean) => {
+ onOpenChangeRef.current?.(isOpen);
+ }, []);
+ const factoryOptions = (
+ rowsSlot: MenuRowsSlot | null,
+ ): CreateContextMenuOptions => {
+ const shared = {
+ label,
+ isDisabled,
+ onOpenChange: handleOpenChange,
+ presentation,
+ };
+ return rowsSlot != null
+ ? {...shared, render: rowsSlot.render}
+ : {...shared, items: items ?? NO_ITEMS};
+ };
+ const view: ContextMenuViewExtras = {
+ size,
+ menuWidth,
+ className,
+ style,
+ xstyle,
+ cursorAnchor: cursorAnchorRef.current,
+ isInline: triggerAs === 'span',
+ };
+ const latestRef = useRef({factoryOptions, view});
+
+ useIsomorphicLayoutEffect(() => {
+ onOpenChangeRef.current = onOpenChange;
+ latestRef.current = {factoryOptions, view};
+ const controller = controllerRef.current;
+ if (controller == null) {
+ return;
+ }
+ updateContextMenu(controller, factoryOptions(slot));
+ viewContextMenu(controller, {
+ ...view,
+ cursorAnchor: cursorAnchorRef.current,
+ containerParent: menuSlot,
+ });
+ });
+
+ // ContextMenu is built on the public headless context menu (spec:AST-107
+ // FR8, FR7): its trigger is the element createContextMenu attaches to.
+ useEffect(() => {
+ const trigger = triggerRef.current;
+ if (trigger == null || menuSlot == null || (hasContent && slot == null)) {
+ return;
+ }
+ const latest = latestRef.current;
+ hostContextMenuInReact(trigger, setMenu);
+ const controller = createContextMenu(trigger, latest.factoryOptions(slot));
+ viewContextMenu(controller, {
+ ...latest.view,
+ cursorAnchor: cursorAnchorRef.current,
+ containerParent: menuSlot,
+ });
+ controllerRef.current = controller;
+ return () => {
+ controller.destroy();
+ slot?.host.remove();
+ if (controllerRef.current === controller) {
+ controllerRef.current = null;
+ }
+ };
+ }, [hasContent, menuSlot, slot, triggerAs]);
+
+ // An inline trigger (`span`) lets prose own a context menu without
+ // breaking its flow.
+ const TriggerElement = triggerAs === 'div' ? 'div' : 'span';
+ return (
+ <>
+
+ {children}
+ {/* At the trigger's corner until the menu places it, so it never
+ hangs past the trigger's bottom edge (a scroll box would count
+ it). The values never change, so a render writes nothing over
+ the menu's placement. */}
+
+
+
+ {menu}
+ {slot != null
+ ? createPortal(
+ {menuContent} ,
+ slot.host,
+ )
+ : null}
+ >
+ );
+}
+
+/** The cursor anchor's place before the menu first places it. */
+const CURSOR_ANCHOR_START = {left: '0px', top: '0px'} as const;
+
+/** `items` when ContextMenu has none, one array for every render. */
+const NO_ITEMS: ContextMenuOption[] = [];
+
+/**
+ * @internal What ContextMenu tells its menu beyond the factory's options: the
+ * menu's size, width and styles, the cursor anchor inside its trigger, and
+ * whether the trigger is inline (createContextMenu.tsx, viewContextMenu).
+ */
+export interface ContextMenuViewExtras {
+ size?: 'sm' | 'md' | 'lg';
+ menuWidth?: number | string;
+ className?: string;
+ style?: React.CSSProperties;
+ xstyle?: StyleXStyles | StyleXStyles[];
+ cursorAnchor?: HTMLElement | null;
+ isInline?: boolean;
+ /** Where the menu's container goes: beside ContextMenu's trigger. */
+ containerParent?: Element | null;
+}
+
+/**
+ * A context request the headless context menu forwards to the menu
+ * (createContextMenu.tsx, from gestures/contextRequest.ts): what made it,
+ * and the client point, none for a key or for `open()` without one.
+ * @internal
+ */
+export interface ContextMenuAttachedRequest {
+ readonly kind: 'hold' | 'pointer' | 'keyboard' | 'open';
+ readonly point: {readonly x: number; readonly y: number} | null;
+}
+
+/** @internal How the headless context menu opens and closes the menu. */
+export interface ContextMenuAttachedHandle {
+ open(request: ContextMenuAttachedRequest): void;
+ close(): void;
+}
+
+/**
+ * @internal The headless context menu's element, which is the trigger, and
+ * the handle createContextMenu's own open() and close() reach the menu
+ * through.
+ */
+export interface ContextMenuAttachment {
+ readonly element: HTMLElement;
+ readonly handleRef: React.Ref;
+ /**
+ * Gives the element's context request (which createContextMenu attaches)
+ * the menu's hold: UIKit's timeline under the touch model, and the haptic
+ * at its commit.
+ */
+ readonly configureRequests: (
+ config: Pick,
+ ) => void;
+}
+
+/** @internal The menu createContextMenu renders for its element. */
+export interface ContextMenuViewProps extends ContextMenuViewExtras {
+ attachment: ContextMenuAttachment;
+ items?: ContextMenuOption[];
+ menuContent?: ReactNode;
+ label?: string;
+ isDisabled?: boolean;
+ onOpenChange?: (isOpen: boolean) => void;
+ presentation?: AdaptivePresentation;
+}
+
+/**
+ * @internal ContextMenu's menu, attached to an element: the menu of
+ * createContextMenu (spec:AST-107 FR8), which ContextMenu is built on. It
+ * attaches the element's context request, runs the touch model on it (press
+ * feedback, UIKit's timeline, the lift), and opens at the cursor anchor
+ * inside the element (ContextMenu's) or at a client point (a plain element).
+ */
+export function ContextMenuView({
+ attachment,
menuWidth,
size = 'md',
label: labelFromProps,
isDisabled = false,
onOpenChange,
- presentation = 'popover',
- triggerAs = 'div',
- ref,
+ presentation,
className,
style,
xstyle,
- triggerXstyle,
- onContextMenu: onContextMenuProp,
- onTouchStart: onTouchStartProp,
- onTouchMove: onTouchMoveProp,
- onTouchEnd: onTouchEndProp,
- onTouchCancel: onTouchCancelProp,
- 'data-testid': testId,
- ...rest
-}: ContextMenuProps) {
+ cursorAnchor: anchorInElement = null,
+ isInline = false,
+ items: itemsProp,
+ menuContent: menuContentProp,
+}: ContextMenuViewProps) {
const t = useTranslator();
const label = labelFromProps ?? t('@astryx.contextMenu.label');
const backLabel = t('@astryx.dropdownMenu.back');
- const resolvedPresentation = useAdaptivePresentation(presentation);
- const usesBottomSheet = resolvedPresentation === '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.
- const {
- items: itemsProp,
- menuContent: menuContentProp,
- ...triggerProps
- } = rest as {items?: ContextMenuOption[]; menuContent?: ReactNode} & Omit<
- typeof rest,
- 'items' | 'menuContent'
- >;
+ // The surface, and whether the touch model applies: under a finger unless
+ // the caller pins `presentation="popover"` (public-component-api INV16).
+ const {surface, touchModes} = usePresentation(presentation, {
+ whenOmitted: 'touch',
+ });
+ // The theme's compact definition, for the one-time read at the open.
+ const compact = useCompactDefinition();
+ const usesBottomSheet = surface === 'bottom-sheet';
const items = itemsProp ?? [];
const menuContent = menuContentProp;
@@ -364,7 +710,18 @@ export function ContextMenu({
// — it scrolls with the content instead of sitting at a fixed viewport point.
const positionRef = useRef({x: 0, y: 0});
const cursorAnchorRef = useRef(null);
+ // While a lift is up, the layer's anchor is the lift's box (openLifted),
+ // and the layer's anchor name, for the close, which is declared before the
+ // layer.
+ const liftAnchorRef = useRef(null);
+ const layerAnchorIdRef = useRef('');
const triggerRef = useRef(null);
+ // The headless context menu's element is the trigger.
+ useIsomorphicLayoutEffect(() => {
+ if (attachment != null) {
+ triggerRef.current = attachment.element;
+ }
+ }, [attachment]);
// Element focused before the menu opened, restored when it closes so focus
// does not fall to after Escape or outside-click dismissal.
const triggerFocusRef = useRef(null);
@@ -381,20 +738,53 @@ export function ContextMenu({
const currentTitle = currentSubmenu?.label ?? label;
const sheetLabel = typeof currentTitle === 'string' ? currentTitle : label;
+ // Whether a finger opened the menu that is up (touch invocation, below).
+ const [isTouchOpen, setIsTouchOpen] = useState(false);
+ // The mounted touch layer, for its press feedback and whether it is timing
+ // a finger.
+ const touchHandleRef = useRef(null);
+ const setTouchHandle = useCallback(
+ (handle: ContextMenuTouchHandle | null) => {
+ touchHandleRef.current = handle;
+ },
+ [],
+ );
+ // The menu closed: a finger's menu is over, and the trigger springs back
+ // with the close itself (run by every close handler below).
+ const endTouchOpen = useCallback(() => {
+ setIsTouchOpen(false);
+ touchHandleRef.current?.release();
+ // The lifted trigger returns, and the menu leaves its lifted placement:
+ // the layer's anchor is the cursor anchor again.
+ touchHandleRef.current?.presentation.drop();
+ setLiftPlacement(null);
+ const liftAnchor = liftAnchorRef.current;
+ liftAnchorRef.current = null;
+ if (liftAnchor != null) {
+ removeAnchorName(liftAnchor, layerAnchorIdRef.current);
+ const anchorEl = cursorAnchorRef.current;
+ if (anchorEl != null) {
+ addAnchorName(anchorEl, layerAnchorIdRef.current);
+ }
+ }
+ }, []);
+
const updateOpenState = useCallback(
(nextIsOpen: boolean) => {
if (!nextIsOpen) {
setSubmenuPath([]);
+ endTouchOpen();
}
setIsOpen(nextIsOpen);
onOpenChange?.(nextIsOpen);
},
- [onOpenChange],
+ [endTouchOpen, onOpenChange],
);
const layer = useLayer({
mode: 'context',
onHide: useCallback(() => {
+ endTouchOpen();
setIsOpen(false);
onOpenChange?.(false);
// Restore focus to the element that was focused before opening.
@@ -403,18 +793,24 @@ export function ContextMenu({
if (toRestore && document.contains(toRestore)) {
toRestore.focus();
}
- }, [onOpenChange]),
+ }, [endTouchOpen, onOpenChange]),
onShow: useCallback(() => {
setIsOpen(true);
onOpenChange?.(true);
}, [onOpenChange]),
lightDismiss: false,
});
+ layerAnchorIdRef.current = layer.anchorId;
+ // A lifted menu shrinks back into the finger as it closes: the lift takes
+ // its exit copy while the menu still shows (set once the menu's list ref
+ // exists, below; a no-op when nothing is lifted).
+ const dismissLiftedMenuRef = useRef<() => void>(() => {});
const closeMenu = useCallback(() => {
if (usesBottomSheet) {
updateOpenState(false);
} else {
+ dismissLiftedMenuRef.current();
layer.hide();
}
}, [layer, updateOpenState, usesBottomSheet]);
@@ -455,6 +851,12 @@ export function ContextMenu({
wrap: true,
hasPaging: true,
});
+ dismissLiftedMenuRef.current = () => {
+ const list = listRef.current;
+ if (list != null) {
+ touchHandleRef.current?.presentation.dismissMenu(list);
+ }
+ };
// Join the shared stack so an Escape press dismisses exactly one top-most
// surface. BottomSheet owns its own dismissal path.
@@ -562,17 +964,26 @@ export function ContextMenu({
// trigger (rather than storing viewport coordinates on the menu itself) is
// 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) => {
- const rect = triggerRef.current?.getBoundingClientRect();
- const x = rect ? keepAnchorInside(localX, rect.width) : localX;
- const y = rect ? keepAnchorInside(localY, rect.height) : localY;
- positionRef.current = {x, y};
- const anchorEl = cursorAnchorRef.current;
- if (anchorEl) {
- anchorEl.style.left = `${x}px`;
- anchorEl.style.top = `${y}px`;
+ // How much the press feedback has scaled a block trigger (from its center):
+ // its bounding rect is the scaled box, its offset size the unscaled one.
+ const triggerScale = useCallback(
+ (rect: DOMRect): {x: number; y: number} => {
+ const trigger = triggerRef.current;
+ if (trigger == null || isInline) {
+ return {x: 1, y: 1};
}
+ return {
+ x: trigger.offsetWidth > 0 ? rect.width / trigger.offsetWidth : 1,
+ y: trigger.offsetHeight > 0 ? rect.height / trigger.offsetHeight : 1,
+ };
+ },
+ [isInline],
+ );
+
+ // Shows the menu once its anchor is placed, focusing its first row or, for
+ // a finger, the menu itself.
+ const showMenu = useCallback(
+ (focusEl: HTMLElement | null, focusTarget: 'first' | 'menu') => {
// Remember the element focused before opening so we can restore it on
// close (Escape or outside-click), instead of dropping focus to .
triggerFocusRef.current =
@@ -583,117 +994,349 @@ export function ContextMenu({
updateOpenState(true);
} else {
layer.show();
- requestAnimationFrame(() => focusFirst());
+ requestAnimationFrame(() => {
+ if (focusTarget === 'menu') {
+ listRef.current?.focus({preventScroll: true});
+ } else {
+ focusFirst();
+ }
+ });
}
},
- [layer, focusFirst, updateOpenState, usesBottomSheet],
+ [layer, focusFirst, listRef, updateOpenState, usesBottomSheet],
);
- // The box the cursor anchor's offsets are measured from: the trigger, which
- // is its containing block.
- const getAnchorBaseRect = useCallback(
- (): DOMRect | undefined => triggerRef.current?.getBoundingClientRect(),
- [],
+ const openAtLocalPoint = useCallback(
+ (
+ 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 scale = rect ? triggerScale(rect) : {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');
+ }
+ }
+ showMenu(focusEl, focusTarget);
+ },
+ [showMenu, triggerScale],
);
- const handleContextMenu = useCallback(
- (e: React.MouseEvent) => {
- if (isDisabled) {
- return;
+ // The headless context menu's open (createContextMenu.tsx): the anchor sits
+ // at the client point in the factory's own container.
+ const openAtClientPoint = useCallback(
+ (point: {x: number; y: number}, focusTarget: 'first' | 'menu') => {
+ const anchorEl = cursorAnchorRef.current;
+ const local =
+ anchorEl != null ? fixedOffsetOfClientPoint(anchorEl, point) : point;
+ positionRef.current = local;
+ if (anchorEl != null) {
+ anchorEl.style.left = `${local.x}px`;
+ anchorEl.style.top = `${local.y}px`;
}
- e.preventDefault();
- const rect = getAnchorBaseRect();
- // A keyboard-initiated contextmenu (Shift+F10 / the Menu key) fires a
- // `contextmenu` event whose coordinates are (0, 0) in several browsers.
- // Detect that and anchor the menu to the trigger's bottom-left instead,
- // so the menu is reachable without a pointer (menus-8).
- const isKeyboardInvoked =
- e.clientX === 0 && e.clientY === 0 && e.detail === 0;
- // Convert the viewport cursor point into the trigger's local space so
- // the anchor lives inside the (scrollable) trigger context.
- const localX = isKeyboardInvoked || !rect ? 0 : e.clientX - rect.left;
- const localY =
- isKeyboardInvoked || !rect ? (rect?.height ?? 0) : e.clientY - rect.top;
- // A finger's long press reaches here as a pointer `contextmenu` where
- // the browser sends one (Chromium); its compatibility mousedown then
- // belongs to the opening press. A mouse or the keyboard opens without
- // one, so every later mousedown is a press outside.
- openingGestureRef.current =
- (e.nativeEvent as Partial).pointerType === 'touch'
- ? currentGesture()
- : null;
- openAtLocalPoint(localX, localY, e.currentTarget as HTMLElement);
+ showMenu(triggerRef.current, focusTarget);
},
- [isDisabled, openAtLocalPoint, getAnchorBaseRect],
+ [showMenu],
);
- // 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.
- const {
- onTouchStart: handleLongPressTouchStart,
- onTouchMove: handleLongPressTouchMove,
- onTouchEnd: handleLongPressTouchEnd,
- onTouchCancel: handleLongPressTouchCancel,
- } = useLongPress({
- disabled: isDisabled,
- onLongPress: useCallback(
- (point: {x: number; y: number}) => {
- const rect = getAnchorBaseRect();
- // The finger is still down: the compatibility mousedown iOS sends
- // mid-hold, or Chromium as it lifts, belongs to this press.
- openingGestureRef.current = currentGesture();
- openAtLocalPoint(
- rect ? point.x - rect.left : point.x,
- rect ? point.y - rect.top : point.y,
- triggerRef.current,
- );
+ // What reaches the menu: the element's requests and the factory's own
+ // open() and close() (set below, with the touch path).
+ const onForwardedRef = useRef<(forwarded: ContextMenuForwarded) => void>(
+ () => {},
+ );
+ // createContextMenu's own open(at) and close() take the same path as the
+ // element's requests.
+ useImperativeHandle(
+ attachment.handleRef,
+ () => ({
+ open: (request: ContextMenuAttachedRequest) => {
+ onForwardedRef.current(request);
},
- [openAtLocalPoint, getAnchorBaseRect],
- ),
- });
+ close: () => {
+ onForwardedRef.current('close');
+ },
+ }),
+ [],
+ );
- // 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],
+ // The box the cursor anchor's offsets are measured from: the trigger, which
+ // is its containing block.
+ const getAnchorBaseRect = useCallback(
+ (): DOMRect | undefined => triggerRef.current?.getBoundingClientRect(),
+ [],
);
- const handleTriggerTouchStart = useCallback(
- (event: React.TouchEvent) => {
- handleLongPressTouchStart(event);
- onTouchStartProp?.(event);
+
+ // A client point in the trigger's own coordinates, where the cursor anchor
+ // lives: its offset from the trigger's box as laid out, before the press
+ // feedback's scale (from its center), kept 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(rect);
+ 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 - left, 0), width),
+ y: Math.min(Math.max(point.y - top, 0), height),
+ };
},
- [handleLongPressTouchStart, onTouchStartProp],
+ [triggerScale],
);
- const handleTriggerTouchMove = useCallback(
- (event: React.TouchEvent) => {
- handleLongPressTouchMove(event);
- onTouchMoveProp?.(event);
+
+ // Opens the menu beside the lifted trigger: the layer's anchor moves to the
+ // lift's box at the lifted rect (an anchor inside the trigger would move
+ // with the trigger's lift, which anchor positioning follows), and the layer
+ // places the menu against it.
+ const openLifted = useCallback(
+ ({anchor}: ContextMenuLiftResult) => {
+ const anchorEl = cursorAnchorRef.current;
+ if (anchorEl != null) {
+ removeAnchorName(anchorEl, layer.anchorId);
+ }
+ addAnchorName(anchor, layer.anchorId);
+ liftAnchorRef.current = anchor;
+ triggerFocusRef.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : triggerRef.current;
+ layer.show();
+ // A touch opened it: the menu itself takes the focus, so no row is lit
+ // until the finger moves onto one (as openAtLocalPoint's touch path).
+ requestAnimationFrame(() => {
+ listRef.current?.focus({preventScroll: true});
+ });
},
- [handleLongPressTouchMove, onTouchMoveProp],
+ [layer, listRef],
);
- const handleTriggerTouchEnd = useCallback(
- (event: React.TouchEvent) => {
- handleLongPressTouchEnd();
- onTouchEndProp?.(event);
+
+ // The lift presentation (ContextMenuLift.tsx, run by the touch layer): when
+ // the menu shows under a finger, the trigger's preview lifts above a tinted
+ // backdrop and the menu sits beside it.
+ // A lift whose menu waits for its side to render, and the finger it grows
+ // out of.
+ const pendingLiftRef = useRef<{
+ lifted: ContextMenuLiftResult;
+ press: {x: number; y: number};
+ isShown: boolean;
+ } | null>(null);
+ const [liftPlacement, setLiftPlacement] =
+ useState(null);
+ // The lifted menu, once its first side (below) has rendered: show it,
+ // measure it, and move it above before the frame paints if it does not fit
+ // (a state update in a layout effect renders again before paint). It then
+ // grows out of the finger, from the side it settled on.
+ useIsomorphicLayoutEffect(() => {
+ const pending = pendingLiftRef.current;
+ if (pending == null || liftPlacement == null) {
+ return;
+ }
+ if (!pending.isShown) {
+ pending.isShown = true;
+ openLifted(pending.lifted);
+ const touch = touchHandleRef.current;
+ const menuHeight = listRef.current?.offsetHeight ?? 0;
+ if (touch != null) {
+ const placement = touch.placeMenu(pending.lifted, menuHeight);
+ if (placement.side !== liftPlacement.side) {
+ setLiftPlacement(placement);
+ return;
+ }
+ }
+ }
+ pendingLiftRef.current = null;
+ const menu = listRef.current?.closest('[popover]');
+ if (menu != null) {
+ touchHandleRef.current?.presentation.morphMenu(menu, pending.press);
+ }
+ }, [liftPlacement, openLifted, listRef]);
+ // Touch invocation (menus-8). Under the touch model the touch layer
+ // (ContextMenuTouchLayer.tsx) 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}) => {
+ // Read once, at the open: the render value can be a frame behind a
+ // pointer change (a trackpad docking).
+ const opensUnderFinger = readPresentation(presentation, {
+ whenOmitted: 'touch',
+ compact,
+ }).touchModes;
+ setIsTouchOpen(opensUnderFinger);
+ // UIKit's presentation under a finger (spec:AST-094 FR33): the preview
+ // lifts and the menu sits beside it. An inline trigger, a fine pointer,
+ // `presentation="popover"` and the sheet keep the menu where it opens.
+ const touch = touchHandleRef.current;
+ const trigger = triggerRef.current;
+ if (
+ touch != null &&
+ trigger != null &&
+ !usesBottomSheet &&
+ !isInline &&
+ opensUnderFinger
+ ) {
+ // The lift grows on from where the press feedback left the trigger,
+ // which hands the trigger's scale over to the lift. The feedback
+ // lets go once the lift has read the page, before it writes, so the
+ // page restyles once for both.
+ const pressed = trigger.getBoundingClientRect();
+ const lifted = touch.presentation.lift(
+ {
+ x: pressed.left,
+ y: pressed.top,
+ width: pressed.width,
+ height: pressed.height,
+ },
+ touch.end,
+ );
+ // A lift that did not happen lets go too (end is idempotent).
+ touch.end();
+ if (lifted != null) {
+ // The menu's side depends on its height: it renders below first,
+ // and the layout effect above shows it, measures it, moves it above
+ // before the frame paints if it does not fit, and then grows it out
+ // of the finger.
+ pendingLiftRef.current = {lifted, press: point, isShown: false};
+ setLiftPlacement(touch.placeMenu(lifted, 0));
+ return;
+ }
+ }
+ // Otherwise the menu opens under the finger: at the anchor inside the
+ // element (openAtLocalPoint cancels the trigger's scale there), or at
+ // the client point.
+ if (anchorInElement == null) {
+ openAtClientPoint(point, 'menu');
+ return;
+ }
+ const local = toTriggerLocal(point);
+ openAtLocalPoint(local.x, local.y, triggerRef.current, 'menu');
},
- [handleLongPressTouchEnd, onTouchEndProp],
+ [
+ anchorInElement,
+ compact,
+ isInline,
+ openAtClientPoint,
+ openAtLocalPoint,
+ presentation,
+ toTriggerLocal,
+ usesBottomSheet,
+ ],
);
- const handleTriggerTouchCancel = useCallback(
- (event: React.TouchEvent) => {
- handleLongPressTouchCancel();
- onTouchCancelProp?.(event);
- },
- [handleLongPressTouchCancel, onTouchCancelProp],
+ // The page stays put while a menu a finger opened is up, as it does under
+ // UIKit's context menu. A sheet locks the page itself. (The lifted trigger
+ // and the menu's anchor are fixed to the viewport in the top layer, so
+ // pinning the page moves neither.)
+ useScrollLock(isOpen && isTouchOpen && !usesBottomSheet);
+
+ // The element's context request (a held finger or pen, a right click,
+ // Shift+F10 or the context-menu key, once per gesture), through the request
+ // core (contextMenuRequests.ts, spec:AST-107 FR8), and the factory's own
+ // open() and close() reach the menu here. Under the touch model the hold
+ // runs on UIContextMenuInteraction's timeline; otherwise a finger's hold
+ // opens the menu at 500 ms, as before (public-component-api INV16).
+ onForwardedRef.current = forwarded => {
+ if (forwarded === 'close') {
+ closeMenu();
+ return;
+ }
+ const {kind, point} = forwarded;
+ if (kind === 'hold' && touchModes && point != null) {
+ // The press feedback stops where it is, and the menu opens under the
+ // finger: UIKit's presentation (the lift) where it applies.
+ touchHandleRef.current?.hold();
+ openFromFinger(point);
+ return;
+ }
+ // A finger's compatibility mousedown, sent mid-hold or at the lift,
+ // belongs to the press that opened the menu (spec:AST-094 FR33).
+ openingGestureRef.current = kind === 'hold' ? currentGesture() : null;
+ const rect = getAnchorBaseRect();
+ if (anchorInElement == null) {
+ // A plain element: the factory's own anchor, at the client point, or
+ // at the element's bottom-left corner for a key or open() without a
+ // point (menus-8). A finger's open lights no row until it moves onto
+ // one.
+ openAtClientPoint(
+ point ?? {x: rect?.left ?? 0, y: rect?.bottom ?? 0},
+ kind === 'hold' ? 'menu' : 'first',
+ );
+ return;
+ }
+ if (point == null || rect == null) {
+ // A key's request, or open() without a point: the trigger's
+ // bottom-left corner, so the menu is reachable without a pointer
+ // (menus-8).
+ openAtLocalPoint(0, rect?.height ?? 0, triggerRef.current);
+ return;
+ }
+ openAtLocalPoint(
+ point.x - rect.left,
+ point.y - rect.top,
+ triggerRef.current,
+ );
+ };
+ // At the commit the click haptic plays, where a vibration motor is the only
+ // haptic (iOS Safari can play none: no tap lands at the commit).
+ const onHoldRef = useRef>(
+ () => {},
);
+ onHoldRef.current = phase => {
+ if (phase === 'committed' && touchModes) {
+ touchHandleRef.current?.commit();
+ }
+ };
+ // The element's request runs the menu's hold: UIKit's timeline under the
+ // touch model, today's long press otherwise.
+ useEffect(() => {
+ attachment.configureRequests({
+ hold: touchModes ? CONTEXT_MENU_TOUCH_HOLD : undefined,
+ onHold: phase => onHoldRef.current(phase),
+ });
+ }, [attachment, touchModes]);
+ // Under the touch model the element is a pressable surface of core's one
+ // press machine (utils/pressFeedback.ts): the touch layer installs the
+ // machine, and its press feedback follows the pressed state.
+ useEffect(() => {
+ const element = attachment.element;
+ if (
+ !touchModes ||
+ isDisabled ||
+ element.hasAttribute(PRESSABLE_ATTRIBUTE)
+ ) {
+ return;
+ }
+ element.setAttribute(PRESSABLE_ATTRIBUTE, '');
+ return () => {
+ element.removeAttribute(PRESSABLE_ATTRIBUTE);
+ };
+ }, [attachment, isDisabled, touchModes]);
const popoverXstyle = menuWidth
? styles.popoverCustomWidth(menuWidth)
@@ -825,58 +1468,78 @@ export function ContextMenu({
renderedMenu
);
- // An inline trigger (`span`) lets prose own a context menu without
- // breaking its flow.
- const TriggerElement = triggerAs === 'div' ? 'div' : 'span';
+ const cursorAnchorElementRef = useMergedRefs(cursorAnchorRef, layer.ref);
+ // ContextMenu's anchor lives inside its trigger (so the menu follows the
+ // content on scroll); the layer anchors the menu to it.
+ useIsomorphicLayoutEffect(() => {
+ if (anchorInElement == null) {
+ return;
+ }
+ cursorAnchorElementRef(anchorInElement);
+ return () => {
+ cursorAnchorElementRef(null);
+ };
+ }, [anchorInElement, cursorAnchorElementRef]);
- return (
- <>
-
- {children}
-
-
+ },
+ )}
+ />
+ ) : null;
+
+ const menuSurface = usesBottomSheet ? (
+
+
+ {renderedBottomSheetContent}
+
+
+ ) : (
+ layer.render(
+ {renderedMenu} ,
+ liftPlacement != null
+ ? {
+ placement: liftPlacement.side,
+ alignment: liftPlacement.alignment,
+ offset: liftPlacement.gap,
+ xstyle: [popoverXstyle],
+ }
+ : {
+ placement: 'below',
+ alignment: 'start',
+ xstyle: [popoverXstyle, layerAnimations.below],
+ },
+ )
+ );
- {usesBottomSheet ? (
-
-
- {renderedBottomSheetContent}
-
-
- ) : (
- layer.render({renderedMenu} , {
- placement: 'below',
- alignment: 'start',
- xstyle: [popoverXstyle, layerAnimations.below],
- })
- )}
+ return (
+ <>
+ {ownCursorAnchor}
+ {touchModes && !isDisabled ? (
+
+ ) : null}
+ {menuSurface}
>
);
}
diff --git a/packages/core/src/ContextMenu/ContextMenuLift.test.tsx b/packages/core/src/ContextMenu/ContextMenuLift.test.tsx
new file mode 100644
index 0000000000000..36a6c058482bb
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuLift.test.tsx
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuLift.test.tsx
+ * @input vitest (jsdom), Testing Library, useContextMenuLift with the lift
+ * module stubbed so its options can be read
+ * @output Checks that every spring the context menu's lift plays is an
+ * internal motion role (spec:AST-094 FR4): the preview's growth, its return,
+ * the tint, the shadow, the menu and its close
+ * @position Testing for ContextMenuLift.tsx
+ */
+
+import {render} from '@testing-library/react';
+import {useRef} from 'react';
+import {expect, it, vi} from 'vitest';
+import type {LiftFromTriggerOptions} from '../liftFromTrigger/liftFromTrigger';
+import {motionRoleOf} from '../motion/roles';
+import {useContextMenuLift} from './ContextMenuLift';
+
+const seen: {options: LiftFromTriggerOptions | null} = {options: null};
+
+vi.mock('../liftFromTrigger/useLiftFromTrigger', () => ({
+ useLiftFromTrigger: () => ({
+ lift: (_source: HTMLElement, options: LiftFromTriggerOptions) => {
+ seen.options = options;
+ return null;
+ },
+ presentSurface: () => {},
+ dismissSurface: () => {},
+ drop: () => {},
+ dispose: () => {},
+ isLifted: () => false,
+ }),
+}));
+
+function Lifted({onReady}: {onReady: (lift: () => void) => void}) {
+ const ref = useRef(null);
+ const lift = useContextMenuLift(ref);
+ onReady(() => {
+ lift.lift();
+ });
+ return card
;
+}
+
+it('plays every spring of the lift through an internal motion role (spec:AST-094 FR4)', () => {
+ let run: () => void = () => {};
+ render(
+ {
+ run = lift;
+ }}
+ />,
+ );
+ run();
+ const motion = seen.options?.motion ?? {};
+ expect(
+ Object.fromEntries(
+ Object.entries(motion).map(([use, spring]) => [
+ use,
+ motionRoleOf(spring)?.id ?? null,
+ ]),
+ ),
+ ).toEqual({
+ lift: 'springs.contextMenuLift',
+ drop: 'springs.contextMenuDismiss',
+ clear: 'springs.contextMenuDismiss',
+ shadowIn: 'springs.contextMenuMorph',
+ shadowOut: 'springs.contextMenuMorph',
+ surfaceIn: 'springs.contextMenuMorph',
+ surfaceOut: 'springs.menuClose',
+ });
+});
diff --git a/packages/core/src/ContextMenu/ContextMenuLift.tsx b/packages/core/src/ContextMenu/ContextMenuLift.tsx
new file mode 100644
index 0000000000000..b5a54bf4a327d
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuLift.tsx
@@ -0,0 +1,159 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file ContextMenuLift.tsx
+ * @input The trigger element, the lift module (liftFromTrigger/), the context-menu
+ * constants and springs, the app's declared layer inset (LayerProvider)
+ * @output Exports useContextMenuLift: lift() / drop() to show UIKit's lifted
+ * preview over a tinted backdrop and to return it to its place, and the
+ * menu's growth out of the finger beside it and its shrink back into it,
+ * on the lift module with UIKit's numbers
+ * @position The lift presentation of ContextMenu's touch invocation, run by
+ * the touch layer (ContextMenuTouchLayer.tsx); ContextMenu.tsx places the
+ * menu beside the preview it lifts
+ *
+ * When a context menu shows on iOS 26.2, the long-pressed view lifts out of
+ * the page (UIKit's preview platter): it grows on from the size the press
+ * gave it to its lifted size, a shadow rising under it, above a backdrop
+ * that tints the page (no blur, no zoom), and the menu grows out of the
+ * finger beside it.
+ * When the menu closes, it shrinks back into the finger as it fades, while
+ * the view returns to its place and the backdrop and the shadow clear.
+ *
+ * The lift module (liftFromTrigger/liftFromTrigger.ts) plays it: the trigger itself lifts into the
+ * top layer, with one placeholder holding its spot, and nothing of the lift
+ * is in the DOM at rest. ContextMenu supplies UIKit's numbers: the scale rule
+ * (`contextMenu.lift`), its measured springs (internal: touch motion has no
+ * theme surface), the
+ * tint (the theme's modal overlay, `--color-overlay`; UIKit's own is #16152A
+ * at 21 %) and the shadow (the theme's `--shadow-high`; UIKit's: black at
+ * 0.30, radius 20, no offset, shaped by the view's pixels). A block trigger
+ * lifts; an inline one keeps the cursor menu. The menu grows out of the
+ * press from `contextMenu.lift.morphStartWidth`, in its own aspect, on
+ * `springs.contextMenuMorph` (the module's rect morph: translate, scale and opacity only,
+ * so UIKit's blob and the content's blur and clip are not played).
+
+ *
+ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx
+ * and /packages/core/src/ContextMenu/__tests__/ContextMenuLift.interaction.browser.spec.ts
+ */
+
+import {use, useMemo, useRef, type RefObject} from 'react';
+import {LayerContext, type LayerInset} from '../Layer/LayerContext';
+import type {
+ LiftFromTriggerMotion,
+ LiftFromTriggerResult,
+} from '../liftFromTrigger/liftFromTrigger';
+import {useLiftFromTrigger} from '../liftFromTrigger/useLiftFromTrigger';
+import type {MorphRect} from '../motion/rectMorph';
+import {
+ contextMenu,
+ registerContextMenuTable,
+} from '../motion/uikit/contextMenu';
+import {registerSpringsTable, springs} from '../motion/uikit/springs';
+
+const LIFT = contextMenu.lift;
+
+/**
+ * The lift's springs, as measured, each an internal motion role
+ * (`spec:AST-094` FR4): the preview grows and the tint fades in on
+ * `springs.contextMenuLift`, the menu enters and the shadow rises and fades on
+ * `springs.contextMenuMorph`. The close: the menu shrinks back into the press
+ * on `springs.menuClose`, the spring a menu's close plays on (`spec:AST-094`
+ * FR31), while the preview returns and the tint clears on UIKit's measured
+ * dismissal, `springs.contextMenuDismiss` (the same spring).
+ */
+const MOTION: LiftFromTriggerMotion = {
+ lift: springs.contextMenuLift,
+ drop: springs.contextMenuDismiss,
+ clear: springs.contextMenuDismiss,
+ shadowIn: springs.contextMenuMorph,
+ shadowOut: springs.contextMenuMorph,
+ surfaceIn: springs.contextMenuMorph,
+ surfaceOut: springs.menuClose,
+};
+
+/** Where a lift landed: the view's box, the preview's, and the viewport. */
+export type ContextMenuLiftResult = LiftFromTriggerResult;
+
+export interface ContextMenuLift {
+ /**
+ * Lift the trigger from `from` (where the press feedback left it, client
+ * px; its box by default). `release` runs once the lift has read the page,
+ * before it writes: the press feedback lets go there. Returns where it
+ * landed, or null without the popover API.
+ */
+ lift(from?: MorphRect, release?: () => void): ContextMenuLiftResult | null;
+ /**
+ * The menu's entrance beside the lifted preview: it grows out of `press`
+ * (client px) into its frame as it fades in. The lift layer takes no touch
+ * until the lift and the menu settle (spec:AST-094 FR35).
+ */
+ morphMenu(menu: HTMLElement, press: {x: number; y: number}): void;
+ /**
+ * The menu is closing: its exit copy (the layer runtime's) shrinks back
+ * into the finger from wherever its growth stands, with its velocity.
+ * Call it while the menu still shows; a no-op when nothing is lifted.
+ */
+ dismissMenu(menu: HTMLElement): void;
+ /** Return the preview to its place. */
+ drop(): void;
+}
+
+export function useContextMenuLift(
+ triggerRef: RefObject,
+ {
+ onBackdropTap,
+ }: {
+ /**
+ * A finger lifted on the backdrop: UIKit ends the presentation at that
+ * lift. (WebKit sends no mouse events for a tap on the bare backdrop, so
+ * the document's outside-press handler cannot stand in.)
+ */
+ onBackdropTap?: () => void;
+ } = {},
+): ContextMenuLift {
+ const lift = useLiftFromTrigger();
+ const onBackdropTapRef = useRef(onBackdropTap);
+ onBackdropTapRef.current = onBackdropTap;
+ // The app's declared inset (LayerProvider), which the gutter adds.
+ const layerInsetRef = useRef(undefined);
+ layerInsetRef.current = use(LayerContext)?.inset;
+ return useMemo(
+ () => ({
+ lift(from, release) {
+ const trigger = triggerRef.current;
+ if (trigger == null) {
+ return null;
+ }
+ // The springs' tables register before the first motion (idempotent),
+ // so every spring the lift plays resolves through its role
+ // (spec:AST-094 FR4).
+ registerContextMenuTable();
+ registerSpringsTable();
+ return lift.lift(trigger, {
+ motion: MOTION,
+ scale: {maxScale: LIFT.maxScale, scaleUpPoints: LIFT.scaleUpPoints},
+ surfaceStartWidth: LIFT.morphStartWidth,
+ from,
+ release,
+ inset: layerInsetRef.current,
+ onBackdropTap: () => onBackdropTapRef.current?.(),
+ attribute: 'data-astryx-context-menu-lift',
+ });
+ },
+ morphMenu(menu, press) {
+ lift.presentSurface(menu, press);
+ },
+ dismissMenu(menu) {
+ lift.dismissSurface(menu);
+ },
+ drop() {
+ lift.drop();
+ },
+ }),
+ [lift, triggerRef],
+ );
+}
diff --git a/packages/core/src/ContextMenu/ContextMenuOnFactory.test.tsx b/packages/core/src/ContextMenu/ContextMenuOnFactory.test.tsx
new file mode 100644
index 0000000000000..eb0089c12a1cd
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuOnFactory.test.tsx
@@ -0,0 +1,205 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuOnFactory.test.tsx
+ * @input vitest (jsdom), ContextMenu with createContextMenu watched
+ * @output Checks that ContextMenu is built on the public headless context
+ * menu (spec:AST-107 FR8, FR7; component:ContextMenu FR10): it attaches
+ * createContextMenu to its own trigger, with its items or a `render` for
+ * its rows, which still read the caller's own contexts; unmounting while
+ * open removes everything; and its source attaches no request of its own
+ * @position Testing for ContextMenu.tsx over createContextMenu.tsx
+ */
+
+import {readFileSync} from 'node:fs';
+import {join} from 'node:path';
+import {act, render, screen} from '@testing-library/react';
+import {createContext, use} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {ContextMenu} from './ContextMenu';
+import {DropdownMenuItem as ContextMenuItem} from '../DropdownMenu/DropdownMenuItem';
+import {dataAttr} from '../naming';
+import {createContextMenu} from './createContextMenu';
+
+// The real factory, watched: ContextMenu must go through it.
+vi.mock('./createContextMenu', async importOriginal => {
+ const actual = await importOriginal();
+ return {...actual, createContextMenu: vi.fn(actual.createContextMenu)};
+});
+
+/** The options the public factory takes (spec:AST-107 FR8). */
+const FACTORY_OPTIONS = new Set([
+ 'items',
+ 'render',
+ 'label',
+ 'isDisabled',
+ 'onOpenChange',
+ 'presentation',
+]);
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function rightClick(target: Element) {
+ act(() => {
+ target.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 20,
+ clientY: 20,
+ button: 2,
+ }),
+ );
+ });
+}
+
+describe('ContextMenu on createContextMenu (spec:AST-107 FR8, FR7)', () => {
+ it('attaches the public createContextMenu to its own trigger, with its items', () => {
+ vi.mocked(createContextMenu).mockClear();
+ render(
+
+ Area
+ ,
+ );
+ expect(vi.mocked(createContextMenu)).toHaveBeenCalledTimes(1);
+ const [element, options] = vi.mocked(createContextMenu).mock.calls[0] ?? [];
+ expect(element).toBe(screen.getByTestId('trigger'));
+ expect(
+ Object.keys(options ?? {}).filter(key => !FACTORY_OPTIONS.has(key)),
+ ).toEqual([]);
+ expect(options?.items).toEqual([{label: 'Rename'}]);
+ expect(options?.label).toBe('File actions');
+ });
+
+ it('hands the public createContextMenu a `render` for its menuContent', () => {
+ vi.mocked(createContextMenu).mockClear();
+ render(
+ }
+ data-testid="trigger">
+ Area
+ ,
+ );
+ expect(vi.mocked(createContextMenu)).toHaveBeenCalledTimes(1);
+ const [element, options] = vi.mocked(createContextMenu).mock.calls[0] ?? [];
+ expect(element).toBe(screen.getByTestId('trigger'));
+ expect(
+ Object.keys(options ?? {}).filter(key => !FACTORY_OPTIONS.has(key)),
+ ).toEqual([]);
+ expect(typeof options?.render).toBe('function');
+ expect(options?.items).toBeUndefined();
+ });
+
+ it("a row in menuContent reads the caller's own context", () => {
+ const AppContext = createContext('no app context');
+ AppContext.displayName = 'AppContext';
+ function AppRow() {
+ return ;
+ }
+ render(
+
+ }>
+ Area
+
+ ,
+ );
+ rightClick(screen.getByText('Area'));
+ expect(
+ screen.getByRole('menuitem', {name: 'from the app', hidden: true}),
+ ).not.toBeNull();
+ });
+
+ it('unmounting while open removes the menu, its container and the trigger\u2019s request (component:ContextMenu FR10)', () => {
+ const view = render(
+
+ Area
+ ,
+ );
+ const trigger = screen.getByTestId('trigger');
+ rightClick(trigger);
+ expect(document.querySelector('[role="menu"]')).not.toBeNull();
+ view.unmount();
+ expect(document.querySelector('[role="menu"]')).toBeNull();
+ expect(
+ document.querySelector(`[${dataAttr('context-menu-host')}]`),
+ ).toBeNull();
+ // The trigger's request is gone: the browser keeps its own menu.
+ const request = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ trigger.dispatchEvent(request);
+ expect(request.defaultPrevented).toBe(false);
+ });
+
+ it('attaches no request and keeps no open state of its own: its source makes no request call (component:ContextMenu FR10)', () => {
+ const source = readFileSync(
+ join(process.cwd(), 'packages/core/src/ContextMenu/ContextMenu.tsx'),
+ 'utf8',
+ );
+ expect(source).not.toMatch(
+ /attachContextRequest\(|attachContextMenuRequests\(/,
+ );
+ });
+
+ it('unmounting leaves React no root to unmount during its own commit, so it logs no error', () => {
+ const errors = vi.spyOn(console, 'error');
+ try {
+ const view = render(
+
+ Area
+ ,
+ );
+ rightClick(screen.getByTestId('trigger'));
+ expect(document.querySelector('[role="menu"]')).not.toBeNull();
+ view.unmount();
+ const messages = errors.mock.calls.map(call => String(call[0]));
+ expect(
+ messages.filter(message =>
+ message.includes('synchronously unmount a root'),
+ ),
+ ).toEqual([]);
+ } finally {
+ errors.mockRestore();
+ }
+ });
+
+ it('unmounting the whole React root around an open ContextMenu throws nothing afterwards', async () => {
+ const thrown: unknown[] = [];
+ const onError = (event: ErrorEvent) => {
+ thrown.push(event.error ?? event.message);
+ };
+ window.addEventListener('error', onError);
+ try {
+ const view = render(
+
+ Area
+ ,
+ );
+ rightClick(screen.getByTestId('trigger'));
+ expect(document.querySelector('[role="menu"]')).not.toBeNull();
+ // The test's root goes with everything in its container.
+ view.unmount();
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(thrown).toEqual([]);
+ } finally {
+ window.removeEventListener('error', onError);
+ }
+ });
+});
diff --git a/packages/core/src/ContextMenu/ContextMenuRequest.test.tsx b/packages/core/src/ContextMenu/ContextMenuRequest.test.tsx
new file mode 100644
index 0000000000000..d7b3319f6734a
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuRequest.test.tsx
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuRequest.test.tsx
+ * @input vitest (jsdom), ContextMenu with its trigger's context request
+ * replaced by a fake that registers nothing and captures what it is given
+ * @output Checks that ContextMenu is built on createContextMenu (spec:AST-107
+ * FR8, FR7): one context request is attached to its trigger, the menu opens
+ * only through it (a right click the request did not make opens nothing), a
+ * pointer's or a key's request opens it with the first row focused, a
+ * disabled ContextMenu's request is off, and unmounting detaches it
+ * @position Testing for ContextMenu.tsx over createContextMenu.tsx
+ */
+
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import type {
+ ContextRequest,
+ ContextRequestOptions,
+} from '../gestures/contextRequest';
+import {ContextMenu} from './ContextMenu';
+
+const attached: {element: HTMLElement; options: ContextRequestOptions}[] = [];
+const detach = vi.fn();
+
+vi.mock('../gestures/contextRequest', async importOriginal => ({
+ ...(await importOriginal()),
+ attachContextRequest: (
+ element: HTMLElement,
+ options: ContextRequestOptions,
+ ) => {
+ attached.push({element, options});
+ return detach;
+ },
+}));
+
+beforeEach(() => {
+ attached.length = 0;
+ detach.mockClear();
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function request(
+ kind: ContextRequest['kind'],
+ point: {x: number; y: number} | null,
+): ContextRequest {
+ return {
+ kind,
+ pointerType:
+ kind === 'keyboard' ? null : kind === 'hold' ? 'touch' : 'mouse',
+ point,
+ pointerId: null,
+ time: 0,
+ };
+}
+
+function renderMenu(props: {isDisabled?: boolean} = {}) {
+ return render(
+
+ Right-click me
+ ,
+ );
+}
+
+const rows = () => screen.queryAllByRole('menuitem', {hidden: true});
+
+describe('ContextMenu over createContextMenu', () => {
+ it('attaches one context request to its trigger', () => {
+ renderMenu();
+ expect(attached).toHaveLength(1);
+ expect(attached[0].element).toBe(screen.getByTestId('ctx'));
+ });
+
+ it('opens only through the request: a right click it did not make opens nothing', () => {
+ renderMenu();
+ fireEvent.contextMenu(screen.getByTestId('ctx'), {
+ clientX: 20,
+ clientY: 20,
+ });
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+ });
+
+ it("a pointer's request opens the menu with the first row focused", async () => {
+ renderMenu();
+ act(() => {
+ attached[0].options.onRequest(request('pointer', {x: 20, y: 20}));
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ });
+
+ it("a key's request opens the menu at the trigger with the first row focused", async () => {
+ renderMenu();
+ act(() => {
+ attached[0].options.onRequest(request('keyboard', null));
+ });
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ });
+
+ it("a disabled ContextMenu's request is off", () => {
+ renderMenu({isDisabled: true});
+ const isEnabled = attached.at(-1)?.options.isEnabled;
+ expect(isEnabled?.() ?? true).toBe(false);
+ });
+
+ it('unmounting detaches the request', () => {
+ const view = renderMenu();
+ view.unmount();
+ expect(detach).toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/ContextMenu/ContextMenuTouch.ts b/packages/core/src/ContextMenu/ContextMenuTouch.ts
new file mode 100644
index 0000000000000..0990e7f208af9
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuTouch.ts
@@ -0,0 +1,24 @@
+// 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 feedback
+ * (contextMenuPressFeedback.ts) and the lift presentation
+ * (ContextMenuLift.tsx, contextMenuLiftGeometry.ts)
+ * @position ContextMenuTouchLayer.tsx, which ContextMenu imports
+ * 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 {useContextMenuPressFeedback} from './contextMenuPressFeedback';
+export {
+ useContextMenuLift,
+ type ContextMenuLift,
+ type ContextMenuLiftResult,
+} from './ContextMenuLift';
+export {menuPlacement, type MenuPlacement} from './contextMenuLiftGeometry';
diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx
new file mode 100644
index 0000000000000..476961f0671bd
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuTouchLayer.tsx
@@ -0,0 +1,113 @@
+// 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
+ * feedback and the lift presentation while ContextMenu is under the touch
+ * model; the hold is the trigger's context request (ContextMenu.tsx)
+ * @position Imported by ContextMenu, which renders it only while the touch
+ * model applies: a fine pointer runs none of it
+ *
+ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx
+ */
+
+import {useEffect, useRef, type RefObject} from 'react';
+import {playHaptic} from '../gestures';
+import {contextMenu} from '../motion/uikit/contextMenu';
+import {
+ menuPlacement,
+ useContextMenuLift,
+ useContextMenuPressFeedback,
+ type ContextMenuLift,
+ type ContextMenuLiftResult,
+ type MenuPlacement,
+} from './ContextMenuTouch';
+
+/** Where the lifted menu sits, and its gap from the lifted preview, in px. */
+export interface LiftedMenuPlacement extends MenuPlacement {
+ readonly gap: number;
+}
+
+/** What ContextMenu reaches of a mounted touch layer. */
+export interface ContextMenuTouchHandle {
+ /** The menu the press opened closed: the trigger springs back. */
+ release(): void;
+ /** The trigger stops growing at once: the lift takes it from here. */
+ end(): void;
+ /** The hold committed: the click haptic plays where a motor is the only haptic. */
+ commit(): void;
+ /** The hold's menu opens: the press feedback stops growing where it is. */
+ hold(): void;
+ /**
+ * The lift presentation (ContextMenuLift.tsx): the trigger lifted above
+ * the tint, and the menu's entrance and exit beside it.
+ */
+ readonly presentation: ContextMenuLift;
+ /** Where the lifted menu sits for its rendered height (contextMenu.lift). */
+ placeMenu(
+ lifted: ContextMenuLiftResult,
+ menuHeight: number,
+ ): LiftedMenuPlacement;
+}
+
+export interface ContextMenuTouchLayerProps {
+ triggerRef: RefObject;
+ /** False for an inline trigger, which does not grow. */
+ isShown: boolean;
+ /** Changes when the trigger element is replaced (`triggerAs`). */
+ triggerKey: unknown;
+ /** Receives the layer's handle as it mounts, and null as it unmounts. */
+ onHandleChange: (handle: ContextMenuTouchHandle | null) => void;
+ /** A finger lifted on the lift's tint: the menu closes. */
+ onBackdropTap: () => void;
+}
+
+/**
+ * UIContextMenuInteraction's press feedback and lift. The trigger's context
+ * request runs the hold on UIKit's timeline (contextMenu.press) and claims the
+ * finger at the commit (the page stops scrolling under it, and its lift sends
+ * no click and no compatibility mouse events); ContextMenu calls `commit()`
+ * there, for the haptic, and `hold()` as the menu opens where the finger
+ * landed. The press feedback grows the trigger while core's press machine
+ * believes the press, springs back when it ends with no menu, and holds while
+ * the menu it opened is up.
+ */
+export function ContextMenuTouchLayer({
+ triggerRef,
+ isShown,
+ triggerKey,
+ onHandleChange,
+ onBackdropTap,
+}: ContextMenuTouchLayerProps): null {
+ const feedback = useContextMenuPressFeedback(triggerRef, isShown, triggerKey);
+ // The lift presentation: ContextMenu decides when a press lifts the
+ // trigger, and drives it through the handle.
+ const lift = useContextMenuLift(triggerRef, {onBackdropTap});
+ const liftRef = useRef(lift);
+ liftRef.current = lift;
+ const feedbackRef = useRef(feedback);
+ feedbackRef.current = feedback;
+
+ useEffect(() => {
+ onHandleChange({
+ release: () => feedbackRef.current.release(),
+ end: () => feedbackRef.current.end(),
+ commit: () => playHaptic(contextMenu.commitHaptic),
+ hold: () => feedbackRef.current.hold(),
+ get presentation() {
+ return liftRef.current;
+ },
+ placeMenu: (lifted, menuHeight) => ({
+ ...menuPlacement(lifted.lifted, menuHeight, lifted.viewport),
+ gap: contextMenu.lift.menuGap,
+ }),
+ });
+ return () => onHandleChange(null);
+ }, [onHandleChange]);
+
+ return null;
+}
diff --git a/packages/core/src/ContextMenu/ContextMenuTouchLayerStatic.test.tsx b/packages/core/src/ContextMenu/ContextMenuTouchLayerStatic.test.tsx
new file mode 100644
index 0000000000000..9af1bfeae205b
--- /dev/null
+++ b/packages/core/src/ContextMenu/ContextMenuTouchLayerStatic.test.tsx
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuTouchLayerStatic.test.tsx
+ * @input vitest (jsdom), Testing Library, ContextMenu under a coarse pointer
+ * @output Checks that a finger landing on the first render already runs
+ * UIKit's timeline: the touch layer is part of ContextMenu, not a load away
+ * @position Testing for ContextMenu.tsx and ContextMenuTouchLayer.tsx
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {afterEach, beforeAll, beforeEach, expect, it, vi} from 'vitest';
+import type {ContextMenu as ContextMenuComponent} from './ContextMenu';
+
+let ContextMenu: typeof ContextMenuComponent;
+
+// A cold import transforms ContextMenu's whole module graph; allow for it.
+beforeAll(async () => {
+ ({ContextMenu} = await import('./ContextMenu'));
+}, 120000);
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn();
+ HTMLElement.prototype.hidePopover = vi.fn();
+ 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(),
+ })),
+ );
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+it('a finger that lands on the first render runs UIKit’s timeline: no menu at 500 ms, the menu at 735 ms', () => {
+ vi.useFakeTimers();
+ render(
+
+ Hold me
+ ,
+ );
+ const trigger = screen.getByTestId('touch');
+ // The press recognizer is on the trigger from the first commit.
+ expect(trigger).toHaveAttribute('data-astryx-pressable');
+ fireEvent.pointerDown(trigger, {
+ pointerId: 1,
+ pointerType: 'touch',
+ isPrimary: true,
+ clientX: 20,
+ clientY: 20,
+ });
+ fireEvent.touchStart(trigger, {
+ touches: [{identifier: 1, clientX: 20, clientY: 20}],
+ });
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ // Today's 500 ms long press never runs under the touch model.
+ expect(HTMLElement.prototype.showPopover).not.toHaveBeenCalled();
+});
diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuLift.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuLift.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..e7befd788ee05
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLift.interaction.browser.spec.ts
@@ -0,0 +1,1398 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuLift.interaction.browser.spec.ts
+ * @input The built "Touch / long press" ContextMenu story, real touch input
+ * (Chromium CDP / WebKit's input command), the interaction harness, the
+ * context-menu constants and springs
+ * @output Interaction and animation proofs for the lift presentation: a held
+ * card lifts itself (no copy) to UIKit's size about its center over the
+ * theme's backdrop colour with the theme's shadow, its spot in the page
+ * held, with the menu 16 px below it and centered; open adds the lift
+ * layer, its anchor and the placeholder and nothing else; a card near the
+ * bottom gets its menu above; a card at the left edge lifts 16 px in with
+ * its menu flush; the card grows on from the press, and the backdrop fades
+ * in, on springs.contextMenuLift frame by frame; the menu fades in on
+ * springs.contextMenuMorph with no blur; closing returns the card to the page as it was
+ * and clears the backdrop; the card keeps growing on every frame through a
+ * blocked main thread; under Reduce Motion the card cross-fades in place;
+ * a storyboard of the lift
+ * @position Interaction specs of packages/core/src/ContextMenu, beside
+ * ContextMenuLongPress.interaction.browser.spec.ts (the press timeline)
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ animationStoryboard,
+ busyWindowProof,
+ castStoryboard,
+ holdAnimations,
+ openStory,
+ releaseAnimations,
+ seekAnimations,
+ startScreencast,
+ tap,
+ timeline,
+ touchDriver,
+ trackMarker,
+ withStorybook,
+ writeEvidence,
+ type BusyWindow,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+import {solveSpring, toSpring} from '../../motion/spring';
+import {springs} from '../../motion/uikit';
+import {contextMenu} from '../../motion/uikit/contextMenu';
+
+const storybook = withStorybook(test);
+const {menuDisplayMs} = contextMenu.press;
+const {menuGap} = contextMenu.lift;
+// The layer runtime's viewport gutter in these pages (spec:AST-059): the
+// spacing-4 step, with no safe area and no app-declared inset.
+const GUTTER = 16;
+
+interface Box {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+interface LiftStory {
+ driver: TouchDriver;
+ center: {x: number; y: number};
+}
+
+/**
+ * Opens the story; `moveCard` gets the card's box and returns the offset
+ * (CSS px) to move it by, for the placement cases.
+ */
+async function openLiftStory(
+ page: Page,
+ moveCard?: (
+ box: Box,
+ viewport: {width: number; height: number},
+ ) => {
+ dx: number;
+ dy: number;
+ },
+): Promise {
+ // One touch model: the engine's own finger (a coarse pointer) lifts.
+ await openStory(page, storybook(), 'core-contextmenu--touch-long-press');
+ const trigger = page.getByTestId('touch-context-menu');
+ // The touch layer, the lift included, marks the trigger pressable once it
+ // runs (from the first render under the touch model).
+ await expect(trigger).toHaveAttribute('data-astryx-pressable', '', {
+ timeout: 10_000,
+ });
+ let box = await trigger.boundingBox();
+ if (box == null) {
+ throw new Error('no trigger');
+ }
+ if (moveCard != null) {
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const {dx, dy} = moveCard(box, viewport);
+ await trigger.evaluate(
+ (el, offset) => {
+ const host = el as HTMLElement;
+ host.style.position = 'relative';
+ host.style.left = `${offset.dx}px`;
+ host.style.top = `${offset.dy}px`;
+ },
+ {dx, dy},
+ );
+ box = await trigger.boundingBox();
+ if (box == null) {
+ throw new Error('no trigger');
+ }
+ }
+ return {
+ driver: await touchDriver(page),
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ };
+}
+
+/**
+ * The card's spot in the page (its placeholder while it is lifted), the
+ * lifted card, the menu's popover and the backdrop, now.
+ */
+async function readLift(page: Page) {
+ return page.evaluate(() => {
+ const rect = (el: Element | null | undefined) => {
+ if (el == null) {
+ return null;
+ }
+ const r = el.getBoundingClientRect();
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ };
+ const trigger = document.querySelector(
+ '[data-testid="touch-context-menu"]',
+ );
+ const isLifted = trigger?.matches(':popover-open') ?? false;
+ const placeholder = document.querySelector(
+ '[data-astryx-context-menu-lift-placeholder]',
+ );
+ // The tint is the lift layer's ::backdrop; the shadow is a box in it.
+ const layer = document.querySelector('[data-astryx-context-menu-lift]');
+ const tint = layer == null ? null : getComputedStyle(layer, '::backdrop');
+ return {
+ card: rect(placeholder ?? trigger),
+ cardOpacity: trigger == null ? null : getComputedStyle(trigger).opacity,
+ preview: isLifted ? rect(trigger) : null,
+ menu: rect(document.querySelector('[role="menu"]')?.closest('[popover]')),
+ backdropColor: tint == null ? null : tint.backgroundColor,
+ // The theme's modal overlay where the card is, for comparison.
+ overlayColor: (() => {
+ const scope = trigger?.parentElement;
+ if (scope == null) {
+ return null;
+ }
+ const probe = document.createElement('span');
+ probe.style.backgroundColor = 'var(--color-overlay)';
+ scope.append(probe);
+ const color = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return color;
+ })(),
+ shadow: (() => {
+ const shadow = document.querySelector(
+ '[data-astryx-context-menu-lift-shadow]',
+ );
+ if (shadow == null) {
+ return null;
+ }
+ const style = getComputedStyle(shadow);
+ return {opacity: Number(style.opacity), boxShadow: style.boxShadow};
+ })(),
+ backdropOpacity: tint == null ? null : Number(tint.opacity),
+ layerOpen: layer?.matches(':popover-open') ?? false,
+ };
+ });
+}
+
+/**
+ * Marks every element matching `selector` (the component creates them) for
+ * the screencast tracker: an inset outline in the harness's marker colour.
+ */
+async function markSelector(page: Page, selector: string) {
+ await page.evaluate(sel => {
+ const style = document.createElement('style');
+ style.textContent = `${sel}{outline:6px solid rgb(255,0,255) !important;outline-offset:-6px !important;}`;
+ document.head.append(style);
+ }, selector);
+}
+
+/**
+ * Holds the main thread `ms` long, `afterMs` after the next touch lands (a
+ * timer set in the touch's own task, so it runs on the page's clock). Returns
+ * a reader for the window it held, epoch ms.
+ */
+async function blockAfterTouch(
+ page: Page,
+ afterMs: number,
+ ms: number,
+): Promise<() => Promise> {
+ await page.evaluate(
+ ({at, length}) => {
+ addEventListener(
+ 'touchstart',
+ () => {
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + length;
+ while (performance.now() < end) {
+ // Held: no task, frame or event runs.
+ }
+ (window as unknown as {__busy: BusyWindow}).__busy = {
+ from,
+ to: performance.timeOrigin + performance.now(),
+ };
+ }, at);
+ },
+ {once: true, capture: true, passive: true},
+ );
+ },
+ {at: afterMs, length: ms},
+ );
+ return async () =>
+ page.evaluate(() => (window as unknown as {__busy: BusyWindow}).__busy);
+}
+
+/** A finger held until the menu shows, then lifted (the menu stays). */
+/**
+ * Until the lift has grown: the layer runtime's hold, which keeps touches off
+ * the lift layer while it grows (AST-094 FR35), has ended.
+ */
+async function untilGrown(page: Page) {
+ await expect
+ .poll(
+ async () =>
+ page.evaluate(() => {
+ const layer = document.querySelector(
+ '[data-astryx-context-menu-lift]',
+ );
+ return (
+ layer != null &&
+ ![...layer.children].some(child =>
+ child.matches('div[popover]:popover-open'),
+ )
+ );
+ }),
+ {timeout: 4000},
+ )
+ .toBe(true);
+}
+
+async function liftAndSettle(page: Page, {driver, center}: LiftStory) {
+ await driver.play(tap(center, {holdMs: menuDisplayMs + 100}));
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ // The lift settles within about half a second (Linux WebKit starts a
+ // page's first animations late, so wait for the shadow to be in, too).
+ await page.waitForTimeout(800);
+ await expect
+ .poll(async () => (await readLift(page)).shadow?.opacity, {timeout: 4000})
+ .toBe(1);
+ await page.waitForTimeout(200);
+ return readLift(page);
+}
+
+test('under a finger the story has the fine pointer’s element count at rest, and open adds only the lift layer, its shadow and anchor, and the placeholder, whatever the card holds (INV7, AST-017 FR60)', async ({
+ page,
+ browser,
+}) => {
+ const count = async (target: Page) =>
+ target.evaluate(() => document.body.querySelectorAll('*').length);
+ // The fine pointer's counts, in a context without touch.
+ const fineContext = await browser.newContext({
+ viewport: page.viewportSize() ?? {width: 402, height: 874},
+ hasTouch: false,
+ isMobile: false,
+ });
+ const fine = await fineContext.newPage();
+ await openStory(fine, storybook(), 'core-contextmenu--touch-long-press');
+ // A fine pointer in this context, before any count.
+ expect(
+ await fine.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const fineRest = await count(fine);
+ const fineBox = await fine.getByTestId('touch-context-menu').boundingBox();
+ if (fineBox == null) {
+ throw new Error('no trigger');
+ }
+ await fine.mouse.click(
+ fineBox.x + fineBox.width / 2,
+ fineBox.y + fineBox.height / 2,
+ {button: 'right'},
+ );
+ await expect(fine.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ const fineOpen = await count(fine);
+ await fineContext.close();
+
+ const story = await openLiftStory(page);
+ const coarseRest = await count(page);
+ const settled = await liftAndSettle(page, story);
+ const coarseOpen = await count(page);
+ const lift = await page.evaluate(() => {
+ const layer = document.querySelector('[data-astryx-context-menu-lift]');
+ const trigger = document.querySelector(
+ '[data-testid="touch-context-menu"]',
+ );
+ return {
+ // The layer holds the shadow and the box the menu is placed against,
+ // nothing else.
+ layerChildren: layer == null ? -1 : layer.children.length,
+ hasAnchor:
+ layer?.querySelector('[data-astryx-context-menu-lift-anchor]') != null,
+ // The card lifts itself: no copy of it anywhere.
+ copies: document.querySelectorAll('[data-astryx-context-menu-preview]')
+ .length,
+ isLifted: trigger?.matches(':popover-open') ?? false,
+ placeholderAfterTrigger:
+ trigger?.nextElementSibling?.hasAttribute(
+ 'data-astryx-context-menu-lift-placeholder',
+ ) ?? false,
+ triggerDescendants:
+ trigger == null ? -1 : trigger.querySelectorAll('*').length,
+ };
+ });
+ const detail = JSON.stringify({
+ fineRest,
+ fineOpen,
+ coarseRest,
+ coarseOpen,
+ lift,
+ });
+ expect(coarseRest, detail).toBe(fineRest);
+ expect(lift.layerChildren, detail).toBe(2);
+ expect(lift.hasAnchor, detail).toBe(true);
+ expect(lift.copies, detail).toBe(0);
+ expect(lift.isLifted, detail).toBe(true);
+ expect(lift.placeholderAfterTrigger, detail).toBe(true);
+ // The layer, the shadow, the anchor and the placeholder: 4, within the 5
+ // an open layer may add under touch (AST-017 FR60, DEC-29), however many
+ // elements the card holds.
+ expect(coarseOpen - fineOpen, detail).toBe(4);
+ // A tap on the tint, on the card's own spot clear of the lifted card.
+ if (settled.card == null) {
+ throw new Error(detail);
+ }
+ await story.driver.play(
+ tap({
+ x: settled.card.x + 10,
+ y: settled.card.y + settled.card.height + 8,
+ }),
+ );
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ await expect.poll(async () => count(page), {timeout: 3000}).toBe(coarseRest);
+});
+
+test('a held card lifts itself to UIKit’s size about its center over the theme’s dim and shadow, its spot in the page held, its menu 16 px below and centered', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ // Closed, the lift layer takes no room and no touches.
+ await expect(page.locator('[data-astryx-context-menu-lift]')).toBeHidden();
+ const lift = await liftAndSettle(page, story);
+ const {card, preview, menu} = lift;
+ if (card == null || preview == null || menu == null) {
+ throw new Error(JSON.stringify(lift));
+ }
+ const detail = JSON.stringify(lift);
+ // 200 × 120 lifts by 26 pt on its longer side: 226 × 135.6.
+ expect(preview.width, detail).toBeCloseTo(226, 0);
+ expect(preview.height, detail).toBeCloseTo(135.6, 0);
+ expect(preview.x + preview.width / 2, detail).toBeCloseTo(
+ card.x + card.width / 2,
+ 0,
+ );
+ expect(preview.y + preview.height / 2, detail).toBeCloseTo(
+ card.y + card.height / 2,
+ 0,
+ );
+ expect(lift.cardOpacity, detail).toBe('1');
+ // The theme's modal overlay (`--color-overlay`), fully faded in.
+ expect(lift.overlayColor, detail).not.toBeNull();
+ expect(lift.backdropColor, detail).toBe(lift.overlayColor);
+ // The theme's high shadow, faded in under the card.
+ expect(lift.shadow?.opacity, detail).toBeCloseTo(1, 2);
+ expect(lift.shadow?.boxShadow, detail).not.toBe('none');
+ expect(lift.backdropOpacity, detail).toBeCloseTo(1, 2);
+ expect(menu.y, detail).toBeCloseTo(preview.y + preview.height + menuGap, 0);
+ expect(menu.x + menu.width / 2, detail).toBeCloseTo(
+ preview.x + preview.width / 2,
+ 0,
+ );
+});
+
+test('a card near the bottom gets its menu above, and stays inside the layer runtime’s gutter', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page, (box, viewport) => ({
+ dx: 0,
+ // The card's bottom 10 px from the viewport's.
+ dy: viewport.height - 10 - (box.y + box.height),
+ }));
+ const lift = await liftAndSettle(page, story);
+ const {preview, menu} = lift;
+ if (preview == null || menu == null) {
+ throw new Error(JSON.stringify(lift));
+ }
+ const viewport = page.viewportSize();
+ const detail = JSON.stringify({lift, viewport});
+ expect(preview.y + preview.height, detail).toBeCloseTo(
+ (viewport?.height ?? NaN) - GUTTER,
+ 0,
+ );
+ expect(menu.y + menu.height, detail).toBeCloseTo(preview.y - menuGap, 0);
+});
+
+test('a card at the left edge lifts 16 px in, and its menu is flush with it', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page, box => ({dx: 4 - box.x, dy: 0}));
+ const lift = await liftAndSettle(page, story);
+ const {preview, menu} = lift;
+ if (preview == null || menu == null) {
+ throw new Error(JSON.stringify(lift));
+ }
+ const detail = JSON.stringify(lift);
+ expect(preview.x, detail).toBeCloseTo(GUTTER, 0);
+ expect(menu.x, detail).toBeCloseTo(GUTTER, 0);
+});
+
+test('in a right-to-left page a card at the left edge keeps its menu flush with that edge (the alignment is logical)', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ const center = await page.getByTestId('touch-context-menu').evaluate(el => {
+ document.documentElement.dir = 'rtl';
+ const host = el as HTMLElement;
+ host.style.position = 'relative';
+ host.style.left = '0px';
+ const box = host.getBoundingClientRect();
+ host.style.left = `${4 - box.x}px`;
+ const moved = host.getBoundingClientRect();
+ return {x: moved.x + moved.width / 2, y: moved.y + moved.height / 2};
+ });
+ const lift = await liftAndSettle(page, {...story, center});
+ const {preview, menu} = lift;
+ if (preview == null || menu == null) {
+ throw new Error(JSON.stringify(lift));
+ }
+ const detail = JSON.stringify(lift);
+ expect(preview.x, detail).toBeCloseTo(GUTTER, 0);
+ expect(menu.x, detail).toBeCloseTo(GUTTER, 0);
+});
+
+test('the menu shows above the lifted card and takes the finger: its rows are on top', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ await liftAndSettle(page, story);
+ const share = await page.getByRole('menuitem', {name: 'Share'}).boundingBox();
+ if (share == null) {
+ throw new Error('no Share row');
+ }
+ const hit = await page.evaluate(
+ ([x, y]) =>
+ document.elementFromPoint(x, y)?.closest('[role="menuitem"]')
+ ?.textContent ?? null,
+ [share.x + share.width / 2, share.y + share.height / 2],
+ );
+ expect(hit).toContain('Share');
+});
+
+test('the card itself lifts into the top layer while its spot in the page holds, and is back in the page as it was once the menu closes', async ({
+ page,
+}) => {
+ const {driver, center} = await openLiftStory(page);
+ const trigger = page.getByTestId('touch-context-menu');
+ const menu = page.getByRole('menu', {name: 'Photo actions'});
+ const before = await trigger.evaluate(el => {
+ const r = el.getBoundingClientRect();
+ return {
+ style: (el as HTMLElement).style.cssText,
+ box: [r.x, r.y, r.width, r.height],
+ next: (() => {
+ const sibling = el.parentElement?.nextElementSibling;
+ if (sibling == null) {
+ return null;
+ }
+ const n = sibling.getBoundingClientRect();
+ return [n.x, n.y];
+ })(),
+ };
+ });
+ await driver.play(tap(center, {holdMs: menuDisplayMs + 100}));
+ await expect(menu).toBeVisible();
+ const lifted = await trigger.evaluate(el => {
+ const placeholder = document.querySelector(
+ '[data-astryx-context-menu-lift-placeholder]',
+ );
+ const r = placeholder?.getBoundingClientRect();
+ const sibling = el.parentElement?.nextElementSibling;
+ const n = sibling?.getBoundingClientRect();
+ return {
+ isOpen: el.matches(':popover-open'),
+ spot: r == null ? null : [r.x, r.y, r.width, r.height],
+ next: n == null ? null : [n.x, n.y],
+ visibility: getComputedStyle(el).visibility,
+ };
+ });
+ const detail = JSON.stringify({before, lifted});
+ expect(lifted.isOpen, detail).toBe(true);
+ expect(lifted.visibility, detail).toBe('visible');
+ for (let i = 0; i < 4; i++) {
+ expect(lifted.spot?.[i] ?? NaN, detail).toBeCloseTo(before.box[i], 0);
+ }
+ // Nothing after the card moved.
+ expect(lifted.next, detail).toEqual(before.next);
+ // Once the lift has grown (it takes no touch before, AST-094 FR35), a tap
+ // on the tint, far from the card and the menu.
+ await untilGrown(page);
+ await driver.play(tap({x: 24, y: 24}));
+ await expect(menu).toBeHidden();
+ await expect
+ .poll(async () => trigger.evaluate(el => el.matches(':popover-open')), {
+ timeout: 3_000,
+ })
+ .toBe(false);
+ await expect
+ .poll(
+ async () =>
+ page.evaluate(() =>
+ document.querySelector('[data-astryx-context-menu-lift]'),
+ ),
+ {timeout: 3_000},
+ )
+ .toBeNull();
+ // The card is back as it was: no popover, and nothing of the lift inline.
+ const after = await trigger.evaluate(el => ({
+ popover: el.getAttribute('popover'),
+ style: (el as HTMLElement).style.cssText,
+ placeholder:
+ document.querySelector('[data-astryx-context-menu-lift-placeholder]') !=
+ null,
+ }));
+ expect(after.popover).toBeNull();
+ expect(after.style).toBe(before.style);
+ expect(after.placeholder).toBe(false);
+});
+
+test('the card grows on from the press, and the backdrop fades in, on springs.contextMenuLift, frame by frame', async ({
+ page,
+}, testInfo) => {
+ const {driver, center} = await openLiftStory(page);
+ const playing = driver.play(tap(center, {holdMs: menuDisplayMs + 600}));
+ const lifted = page.locator('[data-testid="touch-context-menu"][popover]');
+ await expect(lifted).toBeAttached({timeout: 5_000});
+ await holdAnimations(page);
+ const samples: {t: number; scale: number; backdrop: number}[] = [];
+ for (const t of timeline(450)) {
+ await seekAnimations(page, t);
+ samples.push({
+ t,
+ ...(await page.evaluate(() => {
+ const card = document.querySelector(
+ '[data-testid="touch-context-menu"]',
+ );
+ const layer = document.querySelector('[data-astryx-context-menu-lift]');
+ const scale = card == null ? 'none' : getComputedStyle(card).scale;
+ return {
+ scale: scale === 'none' ? 1 : Number.parseFloat(scale),
+ backdrop:
+ layer == null
+ ? NaN
+ : Number(getComputedStyle(layer, '::backdrop').opacity),
+ };
+ })),
+ });
+ }
+ await releaseAnimations(page);
+ await playing;
+ const from = samples[0].scale;
+ const scale = solveSpring(toSpring(springs.contextMenuLift), {
+ from,
+ to: 1.13,
+ });
+ const fade = solveSpring(toSpring(springs.contextMenuLift), {from: 0, to: 1});
+ const errors = samples.map(s => ({
+ t: s.t,
+ widthErrorPx: Math.abs(s.scale - scale.value(s.t / 1000)) * 200,
+ // Opacity stops at 1: the spring's 1.5% overshoot (UIKit's alpha peaks
+ // at 1.0145 too) presents as 1.
+ backdropError: Math.abs(s.backdrop - Math.min(1, fade.value(s.t / 1000))),
+ }));
+ await writeEvidence(
+ 'curves/contextmenu-lift',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {from, samples, errors},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ // The press left the card at about 1.06 (UIKit: 1.0618 at 733 ms).
+ expect(from).toBeGreaterThan(1.04);
+ expect(from).toBeLessThan(1.07);
+ expect(Math.max(...errors.map(e => e.widthErrorPx))).toBeLessThan(0.3);
+ expect(Math.max(...errors.map(e => e.backdropError))).toBeLessThan(0.01);
+ // It overshoots, as UIKit's does (226.39 pt at +279 ms).
+ expect(Math.max(...samples.map(s => s.scale))).toBeGreaterThan(1.13);
+});
+
+test('the menu grows out of the finger on springs.contextMenuMorph, translate, scale and opacity only: at the press at first, its frame at rest, nothing left inline (AST-094 FR5)', async ({
+ page,
+}) => {
+ const {driver, center} = await openLiftStory(page);
+ const playing = driver.play(tap(center, {holdMs: menuDisplayMs + 600}));
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ // The menu's own animations, timed from the menu's start.
+ await holdAnimations(page, page.locator('[popover]:has([role="menu"])'));
+ const read = async (t: number) => {
+ await seekAnimations(page, t);
+ return page.evaluate(() => {
+ const popover = document
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]');
+ if (popover == null) {
+ return null;
+ }
+ const style = getComputedStyle(popover);
+ const r = popover.getBoundingClientRect();
+ const moving = new Set();
+ for (const animation of popover.getAnimations()) {
+ const frames =
+ (animation.effect as KeyframeEffect | null)?.getKeyframes() ?? [];
+ const properties = new Set(frames.flatMap(frame => Object.keys(frame)));
+ for (const property of properties) {
+ if (
+ !['offset', 'computedOffset', 'easing', 'composite'].includes(
+ property,
+ ) &&
+ new Set(frames.map(frame => String(frame[property]))).size > 1
+ ) {
+ moving.add(property);
+ }
+ }
+ }
+ return {
+ x: r.x + r.width / 2,
+ y: r.y + r.height / 2,
+ width: r.width,
+ opacity: Number(style.opacity),
+ filter: style.filter,
+ moving: [...moving].sort(),
+ };
+ });
+ };
+ const start = await read(0);
+ const middle = await read(100);
+ const end = await read(600);
+ await releaseAnimations(page);
+ await playing;
+ const curve = solveSpring(toSpring(springs.contextMenuMorph), {
+ from: 0,
+ to: 1,
+ });
+ const detail = JSON.stringify({center, start, middle, end});
+ // At the press, UIKit's blob wide, clear.
+ expect(start?.width ?? NaN, detail).toBeCloseTo(
+ contextMenu.lift.morphStartWidth,
+ 0,
+ );
+ expect(start?.x ?? NaN, detail).toBeCloseTo(center.x, 0);
+ expect(start?.y ?? NaN, detail).toBeCloseTo(center.y, 0);
+ expect(start?.opacity, detail).toBeCloseTo(0, 2);
+ // Its opacity follows the growth's own progress.
+ expect(middle?.opacity, detail).toBeCloseTo(curve.value(0.1), 1);
+ expect(end?.opacity, detail).toBeCloseTo(1, 2);
+ expect(end?.width ?? 0, detail).toBeGreaterThan(150);
+ for (const sample of [start, middle, end]) {
+ expect(sample?.filter, detail).toBe('none');
+ }
+ expect(start?.moving, detail).toEqual(['opacity', 'scale', 'translate']);
+ // Once grown, nothing of the growth is left inline on the menu.
+ await page.waitForTimeout(300);
+ expect(
+ await page.evaluate(() => {
+ const popover = document
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]');
+ return [popover?.style.translate, popover?.style.scale];
+ }),
+ ).toEqual(['', '']);
+});
+
+test('closing shrinks the menu back into the finger on the layer runtime’s exit copy, translate, scale and opacity only, while the card returns, on UIKit’s dismissal spring (AST-094 FR31)', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ await liftAndSettle(page, story);
+ // The menu's frame as laid out (its popover's box).
+ const menuBox = await page.evaluate(() => {
+ const r = document
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]')
+ ?.getBoundingClientRect();
+ return r == null
+ ? null
+ : {x: r.x + r.width / 2, y: r.y + r.height / 2, width: r.width};
+ });
+ await page.keyboard.press('Escape');
+ await holdAnimations(page);
+ const read = async (t: number) => {
+ await seekAnimations(page, t);
+ return page.evaluate(() => {
+ const copy = document.querySelector(
+ '[data-astryx-context-menu-lift-exit]',
+ );
+ const card = document.querySelector('[data-testid="touch-context-menu"]');
+ const box = copy?.getBoundingClientRect();
+ const scale = card == null ? 'none' : getComputedStyle(card).scale;
+ const moving = new Set();
+ for (const animation of copy?.getAnimations() ?? []) {
+ const frames =
+ (animation.effect as KeyframeEffect | null)?.getKeyframes() ?? [];
+ for (const property of ['translate', 'scale', 'opacity', 'filter']) {
+ if (new Set(frames.map(frame => String(frame[property]))).size > 1) {
+ moving.add(property);
+ }
+ }
+ }
+ return {
+ copy:
+ box == null || copy == null
+ ? null
+ : {
+ x: box.x + box.width / 2,
+ y: box.y + box.height / 2,
+ width: box.width,
+ opacity: Number(getComputedStyle(copy).opacity),
+ inert: copy.inert,
+ },
+ moving: [...moving].sort(),
+ cardScale: scale === 'none' ? 1 : Number.parseFloat(scale),
+ };
+ });
+ };
+ const start = await read(0);
+ const middle = await read(120);
+ await releaseAnimations(page);
+ await page.waitForTimeout(900);
+ const after = await page.evaluate(() => ({
+ exit:
+ document.querySelector('[data-astryx-context-menu-lift-exit]') != null,
+ layer: document.querySelector('[data-astryx-context-menu-lift]') != null,
+ }));
+ const returning = solveSpring(toSpring(springs.contextMenuDismiss), {
+ from: 1.13,
+ to: 1,
+ });
+ const detail = JSON.stringify({
+ menuBox,
+ center: story.center,
+ start,
+ middle,
+ after,
+ });
+ // It starts as the menu stands, opaque and inert.
+ expect(start.copy?.x, detail).toBeCloseTo(menuBox?.x ?? NaN, 0);
+ expect(start.copy?.y, detail).toBeCloseTo(menuBox?.y ?? NaN, 0);
+ expect(start.copy?.width, detail).toBeCloseTo(menuBox?.width ?? NaN, 0);
+ expect(start.copy?.opacity, detail).toBeCloseTo(1, 2);
+ expect(start.copy?.inert, detail).toBe(true);
+ // Partway: smaller, nearer the finger, fading.
+ expect(middle.copy?.width ?? Infinity, detail).toBeLessThan(
+ (menuBox?.width ?? 0) * 0.8,
+ );
+ expect(
+ Math.abs((middle.copy?.y ?? NaN) - story.center.y),
+ detail,
+ ).toBeLessThan(Math.abs((menuBox?.y ?? NaN) - story.center.y));
+ expect(middle.copy?.opacity ?? 1, detail).toBeLessThan(1);
+ expect(middle.moving, detail).toEqual(['opacity', 'scale', 'translate']);
+ expect(middle.cardScale, detail).toBeCloseTo(returning.value(0.12), 2);
+ // Done: the exit copy and the lift are gone.
+ expect(after, detail).toEqual({exit: false, layer: false});
+});
+
+test('a close while the menu is still growing shrinks it back from where it stands, with no jump to its full size (AST-094 FR6)', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ // The finger lifts just after the menu shows (it stays open).
+ await story.driver.play(tap(story.center, {holdMs: menuDisplayMs + 40}));
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ // In one task: the menu's drawn width as the close comes, the close
+ // (Escape on the menu), and the width its exit copy starts from.
+ const {entrance, exitStart} = await page.evaluate(() => {
+ const menu = document.querySelector('[role="menu"]');
+ const popover = menu?.closest('[popover]');
+ const drawn = popover?.getBoundingClientRect().width ?? null;
+ const full = popover?.offsetWidth ?? null;
+ menu?.dispatchEvent(
+ new KeyboardEvent('keydown', {key: 'Escape', bubbles: true}),
+ );
+ return {
+ entrance: {drawn, full},
+ exitStart:
+ document
+ .querySelector('[data-astryx-context-menu-lift-exit]')
+ ?.getBoundingClientRect().width ?? null,
+ };
+ });
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ await page.waitForTimeout(900);
+ const after = await page.evaluate(() => ({
+ exit: document.querySelectorAll('[data-astryx-context-menu-lift-exit]')
+ .length,
+ style:
+ document
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]')
+ ?.getAttribute('style') ?? '',
+ layer: document.querySelector('[data-astryx-context-menu-lift]') != null,
+ }));
+ const detail = JSON.stringify({entrance, exitStart, after});
+ // Mid-growth the menu is still smaller than its frame; the exit continues
+ // from the growth's curve where it stands now (at most a frame on from the
+ // frame last drawn), not from the frame.
+ expect(entrance.drawn ?? Infinity, detail).toBeLessThan(
+ (entrance.full ?? 0) - 10,
+ );
+ expect(exitStart ?? 0, detail).toBeGreaterThan((entrance.drawn ?? 0) - 2);
+ expect(exitStart ?? Infinity, detail).toBeLessThan((entrance.full ?? 0) - 10);
+ expect(after.exit, detail).toBe(0);
+ expect(after.layer, detail).toBe(false);
+ expect(after.style, detail).not.toMatch(/translate|scale/u);
+});
+
+test('a press during the close lands on the fading dim and, held past the close’s end, still reaches nothing: nothing opens, and the layer waits for the lift', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ await liftAndSettle(page, story);
+ await page.evaluate(() => {
+ const w = window as unknown as {__cardEvents: string[]};
+ w.__cardEvents = [];
+ const card = document.querySelector('[data-testid="touch-context-menu"]');
+ for (const type of ['touchstart', 'pointerdown', 'click']) {
+ card?.addEventListener(type, () => w.__cardEvents.push(type), {
+ capture: true,
+ passive: true,
+ });
+ }
+ });
+ await page.keyboard.press('Escape');
+ await page.waitForTimeout(80);
+ // The close holds the layer (the layer runtime's input hold): a
+ // shield in the top layer covers it until the hold ends.
+ const heldState = async () =>
+ page.evaluate(() => {
+ const layer = document.querySelector('[data-astryx-context-menu-lift]');
+ return {
+ exit:
+ document.querySelector('[data-astryx-context-menu-lift-exit]') !=
+ null,
+ held:
+ layer != null &&
+ [...layer.children].some(child =>
+ child.matches('div[popover]:popover-open'),
+ ),
+ };
+ });
+ const during = await heldState();
+ // A new finger held on the card while it is still on its way back, and on
+ // well past the close's end: the layer stays up (bare) under it.
+ const holdMs = menuDisplayMs + 200;
+ const playing = story.driver.play(tap(story.center, {holdMs}));
+ await page.waitForTimeout(holdMs - 150);
+ const heldPastExit = await readLift(page);
+ const heldWhilePressed = await heldState();
+ await playing;
+ await page.waitForTimeout(600);
+ const after = await readLift(page);
+ const heldAfter = await heldState();
+ const cardEvents = await page.evaluate(
+ () => (window as unknown as {__cardEvents: string[]}).__cardEvents,
+ );
+ const detail = JSON.stringify({
+ during,
+ heldPastExit,
+ heldWhilePressed,
+ after,
+ heldAfter,
+ cardEvents,
+ });
+ expect(during, detail).toEqual({exit: true, held: true});
+ expect(heldWhilePressed.held, detail).toBe(true);
+ expect(heldAfter.held, detail).toBe(false);
+ expect(heldPastExit.layerOpen, detail).toBe(true);
+ expect(heldPastExit.preview, detail).toBeNull();
+ expect(cardEvents, detail).toEqual([]);
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ expect(after.preview, detail).toBeNull();
+ expect(after.layerOpen, detail).toBe(false);
+});
+
+test('picking an action closes the menu the same way: it shrinks back into the finger and the card returns', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ await liftAndSettle(page, story);
+ await page.evaluate(() => {
+ const w = window as unknown as {__picked: string[]};
+ w.__picked = [];
+ document.addEventListener(
+ 'click',
+ event => {
+ const row = (event.target as Element).closest('[role="menuitem"]');
+ if (row != null) {
+ w.__picked.push(row.textContent ?? '');
+ }
+ },
+ {capture: true},
+ );
+ });
+ const share = await page.getByRole('menuitem', {name: 'Share'}).boundingBox();
+ if (share == null) {
+ throw new Error('no Share row');
+ }
+ await story.driver.play(
+ tap({x: share.x + share.width / 2, y: share.y + share.height / 2}),
+ );
+ const exiting = await page.evaluate(
+ () =>
+ document.querySelector('[data-astryx-context-menu-lift-exit]') != null,
+ );
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ await page.waitForTimeout(900);
+ const after = await readLift(page);
+ const picked = await page.evaluate(
+ () => (window as unknown as {__picked: string[]}).__picked,
+ );
+ const detail = JSON.stringify({exiting, after, picked});
+ expect(picked, detail).toEqual(['Share']);
+ expect(exiting, detail).toBe(true);
+ expect(after.preview, detail).toBeNull();
+ expect(after.layerOpen, detail).toBe(false);
+});
+
+test('closing returns the card to its place and clears the backdrop', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ const lifted = await liftAndSettle(page, story);
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ await page.waitForTimeout(900);
+ const after = await readLift(page);
+ const detail = JSON.stringify({lifted, after});
+ expect(after.preview, detail).toBeNull();
+ expect(after.layerOpen, detail).toBe(false);
+ expect(after.cardOpacity, detail).toBe('1');
+ // Back on its spot.
+ expect(after.card?.x ?? NaN, detail).toBeCloseTo(lifted.card?.x ?? NaN, 0);
+ expect(after.card?.y ?? NaN, detail).toBeCloseTo(lifted.card?.y ?? NaN, 0);
+ expect(after.card?.width ?? NaN, detail).toBeCloseTo(
+ lifted.card?.width ?? NaN,
+ 0,
+ );
+});
+
+test('a tap on the tint while the lift is still growing is swallowed: the menu finishes and stays open, and nothing beneath gets it (AST-094 FR35)', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ await page.evaluate(() => {
+ const w = window as unknown as {__clicked?: string[]};
+ w.__clicked = [];
+ document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target as Element;
+ w.__clicked?.push(
+ target.closest('[data-astryx-context-menu-lift]')
+ ? 'layer'
+ : target.tagName.toLowerCase(),
+ );
+ },
+ {capture: true},
+ );
+ });
+ await story.driver.play(tap(story.center, {holdMs: menuDisplayMs + 100}));
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ // At once, while the card grows and the menu fades in: a tap on the tint.
+ await story.driver.play(tap({x: 12, y: 12}));
+ await page.waitForTimeout(1200);
+ const lift = await readLift(page);
+ const clicked = await page.evaluate(
+ () => (window as unknown as {__clicked?: string[]}).__clicked ?? [],
+ );
+ const detail = JSON.stringify({lift, clicked});
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ expect(lift.layerOpen, detail).toBe(true);
+ expect(lift.backdropOpacity, detail).toBeCloseTo(1, 2);
+ expect(
+ clicked.filter(target => target !== 'layer'),
+ detail,
+ ).toEqual([]);
+ // Settled, a tap on the tint closes it as before.
+ await story.driver.play(tap({x: 12, y: 12}));
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+});
+
+test('a tap on the backdrop closes the menu and reaches nothing under it', async ({
+ page,
+}) => {
+ const story = await openLiftStory(page);
+ const lift = await liftAndSettle(page, story);
+ if (lift.card == null) {
+ throw new Error(JSON.stringify(lift));
+ }
+ await page.evaluate(() => {
+ const w = window as unknown as {__clicked?: string[]};
+ w.__clicked = [];
+ document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target as Element;
+ w.__clicked?.push(
+ target.closest('[data-astryx-context-menu-lift]')
+ ? 'backdrop'
+ : target.closest('[data-testid="touch-context-menu"]')
+ ? 'card'
+ : target.tagName.toLowerCase(),
+ );
+ },
+ {capture: true},
+ );
+ });
+ // On the card's own spot, under the backdrop, clear of the lifted card.
+ await story.driver.play(
+ tap({x: lift.card.x + 10, y: lift.card.y + lift.card.height + 8}),
+ );
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeHidden();
+ const clicked = await page.evaluate(
+ () => (window as unknown as {__clicked?: string[]}).__clicked ?? [],
+ );
+ expect(clicked.filter(target => target !== 'backdrop')).toEqual([]);
+});
+
+test('the lift keeps moving while the main thread is blocked: the card grows on every frame', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ // Measured: Linux WebKit's compositor stalls with its main thread (no
+ // frames for most of a block, the card frozen). iOS Safari keeps the card
+ // growing through the same 1 s block: the simulator recording.
+ test.skip(
+ browserName !== 'chromium',
+ 'Linux WebKit’s compositor stalls with its main thread; iOS Safari is the simulator recording',
+ );
+ const {driver, center} = await openLiftStory(page);
+ await markSelector(page, '[data-testid="touch-context-menu"]');
+ // Blocked from 20 ms after the menu's moment for 1 s (spec:AST-094's FR5
+ // row), past the card's whole growth; the finger lifts after the block.
+ const busyWindow = await blockAfterTouch(page, menuDisplayMs + 20, 1000);
+ const cast = await startScreencast(page);
+ await driver.play(tap(center, {holdMs: menuDisplayMs + 1300}));
+ const castFrames = await cast.stop();
+ const block = await busyWindow();
+ const tracked = await trackMarker(page, castFrames);
+ // The screencast reports whole pixels: the spring's tail plateaus within
+ // 2 px of the end (the harness's usual settle).
+ const proof = busyWindowProof(tracked, block, {
+ axis: 'width',
+ settledWithin: 2,
+ });
+ await writeEvidence(
+ 'busy-main-thread/contextmenu-lift',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ block,
+ 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-lift-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});
+ // Frames kept coming and the card kept growing through the block: the
+ // harness judges each delivered frame (no stall, no frozen card).
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2);
+ expect(proof.monotonic).toBe(true);
+ expect((proof.last ?? 0) - (proof.first ?? 0)).toBeGreaterThanOrEqual(4);
+});
+
+test('the close keeps going while the main thread is blocked: the menu’s exit copy shrinks on every frame', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ // As the lift's own proof: Linux WebKit's compositor stalls with its main
+ // thread; iOS Safari is the simulator recording, through the same 1 s
+ // block.
+ test.skip(
+ browserName !== 'chromium',
+ 'Linux WebKit’s compositor stalls with its main thread; iOS Safari is the simulator recording',
+ );
+ const story = await openLiftStory(page);
+ await liftAndSettle(page, story);
+ await markSelector(page, '[data-astryx-context-menu-lift-exit]');
+ // A tap on the dim starts the close as its finger lifts (60 ms); blocked
+ // from 20 ms into the close for 1 s (spec:AST-094's FR5 row), past the
+ // copy's whole shrink.
+ const busyWindow = await blockAfterTouch(page, 60 + 20, 1000);
+ const cast = await startScreencast(page);
+ await story.driver.play(tap({x: 24, y: 24}, {holdMs: 60}));
+ await page.waitForTimeout(1600);
+ const castFrames = await cast.stop();
+ const block = await busyWindow();
+ // The copy fades as it shrinks, so its marker pales: a wider tolerance
+ // keeps it tracked while it is still half opaque.
+ const tracked = await trackMarker(page, castFrames, {tolerance: 120});
+ const proof = busyWindowProof(tracked, block, {
+ axis: 'width',
+ settledWithin: 2,
+ });
+ await writeEvidence(
+ 'busy-main-thread/contextmenu-lift-close',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ block,
+ 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-lift-close-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});
+ // Frames kept coming and the copy kept shrinking through the block: the
+ // harness judges each delivered frame (no stall, no frozen copy).
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2);
+ expect(proof.monotonic).toBe(true);
+ expect((proof.first ?? 0) - (proof.last ?? 0)).toBeGreaterThanOrEqual(4);
+});
+
+/** The lifted card's box, its opacity and the menu's filter, as the frame shows them. */
+type ReducedMotionSample = Awaited>;
+
+async function reducedMotionSample(page: Page) {
+ return page.evaluate(() => {
+ const preview = document.querySelector(
+ '[data-testid="touch-context-menu"]',
+ );
+ const menu = document
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]');
+ const box = preview?.getBoundingClientRect();
+ return {
+ x: box?.x ?? Number.NaN,
+ y: box?.y ?? Number.NaN,
+ width: box?.width ?? Number.NaN,
+ opacity: preview ? Number(getComputedStyle(preview).opacity) : Number.NaN,
+ filter: menu ? getComputedStyle(menu).filter : 'none',
+ menuOpacity: menu ? Number(getComputedStyle(menu).opacity) : Number.NaN,
+ // Still lifted (in the top layer), not yet back in the page.
+ lifted: preview?.matches(':popover-open') ?? false,
+ };
+ });
+}
+
+test('under Reduce Motion the lift cross-fades in place, as UIKit’s reduced path does: the card holds its lifted box in every frame, only its opacity moves, and the menu fades in without blur', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver, center} = await openLiftStory(page);
+ const playing = driver.play(tap(center, {holdMs: menuDisplayMs + 600}));
+ const lifted = page.locator('[data-testid="touch-context-menu"][popover]');
+ await expect(lifted).toBeAttached({timeout: 5_000});
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+ // The lift's and the menu's animations, timed from the lift's start (the
+ // menu starts in the commit after it).
+ await holdAnimations(page);
+ const times = timeline(600);
+ const samples: ReducedMotionSample[] = [];
+ for (const t of times) {
+ await seekAnimations(page, t);
+ samples.push(await reducedMotionSample(page));
+ }
+ await releaseAnimations(page);
+ await playing;
+ const detail = JSON.stringify(samples);
+ const last = samples.at(-1);
+ expect(last, detail).toBeDefined();
+ if (last == null) {
+ return;
+ }
+ for (const sample of samples) {
+ // No travel, no growth.
+ expect(Math.abs(sample.x - last.x), detail).toBeLessThan(0.5);
+ expect(Math.abs(sample.y - last.y), detail).toBeLessThan(0.5);
+ expect(Math.abs(sample.width - last.width), detail).toBeLessThan(0.5);
+ // No blur.
+ expect(sample.filter, detail).toMatch(/^(none|blur\(0(px)?\))$/);
+ }
+ // The lifted box is the card's lifted size, not its size on the page.
+ expect(last.width, detail).toBeGreaterThan(
+ (
+ await page
+ .locator('[data-astryx-context-menu-lift-placeholder]')
+ .boundingBox()
+ )?.width ?? 0,
+ );
+ // Only the opacity moves: from (near) clear to opaque, never back, and
+ // done within 200 ms (`design:reduced-motion` DR2); the menu's fade too,
+ // within 200 ms of its own start.
+ expect(samples[0].opacity, detail).toBeLessThan(0.5);
+ expect(last.opacity, detail).toBeCloseTo(1, 2);
+ const menuStart =
+ times[samples.findIndex(sample => sample.menuOpacity > 0.001)] ?? 0;
+ for (const [i, t] of times.entries()) {
+ if (t >= 200 + 1000 / 60) {
+ expect(samples[i].opacity, detail).toBeGreaterThan(0.999);
+ }
+ if (t >= menuStart + 200 + 1000 / 60) {
+ expect(samples[i].menuOpacity, detail).toBeGreaterThan(0.999);
+ }
+ }
+ expect(
+ samples.every(
+ (s, i) => i === 0 || s.opacity >= samples[i - 1].opacity - 1e-4,
+ ),
+ detail,
+ ).toBe(true);
+});
+
+/** The menu's exit copy, as the frame shows it: its box and its opacity. */
+async function exitCopySample(page: Page) {
+ return page.evaluate(() => {
+ const copy = document.querySelector(
+ '[data-astryx-context-menu-lift-exit]',
+ );
+ const box = copy?.getBoundingClientRect();
+ return copy == null || box == null
+ ? null
+ : {
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ opacity: Number(getComputedStyle(copy).opacity),
+ };
+ });
+}
+
+test('under Reduce Motion closing fades the card out where it is, with no return travel', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver, center} = await openLiftStory(page);
+ await driver.play(tap(center, {holdMs: menuDisplayMs + 600}));
+ const menu = page.getByRole('menu', {name: 'Photo actions'});
+ await expect(menu).toBeVisible();
+ await page.waitForTimeout(700);
+ const open = await reducedMotionSample(page);
+ // A tap on the dim, far from the card and the menu.
+ await driver.play(tap({x: 24, y: 24}));
+ await holdAnimations(page);
+ const times = timeline(300);
+ const samples: ReducedMotionSample[] = [];
+ const copies: Awaited>[] = [];
+ for (const t of times) {
+ await seekAnimations(page, t);
+ samples.push(await reducedMotionSample(page));
+ copies.push(await exitCopySample(page));
+ }
+ await releaseAnimations(page);
+ const detail = JSON.stringify({open, samples, copies});
+ // The menu's exit copy fades where it stands too, gone within 200 ms
+ // (`spec:AST-094` FR8, `design:reduced-motion` DR2): no shrink, no travel.
+ const first = copies.find(copy => copy != null);
+ expect(first, detail).toBeDefined();
+ for (const [i, t] of times.entries()) {
+ const copy = copies[i];
+ if (copy == null || first == null) {
+ continue;
+ }
+ expect(Math.abs(copy.x - first.x), detail).toBeLessThan(0.5);
+ expect(Math.abs(copy.y - first.y), detail).toBeLessThan(0.5);
+ expect(Math.abs(copy.width - first.width), detail).toBeLessThan(0.5);
+ if (t >= 200 + 1000 / 60) {
+ expect(copy.opacity, detail).toBeLessThan(0.001);
+ }
+ }
+ // While it is lifted the card fades where it is, gone within 200 ms
+ // (`design:reduced-motion` DR2); once the close settles it is back in the
+ // page, which the samples after that no longer judge.
+ const lifted = samples.filter(sample => sample.lifted);
+ expect(lifted.length, detail).toBeGreaterThan(times.length / 2);
+ for (const [i, t] of times.entries()) {
+ if (
+ samples[i].lifted &&
+ t >= 200 + 1000 / 60 &&
+ Number.isFinite(samples[i].opacity)
+ ) {
+ expect(samples[i].opacity, detail).toBeLessThan(0.001);
+ }
+ }
+ for (const sample of lifted) {
+ expect(Math.abs(sample.x - open.x), detail).toBeLessThan(0.5);
+ expect(Math.abs(sample.y - open.y), detail).toBeLessThan(0.5);
+ expect(Math.abs(sample.width - open.width), detail).toBeLessThan(0.5);
+ }
+ expect(lifted.at(-1)?.opacity ?? 1, detail).toBeLessThan(0.5);
+ expect(
+ lifted.every(
+ (s, i) => i === 0 || s.opacity <= lifted[i - 1].opacity + 1e-4,
+ ),
+ detail,
+ ).toBe(true);
+});
+
+test(
+ 'storyboard: the lift, from the menu’s moment',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const {driver, center} = await openLiftStory(page);
+ const playing = driver.play(tap(center, {holdMs: menuDisplayMs + 900}));
+ await expect(
+ page.locator('[data-testid="touch-context-menu"][popover]'),
+ ).toBeAttached({timeout: 5_000});
+ const viewport = page.viewportSize();
+ const {storyboard} = await animationStoryboard(page, {
+ name: 'contextmenu-lift',
+ clip: {
+ x: 0,
+ y: Math.max(0, center.y - 120),
+ width: viewport?.width ?? 402,
+ height: 360,
+ },
+ times: timeline(450, 1000 / 30),
+ measure: async () =>
+ page.evaluate(() => {
+ const card = document.querySelector(
+ '[data-testid="touch-context-menu"]',
+ );
+ const layer = document.querySelector(
+ '[data-astryx-context-menu-lift]',
+ );
+ return {
+ width: card?.getBoundingClientRect().width.toFixed(1) ?? '-',
+ backdrop:
+ layer == null
+ ? '-'
+ : Number(getComputedStyle(layer, '::backdrop').opacity).toFixed(
+ 3,
+ ),
+ };
+ }),
+ columns: 5,
+ cellScale: 0.5,
+ });
+ await releaseAnimations(page);
+ await playing;
+ await storyboard.write(testInfo);
+ const widths = storyboard.frames.map(f => Number(f.data.width));
+ expect(widths.at(-1)).toBeCloseTo(226, 0);
+ },
+);
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 29102ddf41af7..56af38af8a87b 100644
--- a/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts
+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.a11y.chromium.spec.ts
@@ -49,20 +49,54 @@ async function triggerCenter(page: Page): Promise<{x: number; y: number}> {
}
/**
- * 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.
+ * Resolves two frames after the lift's `touchend`, or after the `click` that
+ * follows it when the browser sends one (the last of a touch's compatibility
+ * mouse events), so anything those events close has closed. Under the touch
+ * model a hold that opens the menu gets no compatibility events, so the lift's
+ * `touchend` is the last event of the press.
*/
async function armCompatClick(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},
- );
+ // Each event restarts the two frames, so a click that follows the
+ // lift's touchend is waited for too.
+ let last = 0;
+ const settle = () => {
+ const mine = ++last;
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ if (mine === last) {
+ resolve();
+ }
+ }),
+ );
+ };
+ document.addEventListener('touchend', settle, {
+ once: true,
+ capture: true,
+ });
+ document.addEventListener('click', settle, {once: true, capture: true});
+ });
+ });
+}
+
+/**
+ * Resolves two frames after every running animation on the page has
+ * finished: the presentation's, which ends the layer's input hold.
+ */
+async function presentationSettled(page: Page): Promise {
+ await page.evaluate(async () => {
+ await Promise.all(
+ document.getAnimations().map(async animation =>
+ animation.finished.then(
+ () => undefined,
+ () => undefined,
+ ),
+ ),
+ );
+ await new Promise(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
});
}
@@ -94,7 +128,10 @@ test('the long press that opens the menu leaves it open as the finger lifts', as
await compatClickDelivered(page);
await expect(menu).toBeVisible();
- // A tap outside still closes it.
+ // A tap outside still closes it, once the presentation has run: until it
+ // completes, a tap reaches nothing (the layer's input hold, as UIKit drops
+ // a touch while a presentation runs).
+ await presentationSettled(page);
await cdp.send('Input.dispatchTouchEvent', {
type: 'touchStart',
touchPoints: [{x: 5, y: 5, id: 2}],
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..6c23fb38d1568
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuLongPress.interaction.browser.spec.ts
@@ -0,0 +1,800 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuLongPress.interaction.browser.spec.ts
+ * @input The built "Touch / long press" ContextMenu story, real touch input
+ * (Chromium CDP / WebKit's input command), the interaction harness, the
+ * context-menu constants and UIKit's measured press frames
+ * @output Interaction and animation proofs for opening a context menu with a
+ * held finger on UIKit's timeline, one touch model on every touch device
+ * (Chromium's finger stands for Android's engine, WebKit's for iOS): the
+ * menu opens at 735 ms for a finger
+ * still down, or at a lift after the commit, and not before; under Reduce
+ * Motion the card does not grow and the timeline holds; the lift sends no
+ * click; an early lift opens nothing and the card springs back; a second
+ * finger before the commit opens nothing and the card springs back; a
+ * drift within the tolerance still opens, past it on one axis (or a drag
+ * after the commit) opens nothing; the press feedback's presented scale
+ * follows UIKit's measured frames; it keeps advancing every frame through a
+ * blocked main thread; it does no Layout or Paint; the page does not scroll
+ * under the held finger; a storyboard of the press
+ * @position Interaction specs of packages/core/src/ContextMenu (the
+ * BottomSheetDetent spec is the exemplar); where the menu then shows is
+ * ContextMenuLift.interaction.browser.spec.ts's
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ blockMainThread,
+ busyWindowProof,
+ castStoryboard,
+ countBetween,
+ drag,
+ 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 {contextMenu} from '../../motion/uikit/contextMenu';
+import {
+ PRESS_FEEDBACK_START_MS,
+ pressFeedbackCurve,
+} from '../contextMenuPressCurve';
+import {UIKIT_LONG_PRESS, UIKIT_PRESS_VIEW_WIDTH} from './uikitPressFrames';
+
+const storybook = withStorybook(test);
+const {commitMs, menuDisplayMs} = contextMenu.press;
+
+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);
+ await installLongTaskLog(page);
+ // Note when the menu is asked to show, on the page clock (no per-frame
+ // work: the rendering proofs share this page).
+ await page.addInitScript(() => {
+ const w = window as unknown as {
+ __menuShownAt?: number | null;
+ __liftHandledAt?: number | null;
+ __liftShownAt?: number | null;
+ __framesBeforeMenu?: number | null;
+ };
+ w.__menuShownAt = null;
+ w.__liftHandledAt = null;
+ w.__liftShownAt = null;
+ w.__framesBeforeMenu = null;
+ // 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,
+ ...args: Parameters
+ ) {
+ // A finger's lift, where one opens the menu: the frames painted from
+ // it until the menu opens.
+ if (
+ w.__liftShownAt == null &&
+ this.hasAttribute('data-astryx-context-menu-lift')
+ ) {
+ w.__liftShownAt = performance.now();
+ let frames = 0;
+ const count = () => {
+ if (w.__menuShownAt == null) {
+ frames += 1;
+ requestAnimationFrame(count);
+ } else {
+ w.__framesBeforeMenu ??= frames;
+ }
+ };
+ requestAnimationFrame(count);
+ }
+ // 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,
+ );
+
+/** When a finger's lift started, and the frames painted before the menu. */
+const liftShownAt = async (page: Page) =>
+ page.evaluate(() => {
+ const w = window as unknown as {
+ __liftShownAt?: number | null;
+ __framesBeforeMenu?: number | null;
+ };
+ return {at: w.__liftShownAt ?? null, frames: w.__framesBeforeMenu ?? 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');
+
+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});
+
+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);
+ const lift = await liftShownAt(page);
+ expect(shown, 'the menu never showed').not.toBeNull();
+ expect(lift.at, 'the trigger never lifted').not.toBeNull();
+ // The presentation starts at the timeline's moment: the timer runs at its
+ // deadline, give or take a task, and the trigger lifts in it.
+ const after = (lift.at as number) - start;
+ expect(after).toBeGreaterThanOrEqual(menuDisplayMs);
+ expect(after).toBeLessThan(menuDisplayMs + 20);
+ // The menu opens with it, in the commit that follows: by the lift's second
+ // frame at the latest (it starts to grow from nothing, so either reads as
+ // one moment).
+ expect(lift.frames ?? 0).toBeLessThanOrEqual(1);
+ await expect(page.getByRole('menu', {name: 'Photo actions'})).toBeVisible();
+});
+
+test('a finger that lands as soon as the card shows gets UIKit’s timeline, however slowly scripts arrive: no menu at 500 ms, the menu at 735 ms', async ({
+ page,
+}) => {
+ // A slow phone network: a touch layer fetched on its own would arrive 8 s
+ // after the page.
+ await page.route(/ContextMenuTouchLayer[^/]*\.js/u, async route => {
+ await new Promise(resolve => setTimeout(resolve, 8000));
+ await route.continue();
+ });
+ 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();
+ expect((shown as number) - start).toBeGreaterThanOrEqual(menuDisplayMs);
+});
+
+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. (On the lift, emulated Chromium sends the
+ // compatibility mouse events a long press sends no click for on a device,
+ // and they dismiss today's menu as they do on main; 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]);
+ // No growth played on it (the lift's own entrance only fades, under Reduce
+ // Motion).
+ expect(
+ await trigger.evaluate(
+ el =>
+ el
+ .getAnimations()
+ .filter(
+ animation =>
+ new Set(
+ (animation.effect as KeyframeEffect | null)
+ ?.getKeyframes()
+ .map(frame => String(frame.scale)),
+ ).size > 1,
+ ).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'),
+ };
+ });
+ // Whether a selection starting under the finger is refused now: where iOS
+ // WebKit does not run, the host's lock cancels `selectstart` and writes no
+ // style (spec:AST-094 FR41).
+ const refusesSelection = async () =>
+ page.evaluate(({x, y}) => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ (document.elementFromPoint(x, y) ?? document.body).dispatchEvent(event);
+ return event.defaultPrevented;
+ }, center);
+ // At rest the trigger's own style keeps selection off (spec:AST-017
+ // FR59), and the host refuses nothing.
+ const rest = {...(await readLock()), refused: await refusesSelection()};
+ expect(rest).toEqual({inline: '', computed: 'none', refused: false});
+ // A held finger, short of the commit: the host refuses a selection under
+ // it, with no style written.
+ const playing = driver.play(hold(center, commitMs - 100));
+ await page.waitForTimeout(commitMs / 2);
+ const held = {...(await readLock()), refused: await refusesSelection()};
+ await playing;
+ await page.waitForTimeout(100);
+ // Lifted with no menu: back to the rest values.
+ const lifted = {...(await readLock()), refused: await refusesSelection()};
+ expect(held).toEqual({inline: '', computed: 'none', refused: true});
+ 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('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 follows UIKit’s measured press, frame by frame', async ({
+ page,
+}, testInfo) => {
+ const {driver, trigger, center} = await openTouchStory(page);
+ 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 PRESS_FEEDBACK_START_MS 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 - PRESS_FEEDBACK_START_MS;
+ 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);
+ };
+ const errors = UIKIT_LONG_PRESS.map(([ms, uikit]) => ({
+ ms,
+ uikit,
+ web: at(ms),
+ errorPt: Math.abs(at(ms) - uikit) * UIKIT_PRESS_VIEW_WIDTH,
+ }));
+ const rms = Math.sqrt(
+ errors.reduce((sum, e) => sum + e.errorPt ** 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: 'uikit-parity',
+ description: `press feedback vs UIKit iOS 26.2 (200 pt card): rms ${rms.toFixed(3)} pt over ${errors.length} frames`,
+ });
+ expect(rms).toBeLessThan(0.1);
+ expect(Math.max(...errors.map(e => e.errorPt))).toBeLessThan(0.25);
+});
+
+test('the press feedback keeps advancing every frame while the main thread is blocked', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)',
+ );
+ 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 => {
+ (el.firstElementChild as HTMLElement).style.width = '340px';
+ });
+ await markElement(trigger, {mode: 'outline'});
+ const cast = await startScreencast(page);
+ const playing = driver.play(hold(center, 1100));
+ const [feedback] = await waitForAnimation(trigger, {minProgressMs: 40});
+ const block = await blockMainThread(page, 450);
+ 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 over the judged window, in the marker's pixels.
+ const touch =
+ (await page.evaluate(() => performance.timeOrigin)) +
+ (await touchStartedAt(page));
+ const curve = pressFeedbackCurve();
+ const scaleAt = (epoch: number) =>
+ curve.at((epoch - touch - PRESS_FEEDBACK_START_MS) / 1000);
+ const restWidth = (proof.first ?? 0) / scaleAt(block.from + 20);
+ const expectedGrowth =
+ restWidth * (scaleAt(block.to - 20) - scaleAt(block.from + 20));
+ 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. The screencast resolves whole pixels and the card
+ // grows by about one every other frame, so a pixel may take 3 frames.
+ 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((proof.last ?? 0) - (proof.first ?? 0)).toBeGreaterThanOrEqual(
+ Math.floor(expectedGrowth) - 1,
+ );
+});
+
+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 + PRESS_FEEDBACK_START_MS + 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);
+ 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('the page does not scroll under a finger held until the menu, nor while the menu is up', 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('fixed');
+});
+
+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, 188 ms after the touch.
+ times: timeline(menuDisplayMs - PRESS_FEEDBACK_START_MS, 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));
+ expect(scales.every((s, i) => i === 0 || s >= scales[i - 1])).toBe(true);
+ // UIKit's platter at 732.6 ms: 1.0618.
+ expect(scales.at(-1)).toBeCloseTo(1.0618, 2);
+ },
+);
diff --git a/packages/core/src/ContextMenu/__tests__/ContextMenuRootUnmount.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/ContextMenuRootUnmount.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..f389f11b05420
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/ContextMenuRootUnmount.interaction.browser.spec.ts
@@ -0,0 +1,57 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ContextMenuRootUnmount.interaction.browser.spec.ts
+ * @input The built "Pointer presentation" ContextMenu story, a mouse, and
+ * Storybook's switch to another story, which unmounts the story's whole
+ * React root
+ * @output Real-browser proof that ContextMenu's menu goes with the React
+ * tree it renders in (component:ContextMenu FR10): unmounting the whole
+ * root around an open menu throws nothing, in Chromium and WebKit
+ * @position Run with `pnpm test:interaction ContextMenuRootUnmount`
+ */
+
+import {expect, test} from '@playwright/test';
+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+test('switching stories, which unmounts the whole React root around an open ContextMenu, throws nothing (component:ContextMenu FR10)', async ({
+ page,
+}) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => {
+ errors.push(error.message);
+ });
+ await openStory(page, storybook(), 'core-contextmenu--pointer-presentation');
+ const box = await page.getByTestId('pointer-context-menu').boundingBox();
+ if (box == null) {
+ throw new Error('no trigger');
+ }
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2, {
+ button: 'right',
+ });
+ const menu = page.getByRole('menu', {name: 'Document actions'});
+ await expect(menu).toBeVisible();
+ // Storybook unmounts the story's root before it renders the next story.
+ await page.evaluate(() => {
+ const channel = (
+ globalThis as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__?: {
+ emit: (event: string, data: unknown) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__;
+ if (channel == null) {
+ throw new Error('no Storybook channel');
+ }
+ channel.emit('setCurrentStory', {
+ storyId: 'core-contextmenu--headless-on-a-list-row',
+ viewMode: 'story',
+ });
+ });
+ await expect(page.getByTestId('headless-row')).toBeVisible();
+ await expect(menu).toHaveCount(0);
+ await page.waitForTimeout(300);
+ expect(errors).toEqual([]);
+});
diff --git a/packages/core/src/ContextMenu/__tests__/createContextMenu.interaction.browser.spec.ts b/packages/core/src/ContextMenu/__tests__/createContextMenu.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..e01642bbd561a
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/createContextMenu.interaction.browser.spec.ts
@@ -0,0 +1,193 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createContextMenu.interaction.browser.spec.ts
+ * @input The built "Headless / createContextMenu on a list row" ContextMenu
+ * story, the engine's own finger, a mouse and the keyboard
+ * @output Real-browser proof of the headless context menu (spec:AST-107
+ * FR8): a held finger, a right click and Shift+F10 each open it once on a
+ * list row; its lift clicks nothing; a key focuses the first row; Escape
+ * returns focus to the row; a choice runs once and the row hears no click;
+ * the list keeps only its `li` rows; useContextMenu opens the same menu,
+ * and its `menuContent` rows act once under a mouse and close the menu; on
+ * a row inside a modal dialog the menu takes focus and a choice acts
+ * @position Run with `pnpm test:interaction createContextMenu`
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ openStory,
+ tap,
+ touchDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+const STORY = 'core-contextmenu--headless-on-a-list-row';
+
+async function centerOf(page: Page, testId: string) {
+ const box = await page.getByTestId(testId).boundingBox();
+ if (box == null) {
+ throw new Error(`no ${testId}`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+const log = (page: Page) => page.getByTestId('headless-log');
+const focusedRole = async (page: Page) =>
+ page.evaluate(() => document.activeElement?.getAttribute('role') ?? null);
+
+test('a finger held on a list row opens its menu once, and the lift clicks nothing (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ const driver = await touchDriver(page);
+ const at = await centerOf(page, 'headless-row');
+ // Held past the long press, then lifted.
+ await driver.play(tap(at, {holdMs: 1200, id: 1}));
+ await expect(page.getByRole('menu', {name: 'Inbox actions'})).toBeVisible();
+ await page.waitForTimeout(300);
+ await expect(page.getByRole('menu', {name: 'Inbox actions'})).toBeVisible();
+ await expect(log(page)).toHaveText('open');
+});
+
+test('a right click and Shift+F10 open it with the first row focused, and Escape returns focus to the row (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ const at = await centerOf(page, 'headless-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ const menu = page.getByRole('menu', {name: 'Inbox actions'});
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => focusedRole(page)).toBe('menuitem');
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await page.getByTestId('headless-row').focus();
+ await page.keyboard.press('Shift+F10');
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => focusedRole(page)).toBe('menuitem');
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await expect
+ .poll(async () =>
+ page.evaluate(() => document.activeElement?.getAttribute('data-testid')),
+ )
+ .toBe('headless-row');
+ await expect(log(page)).toHaveText('open,close,open,close');
+});
+
+test('a choice runs once and closes the menu, the row hears no click, and the list keeps only its rows (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ const at = await centerOf(page, 'headless-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ await expect(page.getByRole('menu', {name: 'Inbox actions'})).toBeVisible();
+ expect(
+ await page
+ .getByTestId('headless-list')
+ .evaluate(list => Array.from(list.children, child => child.localName)),
+ ).toEqual(['li', 'li', 'li', 'li']);
+ await page.getByRole('menuitem', {name: 'Archive'}).click();
+ await expect(page.getByRole('menu', {name: 'Inbox actions'})).toBeHidden();
+ await expect(log(page)).toHaveText('open,archive,close');
+});
+
+test('useContextMenu opens the same menu from a component (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ const at = await centerOf(page, 'hook-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ await expect(page.getByRole('menu', {name: 'Sent actions'})).toBeVisible();
+ await page.getByRole('menuitem', {name: 'Forward'}).click();
+ await expect(log(page)).toHaveText('forward');
+});
+
+test("useContextMenu's menuContent rows act once under a mouse, and choosing one closes the menu (spec:AST-107 FR8)", async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ const at = await centerOf(page, 'hook-content-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ const menu = page.getByRole('menu', {name: 'Archive actions'});
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => focusedRole(page)).toBe('menuitem');
+ // A press and a release on the row: the release acts, and the browser's
+ // own click after it acts on nothing.
+ await page.getByRole('menuitem', {name: 'Restore'}).click();
+ await expect(menu).toBeHidden();
+ await page.waitForTimeout(300);
+ await expect(log(page)).toHaveText('restore');
+});
+
+test('on a row inside a transformed dialog, as a Drawer is, the menu opens at the pointer (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ // The row moves into a modal dialog on the right that keeps a transform,
+ // as a Drawer's does: the dialog is then the containing block of every
+ // fixed box inside it.
+ await page.evaluate(() => {
+ const row = document.querySelector('[data-testid="headless-row"]');
+ if (row == null) {
+ throw new Error('no row');
+ }
+ const dialog = document.createElement('dialog');
+ dialog.style.transform = 'translateX(0)';
+ dialog.style.margin = '80px 0 0 auto';
+ dialog.style.width = '360px';
+ const list = document.createElement('ul');
+ list.append(row);
+ dialog.append(list);
+ document.body.append(dialog);
+ dialog.showModal();
+ });
+ const at = await centerOf(page, 'headless-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ const menu = page.getByRole('menu', {name: 'Inbox actions'});
+ await expect(menu).toBeVisible();
+ const box = await menu.boundingBox();
+ if (box == null) {
+ throw new Error('no menu box');
+ }
+ // The pointer sits at one of the menu's corners, whichever way it opens.
+ const nearestX = Math.min(
+ Math.abs(box.x - at.x),
+ Math.abs(box.x + box.width - at.x),
+ );
+ const nearestY = Math.min(
+ Math.abs(box.y - at.y),
+ Math.abs(box.y + box.height - at.y),
+ );
+ expect(nearestX).toBeLessThan(12);
+ expect(nearestY).toBeLessThan(12);
+});
+
+test('on a row inside a modal dialog, the menu takes focus and a choice acts (spec:AST-107 FR8)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), STORY);
+ // The row moves into a modal dialog, which leaves everything outside it
+ // inert.
+ await page.evaluate(() => {
+ const row = document.querySelector('[data-testid="headless-row"]');
+ if (row == null) {
+ throw new Error('no row');
+ }
+ const dialog = document.createElement('dialog');
+ const list = document.createElement('ul');
+ list.append(row);
+ dialog.append(list);
+ document.body.append(dialog);
+ dialog.showModal();
+ });
+ const at = await centerOf(page, 'headless-row');
+ await page.mouse.click(at.x, at.y, {button: 'right'});
+ const menu = page.getByRole('menu', {name: 'Inbox actions'});
+ await expect(menu).toBeVisible();
+ await expect.poll(async () => focusedRole(page)).toBe('menuitem');
+ await page.getByRole('menuitem', {name: 'Archive'}).click();
+ await expect(menu).toBeHidden();
+ await expect(log(page)).toHaveText('open,archive,close');
+});
diff --git a/packages/core/src/ContextMenu/__tests__/uikitLiftFrames.ts b/packages/core/src/ContextMenu/__tests__/uikitLiftFrames.ts
new file mode 100644
index 0000000000000..84081cd0cf839
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/uikitLiftFrames.ts
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file uikitLiftFrames.ts
+ * @input UIKit's context-menu presentation measured on iOS 26.2 (iPhone 17
+ * Pro simulator, 60 Hz): a 200 × 120 pt card in the middle of the screen
+ * (x 101, y 377), held 0.9 s, a 3-action menu
+ * @output UIKIT_LIFT_FRAMES and UIKIT_LIFT_STARTS: per-frame presentation
+ * values from willDisplay, and when each one starts moving
+ * @position Fixture for the lift's parity tests
+ * (packages/core/src/ContextMenu/contextMenuLiftGeometry.test.ts)
+ *
+ * Columns: ms after willDisplay; the backdrop's alpha; the preview's width
+ * (pt; the press had grown it to 212.36); the menu content's opacity; its
+ * blur (pt). The frame at +27 ms, which still reads the model values, is
+ * left out, as is the preview's width at +45 ms (not yet presented).
+ */
+
+export const UIKIT_LIFT_FRAMES: ReadonlyArray<
+ readonly [
+ ms: number,
+ backdrop: number,
+ previewWidth: number | null,
+ menuOpacity: number,
+ menuBlur: number,
+ ]
+> = [
+ [45.4, 0.0449, null, 0.138, 3.447],
+ [62, 0.1504, 215.16, 0.297, 2.812],
+ [78.7, 0.2832, 217.19, 0.453, 2.188],
+ [95.4, 0.421, 219.19, 0.593, 1.63],
+ [112, 0.5505, 220.96, 0.71, 1.159],
+ [128.7, 0.6644, 222.42, 0.804, 0.783],
+ [145.4, 0.7596, 223.57, 0.876, 0.496],
+ [162, 0.8358, 224.45, 0.929, 0.285],
+ [178.7, 0.8945, 225.09, 0.965, 0.139],
+ [195.4, 0.9381, 225.53, 0.99, 0.042],
+ [212, 0.9689, 225.83, 1.004, -0.017],
+ [228.7, 0.9898, 226.01, 1.012, -0.05],
+ [245.4, 1.003, 226.11, 1.016, -0.063],
+ [262, 1.0106, 226.16, 1.016, -0.066],
+ [278.7, 1.0142, 226.39, 1.015, -0.061],
+ [295.4, 1.0152, 226.37, 1.013, -0.052],
+ [312, 1.0145, 226.33, 1.011, -0.043],
+ [328.7, 1.0129, 226.27, 1.008, -0.033],
+ [345.4, 1.0109, 226.21, 1.006, -0.025],
+ [362, 1.0088, 226.16, 1.004, -0.018],
+ [378.7, 1.0068, 226.12, 1.003, -0.012],
+ [395.4, 1.0051, 226.08, 1.002, -0.008],
+ [412, 1.0036, 226.05, 1.001, -0.004],
+ [428.7, 1.0025, 226.03, 1.001, -0.002],
+ [445.4, 1.0016, 226.02, 1, -0.001],
+ [462, 1.0009, 226.01, 1, 0],
+ [478.7, 1.0005, 226, 1, 0],
+];
+
+/** The preview's width when the menu shows: the press's 1.0618 × 200 pt. */
+export const UIKIT_LIFT_PREVIEW_FROM = 212.36;
+
+/**
+ * When each value starts moving, ms after willDisplay (UIKit commits the
+ * animations a frame or two after the delegate call): least-squares starts
+ * for the springs the lift uses.
+ */
+export const UIKIT_LIFT_STARTS = {
+ backdrop: 28.5,
+ previewWidth: 18.5,
+ menuOpacity: 12.5,
+ menuBlur: 12.5,
+} as const;
diff --git a/packages/core/src/ContextMenu/__tests__/uikitPressFrames.ts b/packages/core/src/ContextMenu/__tests__/uikitPressFrames.ts
new file mode 100644
index 0000000000000..e7b2fc49df90d
--- /dev/null
+++ b/packages/core/src/ContextMenu/__tests__/uikitPressFrames.ts
@@ -0,0 +1,79 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file uikitPressFrames.ts
+ * @input Nothing; measured data only
+ * @output Exports the visible scale of UIKit's context-menu press platter,
+ * frame by frame, for a long press and for a press lifted before the
+ * commit, as the reference the press feedback is compared against
+ * @position Test-only fixture of packages/core/src/ContextMenu (excluded from
+ * the build with the rest of __tests__); read by the unit and interaction
+ * tests of the press feedback
+ *
+ * UIKit lab (injected host app), iOS 26.2 simulator, iPhone 17 Pro, Oct 23
+ * 2026: the presentation width of `_UIContentPlatterView` over a 200 × 120 pt
+ * view, divided by 200, at each frame's display time in ms from the main
+ * thread's receipt of the touch.
+ */
+
+/** The measured view's width, to read scale errors in points. */
+export const UIKIT_PRESS_VIEW_WIDTH = 200;
+
+/** A long press: the menu displayed at 734 ms. */
+export const UIKIT_LONG_PRESS: ReadonlyArray = [
+ [199.6, 1],
+ [215.9, 1.00014],
+ [232.5, 1.00047],
+ [249.2, 1.00109],
+ [265.9, 1.00203],
+ [282.5, 1.00331],
+ [299.2, 1.00492],
+ [315.9, 1.00682],
+ [332.7, 1.00907],
+ [349.2, 1.01159],
+ [366.1, 1.01424],
+ [382.5, 1.01699],
+ [399.2, 1.01988],
+ [415.8, 1.02286],
+ [432.5, 1.02581],
+ [449.2, 1.02877],
+ [466.6, 1.03168],
+ [483.1, 1.03444],
+ [499.2, 1.03703],
+ [515.8, 1.03944],
+ [532.9, 1.04173],
+ [554.4, 1.04388],
+ [565.8, 1.04586],
+ [583, 1.0477],
+ [599.2, 1.04944],
+ [615.8, 1.05111],
+ [632.5, 1.0527],
+ [649.2, 1.05425],
+ [666.5, 1.05577],
+ [682.5, 1.05727],
+ [699.2, 1.05878],
+ [716.1, 1.06029],
+ [732.6, 1.06183],
+];
+
+/** When the early press lifted, ms (main-thread receipt). */
+export const UIKIT_EARLY_LIFT_AT = 266.5;
+
+/** A press lifted before the commit: no menu, the platter springs back. */
+export const UIKIT_EARLY_LIFT: ReadonlyArray = [
+ [199.5, 1],
+ [216.1, 1.00014],
+ [232.7, 1.00046],
+ [249.4, 1.00107],
+ [267.3, 1.002],
+ [282.8, 1.00327],
+ [299.5, 1.00438],
+ [316.1, 1.00493],
+ [332.8, 1.00504],
+ [349.5, 1.00483],
+ [366.1, 1.0044],
+ [382.8, 1.00382],
+ [399.4, 1.00318],
+ [416.1, 1.00252],
+ [432.8, 1.00189],
+];
diff --git a/packages/core/src/ContextMenu/contextMenuLiftGeometry.test.ts b/packages/core/src/ContextMenu/contextMenuLiftGeometry.test.ts
new file mode 100644
index 0000000000000..b515bbfa0a507
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuLiftGeometry.test.ts
@@ -0,0 +1,198 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contextMenuLiftGeometry.test.ts
+ * @input vitest, the context-menu constants, and the settled frames of
+ * UIKit's lifted previews measured on iOS 26.2 (iPhone 17 Pro, 402 × 874)
+ * @output The lift geometry against UIKit: an icon, a card and a full-width
+ * row lift to UIKit's sizes about the same center, held inside the
+ * viewport's gutter; the menu's side and alignment; and the lift's springs
+ * against UIKit's measured frames
+ * @position Unit tests of packages/core/src/ContextMenu/contextMenuLiftGeometry.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {solveSpring, toSpring} from '../motion/spring';
+import {springs} from '../motion/uikit';
+import {contextMenu} from '../motion/uikit/contextMenu';
+import {liftedBox, liftScale, menuPlacement} from './contextMenuLiftGeometry';
+import {
+ UIKIT_LIFT_FRAMES,
+ UIKIT_LIFT_PREVIEW_FROM,
+ UIKIT_LIFT_STARTS,
+} from './__tests__/uikitLiftFrames';
+
+const {screenInset, verticalMargin} = contextMenu.lift;
+/**
+ * UIKit's own margins as the gutter (16 pt at the sides, 20 pt plus the safe
+ * area at the top and bottom), so the frames below are UIKit's.
+ */
+const uikitGutter = (safeTop: number, safeBottom: number) => ({
+ top: safeTop + verticalMargin,
+ bottom: safeBottom + verticalMargin,
+ inline: screenInset,
+});
+const phone = {width: 402, height: 874, gutter: uikitGutter(0, 0)};
+/** UIKit rounds the lifted size to device pixels (3× here): half of one. */
+const HALF_PIXEL = 1 / 6;
+
+describe('liftScale', () => {
+ it('lifts a 60 pt icon to 69 pt (capped at 1.15)', () => {
+ expect(60 * liftScale(60, 60, phone)).toBeCloseTo(69, 5);
+ });
+
+ it('lifts a 200 × 120 card to 226 × 135.67 (26 pt on its larger side)', () => {
+ const scale = liftScale(200, 120, phone);
+ expect(200 * scale).toBeCloseTo(226, 5);
+ expect(Math.abs(120 * scale - 135.67)).toBeLessThan(HALF_PIXEL);
+ });
+
+ it('shrinks a full-width 402 × 60 row to 370 × 55.33 (the screen less 16 pt each side)', () => {
+ const scale = liftScale(402, 60, phone);
+ expect(402 * scale).toBeCloseTo(370, 5);
+ expect(Math.abs(60 * scale - 55.33)).toBeLessThan(HALF_PIXEL);
+ });
+});
+
+describe('liftedBox', () => {
+ it('grows a card about its center, as UIKit’s platter does', () => {
+ const box = liftedBox({x: 101, y: 377, width: 200, height: 120}, phone);
+ expect(box.x).toBeCloseTo(88, 5);
+ expect(box.width).toBeCloseTo(226, 5);
+ expect(box.y + box.height / 2).toBeCloseTo(437, 5);
+ });
+
+ it('centers a full-width row inside the 16 pt side insets', () => {
+ const box = liftedBox({x: 0, y: 300, width: 402, height: 60}, phone);
+ expect(box.x).toBeCloseTo(16, 5);
+ expect(box.x + box.width).toBeCloseTo(386, 5);
+ });
+
+ it('holds a card at the left edge at x 16, and one at the right edge at a right edge of 386', () => {
+ expect(
+ liftedBox({x: 4, y: 377, width: 200, height: 120}, phone).x,
+ ).toBeCloseTo(16, 5);
+ const right = liftedBox({x: 198, y: 377, width: 200, height: 120}, phone);
+ expect(right.x + right.width).toBeCloseTo(386, 5);
+ });
+
+ it('holds a card at the top at y 82 and one at the bottom at a bottom of 820 (UIKit: the safe area and 20 pt)', () => {
+ const safe = {...phone, gutter: uikitGutter(62, 34)};
+ expect(
+ liftedBox({x: 101, y: 70, width: 200, height: 120}, safe).y,
+ ).toBeCloseTo(82, 5);
+ const bottom = liftedBox({x: 101, y: 700, width: 200, height: 120}, safe);
+ expect(bottom.y + bottom.height).toBeCloseTo(820, 5);
+ });
+
+ it("holds a card inside the layer runtime's gutter: the safe area itself where it is past 16, plus an app's bar", () => {
+ // max(16, safe area) + the app's inset (spec:AST-059), here a 50 px bar.
+ const runtime = {...phone, gutter: {top: 62, bottom: 34 + 50, inline: 16}};
+ expect(
+ liftedBox({x: 101, y: 40, width: 200, height: 120}, runtime).y,
+ ).toBeCloseTo(62, 5);
+ const bottom = liftedBox(
+ {x: 101, y: 700, width: 200, height: 120},
+ runtime,
+ );
+ expect(bottom.y + bottom.height).toBeCloseTo(874 - 84, 5);
+ });
+});
+
+describe('menuPlacement', () => {
+ const safe = {...phone, gutter: uikitGutter(62, 34)};
+
+ it('puts the 3-action menu below the middle card, centered, as UIKit did', () => {
+ const box = liftedBox({x: 101, y: 377, width: 200, height: 120}, safe);
+ expect(menuPlacement(box, 146, safe)).toEqual({
+ side: 'below',
+ alignment: 'center',
+ });
+ });
+
+ it('puts the menu above the bottom card, where it does not fit below', () => {
+ const box = liftedBox({x: 101, y: 700, width: 200, height: 120}, safe);
+ expect(menuPlacement(box, 146, safe).side).toBe('above');
+ });
+
+ it('aligns the menu with the edge a preview is held against', () => {
+ const left = liftedBox({x: 4, y: 377, width: 200, height: 120}, safe);
+ expect(menuPlacement(left, 146, safe).alignment).toBe('start');
+ const right = liftedBox({x: 198, y: 377, width: 200, height: 120}, safe);
+ expect(menuPlacement(right, 146, safe).alignment).toBe('end');
+ });
+});
+
+describe('the lift’s springs against UIKit’s measured frames (iOS 26.2, 200 × 120 card)', () => {
+ const at = (
+ description: Parameters[0],
+ from: number,
+ to: number,
+ startMs: number,
+ ms: number,
+ ) =>
+ ms <= startMs
+ ? from
+ : solveSpring(toSpring(description), {from, to}).value(
+ (ms - startMs) / 1000,
+ );
+ const errors = (
+ pick: (row: (typeof UIKIT_LIFT_FRAMES)[number]) => number | null,
+ model: (ms: number) => number,
+ ) =>
+ UIKIT_LIFT_FRAMES.flatMap(row => {
+ const uikit = pick(row);
+ return uikit == null ? [] : [Math.abs(model(row[0]) - uikit)];
+ });
+ const rms = (e: number[]) =>
+ Math.sqrt(e.reduce((sum, x) => sum + x * x, 0) / e.length);
+
+ it('the backdrop fades on springs.contextMenuLift (alpha rms < 0.001)', () => {
+ const e = errors(
+ row => row[1],
+ ms => at(springs.contextMenuLift, 0, 1, UIKIT_LIFT_STARTS.backdrop, ms),
+ );
+ expect(rms(e)).toBeLessThan(0.001);
+ expect(Math.max(...e)).toBeLessThan(0.003);
+ });
+
+ it('the preview grows on from the press on springs.contextMenuLift (rms < 0.15 pt)', () => {
+ const e = errors(
+ row => row[2],
+ ms =>
+ at(
+ springs.contextMenuLift,
+ UIKIT_LIFT_PREVIEW_FROM,
+ 226,
+ UIKIT_LIFT_STARTS.previewWidth,
+ ms,
+ ),
+ );
+ expect(rms(e)).toBeLessThan(0.15);
+ expect(Math.max(...e)).toBeLessThan(0.4);
+ });
+
+ it('the menu content fades in on morphSpring (opacity rms < 0.01); its blur is not played, since only transform and opacity move (spec:AST-094 FR5)', () => {
+ const morphSpring = springs.contextMenuMorph;
+ const opacity = errors(
+ row => row[3],
+ ms => at(morphSpring, 0, 1, UIKIT_LIFT_STARTS.menuOpacity, ms),
+ );
+ expect(rms(opacity)).toBeLessThan(0.01);
+ expect(Math.max(...opacity)).toBeLessThan(0.03);
+ });
+});
+
+describe('menuPlacement in a right-to-left page', () => {
+ const viewport = {...phone, direction: 'rtl' as const};
+
+ it('keeps the menu flush with the edge the preview is held against: the alignment is logical, so the sides swap', () => {
+ const atLeft = {x: 16, y: 300, width: 226, height: 136};
+ const atRight = {x: 402 - 16 - 226, y: 300, width: 226, height: 136};
+ expect(menuPlacement(atLeft, 150, viewport).alignment).toBe('end');
+ expect(menuPlacement(atRight, 150, viewport).alignment).toBe('start');
+ expect(
+ menuPlacement(atLeft, 150, {...viewport, direction: 'ltr'}).alignment,
+ ).toBe('start');
+ });
+});
diff --git a/packages/core/src/ContextMenu/contextMenuLiftGeometry.ts b/packages/core/src/ContextMenu/contextMenuLiftGeometry.ts
new file mode 100644
index 0000000000000..484f7aed8ee52
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuLiftGeometry.ts
@@ -0,0 +1,87 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contextMenuLiftGeometry.ts
+ * @input The context-menu constants and the lift module's geometry
+ * (liftFromTrigger/liftFromTriggerGeometry.ts)
+ * @output Exports liftScale, liftedBox and menuPlacement: where UIKit's
+ * lifted preview lands when the menu shows, and where the menu sits
+ * against it, with UIKit's numbers
+ * @position The geometry of ContextMenu's lift presentation (touch);
+ * ContextMenu.tsx renders it
+ *
+ * When a context menu shows on iOS 26.2, the long-pressed view's preview
+ * lifts above a tinted backdrop: it grows about its center
+ * (`contextMenu.lift`), stays inside the viewport's gutter, and the menu sits
+ * a gap away: below it when it fits, else above, centered on it or flush with
+ * the edge it is held against. The gutter is the layer runtime's one
+ * definition (spec:AST-059), not UIKit's own margins (16 pt at the sides, 20
+ * pt plus the safe area at the top and bottom, `contextMenu.lift`): at the
+ * sides they agree; near a notch the runtime's leaves up to 20 px less. The
+ * lift module owns the geometry; this file gives it UIKit's numbers.
+ *
+ * SYNC: When modified, update
+ * /packages/core/src/ContextMenu/contextMenuLiftGeometry.test.ts
+ */
+
+import {
+ liftFromTriggerRect as liftedRect,
+ liftFromTriggerScale as liftScaleBy,
+ surfacePlacement,
+ type LiftFromTriggerGutter as LiftGutter,
+ type LiftFromTriggerViewport as LiftViewport,
+ type SurfacePlacement,
+} from '../liftFromTrigger/liftFromTriggerGeometry';
+import type {MorphRect} from '../motion/rectMorph';
+import {contextMenu} from '../motion/uikit/contextMenu';
+
+/** A box in client CSS px. */
+export type LiftBox = MorphRect;
+export type {LiftGutter, LiftViewport};
+/** Where the menu sits against the lifted preview. */
+export type MenuPlacement = SurfacePlacement;
+
+/** UIKit's scale rule for the lifted preview (`contextMenu.lift`). */
+const RULE = {
+ maxScale: contextMenu.lift.maxScale,
+ scaleUpPoints: contextMenu.lift.scaleUpPoints,
+};
+
+/**
+ * The factor a `width` × `height` preview grows by when the menu shows: up to
+ * `maxScale`, by `scaleUpPoints` on its larger side, and never wider than the
+ * screen less its insets (which can make it smaller than 1).
+ */
+export function liftScale(
+ width: number,
+ height: number,
+ viewport: LiftViewport,
+): number {
+ return liftScaleBy(width, height, viewport, RULE);
+}
+
+/**
+ * The lifted preview's box: `source` scaled by `liftScale` about its center,
+ * then moved inside the viewport's gutter if it crosses it.
+ */
+export function liftedBox(source: LiftBox, viewport: LiftViewport): LiftBox {
+ return liftedRect(source, viewport, RULE);
+}
+
+/**
+ * The menu's place: below the preview when `menuHeight` fits between it and
+ * the bottom limit, else above; centered on the preview, or flush with the
+ * preview's edge when the preview is held against a side of the screen.
+ */
+export function menuPlacement(
+ lifted: LiftBox,
+ menuHeight: number,
+ viewport: LiftViewport,
+): MenuPlacement {
+ return surfacePlacement(
+ lifted,
+ menuHeight,
+ viewport,
+ contextMenu.lift.menuGap,
+ );
+}
diff --git a/packages/core/src/ContextMenu/contextMenuPressCurve.test.ts b/packages/core/src/ContextMenu/contextMenuPressCurve.test.ts
new file mode 100644
index 0000000000000..01cc989944e7c
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuPressCurve.test.ts
@@ -0,0 +1,226 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contextMenuPressCurve.test.ts
+ * @input vitest, the context-menu constants, the press feedback curves, an
+ * independent RK4 integration, and per-frame presentation sizes of UIKit's
+ * press platter measured on iOS 26.2
+ * @output The press feedback against UIKit: the size UIKit asks for, the
+ * closed-form curve against a numerical integration of the same spring,
+ * continuity where the ramp changes, and the visible size of a long press
+ * and of a press lifted at 0.25 s against the measured frames
+ * @position Unit tests of packages/core/src/ContextMenu/contextMenuPressCurve.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {solveSpring, toSpring} from '../motion/spring';
+import {
+ contextMenu,
+ registerContextMenuTable,
+} from '../motion/uikit/contextMenu';
+import {
+ PRESS_FEEDBACK_START_MS,
+ pressFeedbackCurve,
+ pressFeedbackMotion,
+ pressFeedbackTarget,
+} from './contextMenuPressCurve';
+import {
+ UIKIT_EARLY_LIFT,
+ UIKIT_EARLY_LIFT_AT,
+ UIKIT_LONG_PRESS,
+ UIKIT_PRESS_VIEW_WIDTH,
+} from './__tests__/uikitPressFrames';
+
+const press = contextMenu.press;
+
+/** The visible scale of a held press `t` ms after the touch. */
+function held(t: number): number {
+ const curve = pressFeedbackCurve();
+ return t <= PRESS_FEEDBACK_START_MS
+ ? 1
+ : curve.at((t - PRESS_FEEDBACK_START_MS) / 1000);
+}
+
+/**
+ * The visible scale of a press lifted at `lift` ms: the held curve until the
+ * screen shows the lift, then the feedback spring back to 1 from where the
+ * curve was (what the animator plays on `fail`).
+ */
+function liftedAt(lift: number): (t: number) => number {
+ const curve = pressFeedbackCurve();
+ const turn = lift + press.returnLatencyMs;
+ const s = (turn - PRESS_FEEDBACK_START_MS) / 1000;
+ const back = solveSpring(toSpring(press.feedbackSpring), {
+ from: curve.at(s),
+ to: 1,
+ velocity: curve.velocity(s),
+ });
+ return t => (t < turn ? held(t) : back.value((t - turn) / 1000));
+}
+
+function errors(
+ measured: ReadonlyArray,
+ model: (t: number) => number,
+): {rms: number; max: number} {
+ const points = measured.map(
+ ([t, value]) => Math.abs(model(t) - value) * UIKIT_PRESS_VIEW_WIDTH,
+ );
+ return {
+ rms: Math.sqrt(points.reduce((sum, e) => sum + e * e, 0) / points.length),
+ max: Math.max(...points),
+ };
+}
+
+describe('pressFeedbackTarget', () => {
+ it('is 1 until the onset, then ramps to 1.04 at the commit', () => {
+ expect(pressFeedbackTarget(0)).toBe(1);
+ expect(pressFeedbackTarget(press.feedbackOnsetMs)).toBe(1);
+ expect(pressFeedbackTarget(press.commitMs)).toBeCloseTo(1.04, 10);
+ });
+
+ it('continues on the slower ramp from the same size, and stops when the menu displays', () => {
+ expect(pressFeedbackTarget(press.commitMs + 1e-9)).toBeCloseTo(1.04, 8);
+ expect(pressFeedbackTarget(press.menuDisplayMs)).toBeCloseTo(
+ 1 + (press.feedbackRateAfterCommit * press.menuDisplayMs) / 1000,
+ 10,
+ );
+ expect(pressFeedbackTarget(5000)).toBe(
+ pressFeedbackTarget(press.menuDisplayMs),
+ );
+ });
+});
+
+describe('pressFeedbackCurve', () => {
+ it('matches a numerical integration of the feedback spring chasing the ramp', () => {
+ const {stiffness, damping, mass} = toSpring(press.feedbackSpring);
+ const curve = pressFeedbackCurve();
+ const target = (s: number) =>
+ pressFeedbackTarget(press.feedbackOnsetMs + s * 1000);
+ let x = 1;
+ let v = 0;
+ const h = 1e-4;
+ let worst = 0;
+ for (let step = 0; step * h < curve.duration - h; step++) {
+ const s = step * h;
+ if (step % 50 === 0) {
+ worst = Math.max(worst, Math.abs(curve.at(s) - x));
+ }
+ const f = (px: number, pv: number, ps: number): [number, number] => [
+ pv,
+ (stiffness * (target(ps) - px) - damping * pv) / mass,
+ ];
+ const [a1, b1] = f(x, v, s);
+ const [a2, b2] = f(x + (h / 2) * a1, v + (h / 2) * b1, s + h / 2);
+ const [a3, b3] = f(x + (h / 2) * a2, v + (h / 2) * b2, s + h / 2);
+ const [a4, b4] = f(x + h * a3, v + h * b3, s + h);
+ x += (h / 6) * (a1 + 2 * a2 + 2 * a3 + a4);
+ v += (h / 6) * (b1 + 2 * b2 + 2 * b3 + b4);
+ }
+ expect(worst).toBeLessThan(1e-6);
+ });
+
+ it('is continuous in value and velocity where the ramp changes', () => {
+ const curve = pressFeedbackCurve();
+ for (const ms of [press.commitMs, press.menuDisplayMs]) {
+ const s = (ms - press.feedbackOnsetMs) / 1000;
+ expect(curve.at(s + 1e-7)).toBeCloseTo(curve.at(s - 1e-7), 6);
+ expect(curve.velocity(s + 1e-7)).toBeCloseTo(curve.velocity(s - 1e-7), 4);
+ }
+ });
+
+ it('starts from rest at 1 and rests on the last size', () => {
+ const curve = pressFeedbackCurve();
+ expect(curve.at(0)).toBe(1);
+ expect(curve.velocity(0)).toBe(0);
+ expect(curve.at(curve.duration)).toBeCloseTo(
+ pressFeedbackTarget(press.menuDisplayMs),
+ 3,
+ );
+ expect(Math.abs(curve.velocity(curve.duration))).toBeLessThan(1e-3);
+ });
+
+ it('continues from a press still moving', () => {
+ const curve = pressFeedbackCurve({from: 1.02, velocity: -0.05});
+ expect(curve.at(0)).toBeCloseTo(1.02, 10);
+ expect(curve.velocity(0)).toBeCloseTo(-0.05, 10);
+ });
+});
+
+describe('the press feedback against UIKit (iOS 26.2, measured frames)', () => {
+ it('a long press: the visible size follows UIKit’s within 0.05 pt rms on a 200 pt view', () => {
+ const {rms, max} = errors(UIKIT_LONG_PRESS, held);
+ expect(rms).toBeLessThan(0.05);
+ expect(max).toBeLessThan(0.12);
+ });
+
+ it('a press lifted at 0.25 s: it overshoots on the way back as UIKit’s does, within 0.05 pt rms', () => {
+ const {rms, max} = errors(UIKIT_EARLY_LIFT, liftedAt(UIKIT_EARLY_LIFT_AT));
+ expect(rms).toBeLessThan(0.05);
+ expect(max).toBeLessThan(0.12);
+ // The measured peak after the lift: 1.00504 at 332.8 ms.
+ expect(liftedAt(UIKIT_EARLY_LIFT_AT)(332.8)).toBeCloseTo(1.00504, 4);
+ });
+});
+
+describe('pressFeedbackMotion: the feedback plays the table’s motion (touch motion stays internal)', () => {
+ // The touch code registers the table before its first motion.
+ registerContextMenuTable();
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ function themed(values: Record) {
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(
+ (element: Element) =>
+ ({
+ getPropertyValue: (name: string) =>
+ element.hasAttribute('data-astryx-theme')
+ ? (values[name] ?? '')
+ : '',
+ }) as CSSStyleDeclaration,
+ );
+ const scope = document.createElement('div');
+ scope.setAttribute('data-astryx-theme', 'test');
+ const child = document.createElement('div');
+ scope.append(child);
+ document.body.append(scope);
+ return child;
+ }
+
+ it('reads the table’s spring, onset and latency where no theme sets them', () => {
+ const element = themed({});
+ expect(pressFeedbackMotion(element)).toEqual({
+ spring: contextMenu.press.feedbackSpring,
+ onsetMs: contextMenu.press.feedbackOnsetMs,
+ latencyMs: contextMenu.press.feedbackLatencyMs,
+ });
+ });
+
+ it('takes nothing from a theme: no ContextMenu value is a motion role', () => {
+ const element = themed({
+ '--motion-context-menu-press-feedback-spring': '0.5s 0',
+ '--motion-context-menu-press-feedback-latency-ms': '80ms',
+ '--motion-context-menu-press-feedback-onset-ms': '300ms',
+ '--motion-context-menu-press-commit-ms': '100ms',
+ });
+ const motion = pressFeedbackMotion(element);
+ expect(motion).toEqual({
+ spring: contextMenu.press.feedbackSpring,
+ onsetMs: contextMenu.press.feedbackOnsetMs,
+ latencyMs: contextMenu.press.feedbackLatencyMs,
+ });
+ const curve = pressFeedbackCurve({motion});
+ expect(curve.at(0)).toBe(1);
+ expect(curve.at(0.3)).toBeGreaterThan(1);
+ });
+
+ it('starts its ramp at the onset it is given and reaches the commit continuously', () => {
+ // Nothing until the onset; the ramp then reaches UIKit's commit
+ // continuously.
+ expect(pressFeedbackTarget(250, 300)).toBe(1);
+ expect(pressFeedbackTarget(400, 300)).toBeCloseTo(1.016, 6);
+ expect(pressFeedbackTarget(400.001, 300)).toBeCloseTo(1.016, 4);
+ });
+});
diff --git a/packages/core/src/ContextMenu/contextMenuPressCurve.ts b/packages/core/src/ContextMenu/contextMenuPressCurve.ts
new file mode 100644
index 0000000000000..aa77f4b4aa388
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuPressCurve.ts
@@ -0,0 +1,182 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file contextMenuPressCurve.ts
+ * @input The context-menu constants and
+ * the motion foundation's spring toward a moving target
+ * @output Exports pressFeedbackTarget (the size UIKit asks the press copy for
+ * at a moment of the press), PRESS_FEEDBACK_START_MS, pressFeedbackMotion
+ * (the feedback's spring, onset and latency) and
+ * pressFeedbackCurve (the size it shows, as a PressFeedbackCurve the
+ * compositor animator plays)
+ * @position The press feedback's curve, for ContextMenu's touch invocation
+ *
+ * On iOS 26.2 a finger resting on a view with a context menu makes a copy of
+ * the view grow from its center: UIKit asks for a size that ramps linearly
+ * (`contextMenu.press.feedbackRate` from the onset, a slower
+ * `feedbackRateAfterCommit` after the commit, until the menu displays), and
+ * the copy's visible size chases that ramp through a spring
+ * (`feedbackSpring`), shown `feedbackLatencyMs` after UIKit starts it. These
+ * are pure functions of the constants; the curve is closed-form, so the whole
+ * held press can be computed when the finger lands and played on the
+ * compositor. None of them is a motion role: touch motion stays internal,
+ * so no theme retunes them, and `pressFeedbackMotion` reads the table's.
+ *
+ * SYNC: When modified, update
+ * /packages/core/src/ContextMenu/contextMenuPressCurve.test.ts
+ */
+
+import {
+ settlingDuration,
+ solveSpringTowardRamp,
+ toSpring,
+ type SpringDescription,
+ type SpringRampCurve,
+} from '../motion/spring';
+import {resolveMotion} from '../motion/resolveMotion';
+import {contextMenu} from '../motion/uikit/contextMenu';
+
+const {
+ feedbackOnsetMs,
+ commitMs,
+ menuDisplayMs,
+ feedbackRate,
+ feedbackRateAfterCommit,
+ feedbackSpring,
+ feedbackLatencyMs,
+} = contextMenu.press;
+
+/** The press feedback's motion: its spring, onset and display latency. */
+export interface PressFeedbackMotion {
+ readonly spring: SpringDescription;
+ readonly onsetMs: number;
+ readonly latencyMs: number;
+}
+
+/** The table's motion (UIKit's). */
+const TABLE_MOTION: PressFeedbackMotion = {
+ spring: feedbackSpring,
+ onsetMs: feedbackOnsetMs,
+ latencyMs: feedbackLatencyMs,
+};
+
+/**
+ * The press feedback's motion for `element`: the table's spring and latency,
+ * as its registry resolves them (no ContextMenu value is a motion role, so a
+ * theme sets none). The onset is the measured one: core's press machine
+ * decides when a press is believed.
+ */
+export function pressFeedbackMotion(
+ element: Element | null | undefined,
+): PressFeedbackMotion {
+ return {
+ spring: resolveMotion(element, contextMenu.press.feedbackSpring),
+ onsetMs: feedbackOnsetMs,
+ latencyMs: resolveMotion(element, contextMenu.press, 'feedbackLatencyMs'),
+ };
+}
+
+/**
+ * The scale UIKit asks the press copy for, `t` ms after the finger landed:
+ * 1 until the onset, then the first ramp, then (continuously) the second one
+ * until the menu displays, where it stops.
+ */
+export function pressFeedbackTarget(
+ t: number,
+ onsetMs: number = feedbackOnsetMs,
+): number {
+ if (t <= onsetMs) {
+ return 1;
+ }
+ const atCommit = 1 + (feedbackRate * Math.max(commitMs - onsetMs, 0)) / 1000;
+ if (t <= commitMs) {
+ return 1 + (feedbackRate * (t - onsetMs)) / 1000;
+ }
+ return (
+ atCommit +
+ (feedbackRateAfterCommit * (Math.min(t, menuDisplayMs) - commitMs)) / 1000
+ );
+}
+
+/**
+ * A closed-form curve over `duration` seconds: t is seconds from its start,
+ * the value at `duration` its end state. The shape the compositor animator
+ * plays (`animator.play`).
+ */
+export interface PressFeedbackCurve {
+ readonly duration: number;
+ at(t: number): number;
+ /** Units per second. */
+ velocity(t: number): number;
+}
+
+/** When the visible curve starts, ms after the finger landed. */
+export const PRESS_FEEDBACK_START_MS = feedbackOnsetMs + feedbackLatencyMs;
+
+/**
+ * The scale the press copy shows from `PRESS_FEEDBACK_START_MS` on (t in
+ * seconds from there), for a finger that stays: the feedback spring chasing
+ * `pressFeedbackTarget` as the screen shows it (`feedbackLatencyMs` late),
+ * chained piece by piece where the ramp changes, then settling on the last
+ * size. It starts from rest at 1 unless the view is still moving from an
+ * earlier press.
+ */
+export function pressFeedbackCurve({
+ from = 1,
+ velocity = 0,
+ motion = TABLE_MOTION,
+}: {
+ from?: number;
+ velocity?: number;
+ /** The motion to play (`pressFeedbackMotion`); the table's by default. */
+ motion?: PressFeedbackMotion;
+} = {}): PressFeedbackCurve {
+ const {onsetMs} = motion;
+ const spring = toSpring(motion.spring);
+ const commit = Math.max(commitMs - onsetMs, 0) / 1000;
+ const display = Math.max(menuDisplayMs - onsetMs, 0) / 1000;
+ const first = solveSpringTowardRamp(spring, {
+ from,
+ velocity,
+ target: 1,
+ slope: feedbackRate,
+ });
+ const second = solveSpringTowardRamp(spring, {
+ from: first.value(commit),
+ velocity: first.velocity(commit),
+ target: pressFeedbackTarget(commitMs, onsetMs),
+ slope: feedbackRateAfterCommit,
+ });
+ const secondLength = display - commit;
+ const last = solveSpringTowardRamp(spring, {
+ from: second.value(secondLength),
+ velocity: second.velocity(secondLength),
+ target: pressFeedbackTarget(menuDisplayMs, onsetMs),
+ slope: 0,
+ });
+ const settle = settlingDuration(spring, {epsilon: 1e-4});
+ const pieces: ReadonlyArray<[start: number, curve: SpringRampCurve]> = [
+ [0, first],
+ [commit, second],
+ [display, last],
+ ];
+ const pieceAt = (t: number): [number, SpringRampCurve] => {
+ for (let i = pieces.length - 1; i > 0; i--) {
+ if (t >= pieces[i][0]) {
+ return pieces[i];
+ }
+ }
+ return pieces[0];
+ };
+ return {
+ duration: display + settle,
+ at: t => {
+ const [start, curve] = pieceAt(t);
+ return curve.value(t - start);
+ },
+ velocity: t => {
+ const [start, curve] = pieceAt(t);
+ return curve.velocity(t - start);
+ },
+ };
+}
diff --git a/packages/core/src/ContextMenu/contextMenuPressFeedback.ts b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts
new file mode 100644
index 0000000000000..99663a0c7d090
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuPressFeedback.ts
@@ -0,0 +1,260 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file contextMenuPressFeedback.ts
+ * @input The press feedback's curve (contextMenuPressCurve.ts), the
+ * context-menu constants, the compositor animator, the trigger element and
+ * the press paint core's one press machine gives it (utils/pressFeedback.ts,
+ * `subscribePressPaint`: one shared registry, no observer per trigger)
+ * @output Exports useContextMenuPressFeedback (hold and release from
+ * ContextMenu's menu, and end when the lift takes over; the growth
+ * itself follows the press machine)
+ * @position The press feedback of ContextMenu's touch invocation
+ * (pressFeedback.ts believes the press, the trigger's context request
+ * opens the menu; this shows it)
+ *
+ * On iOS 26.2 a finger resting on a view with a context menu makes a copy of
+ * the view grow from its center: UIKit asks for a size that ramps linearly
+ * (`contextMenu.press.feedbackRate` from the onset, a slower
+ * `feedbackRateAfterCommit` after the commit), and the copy's visible size
+ * chases that ramp through a spring (`feedbackSpring`), shown
+ * `feedbackLatencyMs` after UIKit starts it. A finger that lifts or wanders
+ * before the commit sends the size back to 1 on the same spring
+ * (`returnLatencyMs` after the lift). After the commit the view stays grown
+ * while the menu is up, and returns on the dismissal spring
+ * (`springs.contextMenuDismiss`) when it closes.
+ *
+ * Here the trigger itself takes the scale (the individual `scale` property,
+ * from its center), played by the compositor animator. The trigger is a
+ * pressable surface of core's one press machine, which writes
+ * `data-astryx-press="on"` once it believes the press (its onset) and takes
+ * it away when the press ends (a lift, travel, a scroll, a second finger):
+ * the growth starts at "on" and springs back when it goes, unless the menu
+ * opened. The whole held curve is computed when it starts and placed on the
+ * document timeline, so it keeps advancing every frame while the main thread
+ * is busy. Nothing renders and nothing reads layout during the press. The
+ * machine's onset (150 ms, on a timer) stands for UIKit's measured
+ * `feedbackOnsetMs` (the same 150 ms, from the touch).
+ *
+ * Not shown: an inline trigger (`triggerAs="span"`), which a transform does
+ * not apply to, and Reduce Motion (`contextMenu.reducedMotionFeedback`).
+ *
+ * SYNC: When modified, update /packages/core/src/ContextMenu/ContextMenu.tsx
+ */
+
+import {useCallback, useEffect, useRef, type RefObject} from 'react';
+import {usePressFeedback} from '../hooks/usePressFeedback';
+import {
+ PRESSED_ATTRIBUTE,
+ subscribePressPaint,
+ type pressableProps,
+} from '../utils/pressFeedback';
+import {createAnimator, type Animator} from '../motion/animator';
+import {resolveMotion} from '../motion/resolveMotion';
+import {registerSpringsTable, springs} from '../motion/uikit/springs';
+import {
+ contextMenu,
+ registerContextMenuTable,
+} from '../motion/uikit/contextMenu';
+import {pressFeedbackCurve, pressFeedbackMotion} from './contextMenuPressCurve';
+
+const {feedbackSpring} = contextMenu.press;
+
+export interface ContextMenuPressFeedback {
+ /**
+ * The trigger's marker for core's press machine (utils/pressFeedback.ts):
+ * spread on the trigger; the growth follows the pressed state it writes.
+ */
+ pressable: typeof pressableProps;
+ /** The menu the press opened closed: return on the dismissal spring. */
+ release(): 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 still growing would carry the open menu with it.
+ */
+ hold(): void;
+ /**
+ * The lift takes over: the feedback lets go of the trigger at once (its
+ * scale and compositing layer), and the lift grows it on from the rect the
+ * press left.
+ */
+ end(): void;
+}
+
+/**
+ * The press feedback of a ContextMenu trigger. `isShown` is read at each
+ * press: false for an inline trigger. `triggerKey` changes when the trigger
+ * element is replaced (`triggerAs`), so the new one is followed.
+ */
+export function useContextMenuPressFeedback(
+ triggerRef: RefObject,
+ isShown: boolean,
+ triggerKey?: unknown,
+): ContextMenuPressFeedback {
+ const pressable = 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);
+
+ useEffect(
+ () => () => {
+ animatorRef.current?.dispose();
+ animatorRef.current = null;
+ },
+ [],
+ );
+
+ const animatorFor = useCallback((): Animator | null => {
+ const element = triggerRef.current;
+ if (element == null) {
+ return null;
+ }
+ // The feedback's springs resolve through their tables (none is a motion
+ // role): register them before the first motion (idempotent).
+ registerContextMenuTable();
+ registerSpringsTable();
+ if (animatorRef.current?.element !== element) {
+ animatorRef.current?.dispose();
+ animatorRef.current = createAnimator(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) {
+ return;
+ }
+ const animator = animatorFor();
+ // Under Reduce Motion the view does not grow (UIKit's
+ // `reducedMotionFeedback`), and no fade stands in for it.
+ if (
+ animator == null ||
+ (animator.reducedMotion() !== 'off' &&
+ !contextMenu.reducedMotionFeedback)
+ ) {
+ return;
+ }
+ isGrownRef.current = true;
+ // The table's spring and latency. `time` is the onset (the press
+ // machine's "on").
+ const motion = pressFeedbackMotion(animator.element);
+ const at = time + motion.latencyMs;
+ animator.play(
+ {
+ scale: pressFeedbackCurve({
+ from: animator.get('scaleX', at),
+ velocity: animator.getVelocity('scaleX', at),
+ motion,
+ }),
+ },
+ {at},
+ );
+ },
+ [animatorFor],
+ );
+
+ const fail = useCallback(
+ (time: number) => {
+ const animator = animatorRef.current;
+ if (animator == null || !isGrownRef.current || isHeldRef.current) {
+ return;
+ }
+ settleBack(
+ animator.animate(
+ {scale: 1},
+ {spring: feedbackSpring},
+ {
+ at:
+ time +
+ resolveMotion(
+ animator.element,
+ contextMenu.press,
+ 'returnLatencyMs',
+ ),
+ },
+ ).finished,
+ );
+ },
+ [settleBack],
+ );
+
+ const release = useCallback(() => {
+ isHeldRef.current = false;
+ const animator = animatorRef.current;
+ if (animator == null || !isGrownRef.current) {
+ return;
+ }
+ settleBack(
+ animator.animate({scale: 1}, {spring: springs.contextMenuDismiss})
+ .finished,
+ );
+ }, [settleBack]);
+
+ const hold = useCallback(() => {
+ isHeldRef.current = true;
+ if (isGrownRef.current) {
+ animatorRef.current?.stop(['scale']);
+ }
+ }, []);
+
+ const end = useCallback(() => {
+ const animator = animatorRef.current;
+ if (animator == null || !isGrownRef.current) {
+ return;
+ }
+ isGrownRef.current = false;
+ // Let go of the trigger at once, its compositing layer included: the
+ // lift's own motion has it to itself from here (a new press makes a new
+ // animator).
+ const element = animator.element;
+ animatorRef.current = null;
+ animator.dispose();
+ element?.style.removeProperty('scale');
+ }, []);
+
+ // Follow the press machine's paint on the trigger: grow from its "on",
+ // spring back when the press ends with no menu. One registry serves every
+ // surface (no observer or listener per trigger).
+ useEffect(() => {
+ void triggerKey;
+ const element = triggerRef.current;
+ if (element == null) {
+ return;
+ }
+ let isPressed = element.getAttribute(PRESSED_ATTRIBUTE) === 'on';
+ return subscribePressPaint(element, paint => {
+ const next = paint === 'on';
+ if (next === isPressed) {
+ return;
+ }
+ isPressed = next;
+ if (next) {
+ start(performance.now());
+ } else {
+ fail(performance.now());
+ }
+ });
+ }, [triggerRef, triggerKey, start, fail]);
+
+ return {pressable, release, hold, end};
+}
diff --git a/packages/core/src/ContextMenu/contextMenuRequests.ts b/packages/core/src/ContextMenu/contextMenuRequests.ts
new file mode 100644
index 0000000000000..1c99a76d85c2d
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuRequests.ts
@@ -0,0 +1,125 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file contextMenuRequests.ts
+ * @input An element, whether its menu is disabled, where to forward each
+ * request, and the hold's timeline, drift tolerance and stages
+ * @output attachContextMenuRequests: the headless context menu's request core
+ * (spec:AST-107 FR8). It attaches the element's context request
+ * (gestures/contextRequest.ts) and forwards each request, and `open(at)`
+ * and `close()`, to whoever renders the menu; `destroy` detaches it
+ * @position Used by createContextMenu, which ContextMenu is built on: one
+ * request path for both
+ */
+
+import {
+ attachContextRequest,
+ type ContextRequestOptions,
+} from '../gestures/contextRequest';
+import type {ContextMenuAttachedRequest} from './ContextMenu';
+
+/** What a menu receives: a request to open, or a close. */
+export type ContextMenuForwarded = ContextMenuAttachedRequest | 'close';
+
+export interface ContextMenuRequestOptions {
+ /** While true, the element makes no request and keeps the browser's menu. */
+ isDisabled?: boolean;
+ /** The hold's timeline and drift tolerance (the context request's `hold`). */
+ hold?: ContextRequestOptions['hold'];
+ /** The hold's stages (the context request's `onHold`). */
+ onHold?: ContextRequestOptions['onHold'];
+}
+
+export interface ContextMenuRequests {
+ /** Forwards an open at `at`, client coordinates, or at the element. */
+ open(at?: {readonly x: number; readonly y: number}): void;
+ /** Forwards a close. */
+ close(): void;
+ /** Takes new options; enabling, disabling or a new hold attaches again. */
+ update(options: ContextMenuRequestOptions): void;
+ /** Detaches the request. */
+ destroy(): void;
+}
+
+/**
+ * Attaches `element`'s context request and forwards each request to
+ * `forward` (spec:AST-107 FR8). A disabled menu's request registers nothing
+ * (spec:AST-094 FR24), so enabling attaches it again.
+ */
+export function attachContextMenuRequests(
+ element: HTMLElement,
+ initialOptions: ContextMenuRequestOptions,
+ forward: (forwarded: ContextMenuForwarded) => void,
+): ContextMenuRequests {
+ let options = initialOptions;
+ let isDestroyed = false;
+ let detach: () => void = () => {};
+
+ const attach = () => {
+ detach();
+ detach = attachContextRequest(element, {
+ onRequest: request => {
+ if (isDestroyed) {
+ return;
+ }
+ // Several browsers report Shift+F10 as a mouse `contextmenu` at
+ // (0, 0) with no keydown to read: that is a key's request, which opens
+ // at the element, not at the viewport's corner (menus-8).
+ const isKeyAtOrigin =
+ request.kind === 'pointer' &&
+ request.pointerType === 'mouse' &&
+ request.point?.x === 0 &&
+ request.point.y === 0;
+ forward(
+ isKeyAtOrigin
+ ? {kind: 'keyboard', point: null}
+ : {kind: request.kind, point: request.point},
+ );
+ },
+ isEnabled: () => !isDestroyed && options.isDisabled !== true,
+ hold: options.hold,
+ onHold: phase => options.onHold?.(phase),
+ });
+ };
+ attach();
+
+ return {
+ open(at) {
+ if (!isDestroyed) {
+ forward({kind: 'open', point: at ?? null});
+ }
+ },
+ close() {
+ if (!isDestroyed) {
+ forward('close');
+ }
+ },
+ update(next) {
+ const wasDisabled = options.isDisabled === true;
+ const holdChanged =
+ JSON.stringify(options.hold ?? null) !==
+ JSON.stringify(next.hold ?? null);
+ options = next;
+ if (isDestroyed) {
+ return;
+ }
+ const isDisabled = options.isDisabled === true;
+ if (isDisabled && !wasDisabled) {
+ forward('close');
+ }
+ if (wasDisabled !== isDisabled || holdChanged) {
+ attach();
+ }
+ },
+ destroy() {
+ if (isDestroyed) {
+ return;
+ }
+ isDestroyed = true;
+ detach();
+ detach = () => {};
+ },
+ };
+}
diff --git a/packages/core/src/ContextMenu/contextMenuRows.tsx b/packages/core/src/ContextMenu/contextMenuRows.tsx
new file mode 100644
index 0000000000000..70b2b2418c099
--- /dev/null
+++ b/packages/core/src/ContextMenu/contextMenuRows.tsx
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file contextMenuRows.tsx
+ * @input createContextMenu's rows context for its `render` slot, and a React
+ * caller's Core providers
+ * @output createMenuRowsSlot, MenuRows and useCoreBridge: how a React caller
+ * hands createContextMenu a `render` for its rows (spec:AST-107 FR8). The
+ * rows stay rendered into a host the menu's container adopts while the menu
+ * is open, so its first enabled row is there when focus starts, and they
+ * read the menu's own row context, open state and layer
+ * @position Internal to ContextMenu: shared by useContextMenu (its rows in a
+ * root it owns) and ContextMenu (its rows portaled from its own tree, so a
+ * caller's own contexts reach them)
+ */
+
+import {use, useCallback, useSyncExternalStore, type ReactNode} from 'react';
+import {
+ DropdownMenuContext,
+ DropdownMenuRootOpenContext,
+} from '../DropdownMenu/DropdownMenuContext';
+import {InternationalizationContext} from '../i18n/InternationalizationContext';
+import {LayerContext} from '../Layer/LayerContext';
+import {LayerDepthContext} from '../Layer/LayerDepthContext';
+import {LinkContext} from '../Link/LinkContext';
+import {ThemeContext} from '../theme/useTheme';
+import {
+ readRowsContext,
+ subscribeRowsContext,
+ type ContextMenuRowsContext,
+} from './createContextMenu';
+
+/** Wraps a menu in a React caller's Core providers. */
+export type CoreBridge = (menu: ReactNode) => ReactNode;
+
+/** Where a React caller's rows render, and the `render` that shows them. */
+export interface MenuRowsSlot {
+ /** Where the rows render; the menu's container adopts it while open. */
+ readonly host: HTMLElement;
+ /** createContextMenu's `render`: the container adopts the host. */
+ readonly render: (container: HTMLElement) => () => void;
+ /** Calls `listener` when the menu's rows context changes. */
+ readonly subscribe: (listener: () => void) => () => void;
+ /** The menu's rows context while it is open; null while it is closed. */
+ readonly getRowsContext: () => ContextMenuRowsContext | null;
+}
+
+export function createMenuRowsSlot(doc: Document): MenuRowsSlot {
+ const host = doc.createElement('div');
+ let rows: ContextMenuRowsContext | null = null;
+ const listeners = new Set<() => void>();
+ const notify = () => {
+ for (const listener of listeners) {
+ listener();
+ }
+ };
+ return {
+ host,
+ render(container) {
+ container.append(host);
+ rows = readRowsContext(container);
+ const stop = subscribeRowsContext(container, () => {
+ rows = readRowsContext(container);
+ notify();
+ });
+ notify();
+ return () => {
+ stop();
+ rows = null;
+ notify();
+ host.remove();
+ };
+ },
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ getRowsContext: () => rows,
+ };
+}
+
+/**
+ * Gives a React caller's rows what they read from inside the menu while it
+ * is open: its row context (a choice closes it, a sub-menu drills in), its
+ * open state, its layer (a flyout stacks above it) and its layer depth (a
+ * layer in the rows takes Escape before the menu).
+ */
+export function MenuRows({
+ slot,
+ children,
+}: {
+ slot: MenuRowsSlot;
+ children: ReactNode;
+}) {
+ const rows = useSyncExternalStore(
+ slot.subscribe,
+ slot.getRowsContext,
+ slot.getRowsContext,
+ );
+ const callerLayer = use(LayerContext);
+ const callerDepth = use(LayerDepthContext);
+ return (
+
+
+
+
+ {children}
+
+
+
+
+ );
+}
+
+/** The caller's Core providers (theme, layer, link, i18n), for the menu. */
+export function useCoreBridge(): CoreBridge {
+ const theme = use(ThemeContext);
+ const layer = use(LayerContext);
+ const link = use(LinkContext);
+ const intl = use(InternationalizationContext);
+ return useCallback(
+ menu => (
+
+
+
+ {menu}
+
+
+
+ ),
+ [intl, theme, layer, link],
+ );
+}
diff --git a/packages/core/src/ContextMenu/createContextMenu.doc.mjs b/packages/core/src/ContextMenu/createContextMenu.doc.mjs
new file mode 100644
index 0000000000000..023263a26efd6
--- /dev/null
+++ b/packages/core/src/ContextMenu/createContextMenu.doc.mjs
@@ -0,0 +1,164 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'createContextMenu',
+ displayName: 'createContextMenu',
+ // A factory documented as a hook: listed with the utilities, beside its
+ // hook, not as a tile in the components gallery.
+ group: 'Utilities',
+ keywords: [
+ 'context menu',
+ 'right click',
+ 'long press',
+ 'shift f10',
+ 'row actions',
+ 'headless',
+ 'vanilla',
+ 'factory',
+ ],
+ params: [
+ {
+ name: 'element',
+ type: 'HTMLElement',
+ description:
+ 'The element that owns the menu, already on the page, such as a list row. Its markup is untouched: the menu renders outside it, so a `li` row keeps its list valid.',
+ required: true,
+ },
+ {
+ name: 'options.items',
+ type: 'ContextMenuOption[]',
+ description:
+ "The menu's rows, as ContextMenu's `items`: actions, dividers, sections and sub-menus. Give `items` or `render`.",
+ },
+ {
+ name: 'options.render',
+ type: '(container: HTMLElement) => (() => void) | undefined',
+ description:
+ "Fills the menu's container with custom content in plain DOM, once, as the menu is attached; return a cleanup, which runs as it is destroyed. Give rows the `menuitem` role so the keys reach them.",
+ },
+ {
+ name: 'options.label',
+ type: 'string',
+ description:
+ 'Names the menu for assistive technology, as ContextMenu\u2019s `label`.',
+ },
+ {
+ name: 'options.isDisabled',
+ type: 'boolean',
+ description:
+ 'Keeps the menu from opening: the element then makes no request, and the browser keeps its own menu.',
+ },
+ {
+ name: 'options.onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description:
+ 'Called with true when the menu opens and false when it closes.',
+ },
+ {
+ name: 'options.presentation',
+ type: "'popover' | 'bottom-sheet' | 'adaptive'",
+ description:
+ 'Where the menu appears, as ContextMenu\u2019s `presentation`.',
+ },
+ ],
+ returns: [
+ {
+ name: 'open',
+ type: '(at?: {x: number, y: number}) => void',
+ description:
+ "Opens the menu at `at`, in client coordinates, or at the element's bottom-left corner without it, and focuses its first row.",
+ },
+ {
+ name: 'close',
+ type: '() => void',
+ description:
+ 'Closes the menu; focus returns to what had it before the menu opened.',
+ },
+ {
+ name: 'destroy',
+ type: '() => void',
+ description:
+ 'Closes the menu and removes every listener and node the factory added. Call it when you remove the element.',
+ },
+ ],
+ usage: {
+ description:
+ "Attaches ContextMenu's menu to an element that is already on the page, without React. It opens on the element's context request: a held finger or pen, a right click, Shift+F10 or the context-menu key, each once per gesture. The menu is ContextMenu's own, with its rows, keys, sub-menus and dismissal. Use the `useContextMenu` hook in React. When you render the trigger yourself, use the ContextMenu component instead.",
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Attach it to the element a person acts on, such as a row, so a long press, a right click and Shift+F10 all reach it.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep every action reachable another way too, such as a MoreMenu on the row: a context menu is a shortcut that many people never discover.',
+ },
+ {
+ guidance: true,
+ description: 'Call `destroy` when the element leaves the page.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Wrap the element in another element for the menu: the factory attaches to the element itself.',
+ },
+ ],
+ accessibility: [
+ {
+ name: 'Keyboard and assistive technology',
+ category: 'Keyboard',
+ description:
+ 'Shift+F10 or the context-menu key opens the menu on a focused element, so give the element a tab stop. The menu follows the WAI-ARIA menu pattern: focus starts on the first enabled row, Up and Down move between rows, Home and End jump to the ends, typing a letter moves to a row that starts with it, Escape closes it, and focus returns to the element.',
+ },
+ {
+ name: 'Reduce Motion',
+ category: 'Content',
+ criterion: '2.3.3 Animation from Interactions',
+ description:
+ 'The menu appears as ContextMenu\u2019s does: under Reduce Motion it appears without moving, and on a touch screen it fades in.',
+ },
+ ],
+ },
+ relatedComponents: ['ContextMenu', 'MoreMenu'],
+ relatedHooks: ['useContextMenu'],
+ importPath: '@astryxdesign/core/ContextMenu',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ "Attaches ContextMenu's menu to an existing element, without React; opens on a long press, a right click or Shift+F10.",
+ paramDescriptions: {
+ element: 'The element that owns the menu; its markup is untouched.',
+ 'options.items': "ContextMenu's rows. Give items or render.",
+ 'options.render':
+ '(container) => cleanup; fills the menu in plain DOM when it opens.',
+ 'options.label': 'Names the menu.',
+ 'options.isDisabled': 'Keeps it from opening.',
+ 'options.onOpenChange': '(isOpen) => void.',
+ 'options.presentation': "As ContextMenu's presentation.",
+ },
+ returnDescriptions: {
+ open: '(at?) => void; at the element without a point.',
+ close: '() => void; focus returns.',
+ destroy: '() => void; removes every listener and node.',
+ },
+ usage: {
+ description:
+ "Opens on the element's context request; the menu is ContextMenu's. In React, use useContextMenu; to render the trigger, use ContextMenu.",
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Attach it to the row itself; call destroy on removal.',
+ },
+ {
+ guidance: false,
+ description: 'Wrap the element in another element for the menu.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/ContextMenu/createContextMenu.ssr.test.tsx b/packages/core/src/ContextMenu/createContextMenu.ssr.test.tsx
new file mode 100644
index 0000000000000..6da66156966b4
--- /dev/null
+++ b/packages/core/src/ContextMenu/createContextMenu.ssr.test.tsx
@@ -0,0 +1,48 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createContextMenu.ssr.test.tsx
+ * @input vitest (jsdom), react-dom/server, a fresh module graph
+ * @output Checks that createContextMenu and useContextMenu are safe on the
+ * server (spec:AST-107 FR6): a component using the hook renders only its own
+ * markup, and importing either does no DOM work
+ * @position Server-render and import checks for createContextMenu.tsx and
+ * useContextMenu.tsx
+ */
+
+import {useRef} from 'react';
+import {renderToString} from 'react-dom/server';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {useContextMenu} from './useContextMenu';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function Row() {
+ const ref = useRef(null);
+ useContextMenu(ref, {items: [{label: 'Archive'}]});
+ return (
+
+ );
+}
+
+describe('createContextMenu and useContextMenu on the server (spec:AST-107 FR6)', () => {
+ it('a component using useContextMenu renders only its own markup', () => {
+ expect(renderToString(
)).toBe('');
+ });
+
+ it('importing the factory and its hook adds no node and no listener', async () => {
+ vi.resetModules();
+ const children = document.body.childElementCount;
+ const documentListeners = vi.spyOn(document, 'addEventListener');
+ const windowListeners = vi.spyOn(window, 'addEventListener');
+ await import('./createContextMenu');
+ await import('./useContextMenu');
+ expect(documentListeners).not.toHaveBeenCalled();
+ expect(windowListeners).not.toHaveBeenCalled();
+ expect(document.body.childElementCount).toBe(children);
+ });
+});
diff --git a/packages/core/src/ContextMenu/createContextMenu.test.tsx b/packages/core/src/ContextMenu/createContextMenu.test.tsx
new file mode 100644
index 0000000000000..14cd5adfd9bbf
--- /dev/null
+++ b/packages/core/src/ContextMenu/createContextMenu.test.tsx
@@ -0,0 +1,472 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createContextMenu.test.tsx
+ * @input vitest (jsdom), createContextMenu on a plain element with no React
+ * around it
+ * @output Checks the headless context menu's contract (spec:AST-107 FR8): it
+ * opens ContextMenu's own menu on the element's context request (a right
+ * click, Shift+F10) or open(at), focuses its first row as ContextMenu does,
+ * closes on Escape, a choice or close(), returns focus, renders a plain-JS
+ * `render` callback's content, registers nothing while disabled, and
+ * destroy removes it all
+ * @position Testing for createContextMenu.tsx
+ */
+
+import {act, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {contextMenu} from '../motion/uikit/contextMenu';
+import {dataAttr, stableClassName} from '../naming';
+import {
+ createContextMenu,
+ type ContextMenuController,
+} from './createContextMenu';
+
+let element: HTMLElement;
+let controllers: ContextMenuController[] = [];
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ });
+ element = document.createElement('div');
+ element.tabIndex = 0;
+ element.textContent = 'Inbox';
+ document.body.append(element);
+});
+
+afterEach(() => {
+ act(() => {
+ for (const controller of controllers) {
+ controller.destroy();
+ }
+ });
+ controllers = [];
+ element.remove();
+ vi.restoreAllMocks();
+});
+
+function attach(
+ options: Parameters[1],
+): ContextMenuController {
+ // The factory renders its menu in a root of its own as it attaches.
+ let controller: ContextMenuController | undefined;
+ act(() => {
+ controller = createContextMenu(element, options);
+ });
+ if (controller == null) {
+ throw new Error('createContextMenu returned nothing');
+ }
+ controllers.push(controller);
+ return controller;
+}
+
+function rightClick(target: Element, x = 40, y = 50): MouseEvent {
+ const event = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: x,
+ clientY: y,
+ button: 2,
+ });
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ return event;
+}
+
+function press(target: Element, key: string, init: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ key,
+ ...init,
+ });
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ return event;
+}
+
+const menu = () => document.querySelector('[role="menu"]');
+/** Whether the menu's popover is showing (the popover mocks above). */
+const isOpen = () =>
+ menu()?.closest('[popover]')?.hasAttribute('popover-open') === true;
+/** Whether the menu inside `root` is showing (the popover mocks above). */
+const isOpenIn = (root: ParentNode) =>
+ root
+ .querySelector('[role="menu"]')
+ ?.closest('[popover]')
+ ?.hasAttribute('popover-open') === true;
+const rows = () =>
+ Array.from(document.querySelectorAll('[role="menuitem"]'));
+
+describe('createContextMenu', () => {
+ it('opens on a right click, keeps the browser menu off, and reports the open', () => {
+ const onOpenChange = vi.fn();
+ attach({
+ label: 'Inbox actions',
+ onOpenChange,
+ items: [{label: 'Archive'}, {label: 'Delete'}],
+ });
+ const event = rightClick(element);
+ expect(event.defaultPrevented).toBe(true);
+ expect(menu()?.getAttribute('aria-label')).toBe('Inbox actions');
+ expect(rows().map(row => row.textContent)).toEqual(['Archive', 'Delete']);
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it("is ContextMenu's own menu, with ContextMenu's theme class", () => {
+ attach({items: [{label: 'Archive'}]});
+ rightClick(element);
+ expect(menu()?.classList.contains(stableClassName('context-menu'))).toBe(
+ true,
+ );
+ });
+
+ it('a right click focuses the first row, as ContextMenu does', async () => {
+ attach({items: [{label: 'Archive'}, {label: 'Delete'}]});
+ rightClick(element);
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ });
+
+ it('Shift+F10 opens it with the first row focused', async () => {
+ attach({items: [{label: 'Archive'}, {label: 'Delete'}]});
+ element.focus();
+ press(element, 'F10', {shiftKey: true});
+ expect(isOpen()).toBe(true);
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ });
+
+ it('the arrow keys move between rows, and Escape closes it and returns focus', async () => {
+ const onOpenChange = vi.fn();
+ attach({onOpenChange, items: [{label: 'Archive'}, {label: 'Delete'}]});
+ element.focus();
+ press(element, 'ContextMenu');
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ press(rows()[0], 'ArrowDown');
+ expect(document.activeElement).toBe(rows()[1]);
+ press(rows()[1], 'Escape');
+ await waitFor(() => expect(isOpen()).toBe(false));
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ expect(document.activeElement).toBe(element);
+ });
+
+ it('Home and End jump to the first and last rows (spec:AST-107 FR8)', async () => {
+ attach({items: [{label: 'Archive'}, {label: 'Move'}, {label: 'Delete'}]});
+ element.focus();
+ press(element, 'F10', {shiftKey: true});
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ press(rows()[0], 'End');
+ expect(document.activeElement).toBe(rows()[2]);
+ press(rows()[2], 'Home');
+ expect(document.activeElement).toBe(rows()[0]);
+ });
+
+ it('focus starts on the first enabled row (spec:AST-107 FR8)', async () => {
+ attach({items: [{label: 'Archive', isDisabled: true}, {label: 'Delete'}]});
+ element.focus();
+ press(element, 'F10', {shiftKey: true});
+ expect(isOpen()).toBe(true);
+ await waitFor(() =>
+ expect(document.activeElement?.textContent).toContain('Delete'),
+ );
+ });
+
+ it("lives inside the element's dialog, where a modal dialog leaves it usable", () => {
+ attach({items: [{label: 'Archive'}]});
+ // The element moves into a dialog after the menu is attached.
+ const dialog = document.createElement('dialog');
+ document.body.append(dialog);
+ dialog.append(element);
+ rightClick(element);
+ expect(isOpen()).toBe(true);
+ const host = document.querySelector(`[${dataAttr('context-menu-host')}]`);
+ expect(host?.parentElement).toBe(dialog);
+ expect(element.contains(host)).toBe(false);
+ dialog.remove();
+ });
+
+ it("lives inside the element's popover, so opening it leaves that popover open", () => {
+ attach({items: [{label: 'Archive'}]});
+ const popover = document.createElement('div');
+ popover.setAttribute('popover', 'auto');
+ document.body.append(popover);
+ popover.append(element);
+ rightClick(element);
+ const host = document.querySelector(`[${dataAttr('context-menu-host')}]`);
+ expect(host?.parentElement).toBe(popover);
+ popover.remove();
+ });
+
+ it("lives inside the element's shadow root, so the menu stays in the element's tree", () => {
+ attach({items: [{label: 'Archive'}]});
+ const shadowHost = document.createElement('div');
+ document.body.append(shadowHost);
+ const shadow = shadowHost.attachShadow({mode: 'open'});
+ shadow.append(element);
+ rightClick(element);
+ expect(isOpenIn(shadow)).toBe(true);
+ const host = shadow.querySelector(`[${dataAttr('context-menu-host')}]`);
+ expect(host?.parentNode).toBe(shadow);
+ shadowHost.remove();
+ });
+
+ it('a mouse press outside the menu closes it (spec:AST-107 FR8)', () => {
+ attach({items: [{label: 'Archive'}]});
+ rightClick(element);
+ expect(isOpen()).toBe(true);
+ act(() => {
+ document.body.dispatchEvent(
+ new MouseEvent('mousedown', {bubbles: true, cancelable: true}),
+ );
+ });
+ expect(isOpen()).toBe(false);
+ });
+
+ it('choosing a row runs it and closes the menu', async () => {
+ const onArchive = vi.fn();
+ attach({items: [{label: 'Archive', onClick: onArchive}]});
+ rightClick(element);
+ await userEvent.setup().click(rows()[0]);
+ expect(onArchive).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(isOpen()).toBe(false));
+ });
+
+ it('a click inside the menu never reaches the element it is attached to', () => {
+ const onElementClick = vi.fn();
+ element.addEventListener('click', onElementClick);
+ attach({items: [{label: 'Archive'}]});
+ rightClick(element);
+ act(() => {
+ rows()[0].click();
+ });
+ expect(onElementClick).not.toHaveBeenCalled();
+ });
+
+ it('open(at) and close() drive it without a request', () => {
+ const onOpenChange = vi.fn();
+ const controller = attach({onOpenChange, items: [{label: 'Archive'}]});
+ act(() => {
+ controller.open({x: 10, y: 20});
+ });
+ expect(isOpen()).toBe(true);
+ act(() => {
+ controller.close();
+ });
+ expect(isOpen()).toBe(false);
+ expect(onOpenChange.mock.calls).toEqual([[true], [false]]);
+ });
+
+ it('fills the menu through `render` in plain DOM once, and runs its cleanup when destroyed', () => {
+ const cleanup = vi.fn();
+ const controller = attach({
+ render: container => {
+ const button = document.createElement('button');
+ button.setAttribute('role', 'menuitem');
+ button.textContent = 'Custom';
+ container.append(button);
+ return cleanup;
+ },
+ });
+ rightClick(element);
+ expect(rows().map(row => row.textContent)).toEqual(['Custom']);
+ act(() => {
+ controller.close();
+ });
+ rightClick(element);
+ expect(rows().map(row => row.textContent)).toEqual(['Custom']);
+ expect(cleanup).not.toHaveBeenCalled();
+ act(() => {
+ controller.destroy();
+ });
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers nothing while disabled: the browser keeps its own menu', () => {
+ attach({isDisabled: true, items: [{label: 'Archive'}]});
+ const event = rightClick(element);
+ expect(event.defaultPrevented).toBe(false);
+ expect(isOpen()).toBe(false);
+ });
+
+ it('destroy closes it and removes everything it added', () => {
+ const before = document.body.childElementCount;
+ const controller = attach({items: [{label: 'Archive'}]});
+ rightClick(element);
+ act(() => {
+ controller.destroy();
+ });
+ expect(isOpen()).toBe(false);
+ expect(document.body.childElementCount).toBe(before);
+ const event = rightClick(element);
+ expect(event.defaultPrevented).toBe(false);
+ expect(isOpen()).toBe(false);
+ });
+});
+
+// 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;
+
+/** 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 as a browser reports it: its pointer event, then its touch event. */
+function fingerDown(target: Element, x = 20, y = 20) {
+ const pointer = new PointerEvent('pointerdown', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: 1,
+ pointerType: 'touch',
+ isPrimary: true,
+ clientX: x,
+ clientY: y,
+ buttons: 1,
+ });
+ Object.defineProperty(pointer, 'timeStamp', {value: performance.now()});
+ target.dispatchEvent(pointer);
+ const touch = {identifier: 1, target, clientX: x, clientY: y};
+ const start = new Event('touchstart', {bubbles: true, cancelable: true});
+ Object.defineProperties(start, {
+ touches: {value: [touch]},
+ targetTouches: {value: [touch]},
+ changedTouches: {value: [touch]},
+ timeStamp: {value: performance.now()},
+ });
+ target.dispatchEvent(start);
+}
+
+describe('createContextMenu under a finger: ContextMenu\u2019s touch model (spec:AST-107 FR8)', () => {
+ 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 a held finger at UIKit\u2019s moment where the primary pointer is coarse, as ContextMenu does, not at 500 ms', () => {
+ stubPointer(true);
+ attach({items: [{label: 'Archive'}]});
+ act(() => {
+ fingerDown(element);
+ });
+ act(() => {
+ vi.advanceTimersByTime(600);
+ });
+ expect(isOpen()).toBe(false);
+ act(() => {
+ vi.advanceTimersByTime(contextMenu.press.menuDisplayMs - 600);
+ });
+ expect(isOpen()).toBe(true);
+ });
+});
+
+describe('createContextMenu: a finger\u2019s press outside (spec:AST-107 FR8)', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'performance',
+ 'Date',
+ ],
+ });
+ // The gesture host remembers the latest event time across cases.
+ clockEpoch += 100_000;
+ vi.advanceTimersByTime(clockEpoch);
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /** A finger's press as a browser reports it: pointer, then touch. */
+ function fingerDown(target: Element, id: number) {
+ const pointer = new PointerEvent('pointerdown', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerId: id,
+ pointerType: 'touch',
+ isPrimary: true,
+ clientX: 20,
+ clientY: 20,
+ buttons: 1,
+ });
+ Object.defineProperty(pointer, 'timeStamp', {value: performance.now()});
+ target.dispatchEvent(pointer);
+ const touch = {identifier: id, target, clientX: 20, clientY: 20};
+ const start = new Event('touchstart', {bubbles: true, cancelable: true});
+ Object.defineProperties(start, {
+ touches: {value: [touch]},
+ targetTouches: {value: [touch]},
+ changedTouches: {value: [touch]},
+ timeStamp: {value: performance.now()},
+ });
+ target.dispatchEvent(start);
+ }
+
+ it("leaves the menu open through the opening press's own compatibility mousedown, and closes on a later press outside", () => {
+ attach({items: [{label: 'Archive'}]});
+ act(() => {
+ fingerDown(element, 1);
+ });
+ act(() => {
+ vi.advanceTimersByTime(1_000);
+ });
+ expect(isOpen()).toBe(true);
+ // The compatibility mousedown the browser sends for the same press.
+ act(() => {
+ element.dispatchEvent(
+ new MouseEvent('mousedown', {bubbles: true, cancelable: true}),
+ );
+ });
+ expect(isOpen()).toBe(true);
+ // A new press outside is a new gesture.
+ act(() => {
+ fingerDown(document.body, 2);
+ document.body.dispatchEvent(
+ new MouseEvent('mousedown', {bubbles: true, cancelable: true}),
+ );
+ });
+ expect(isOpen()).toBe(false);
+ });
+});
diff --git a/packages/core/src/ContextMenu/createContextMenu.tsx b/packages/core/src/ContextMenu/createContextMenu.tsx
new file mode 100644
index 0000000000000..d36dfaa49f95a
--- /dev/null
+++ b/packages/core/src/ContextMenu/createContextMenu.tsx
@@ -0,0 +1,612 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file createContextMenu.tsx
+ * @input An element, its menu (`items`, or a `render` callback that fills it),
+ * and the menu's label, enablement, open-state callback and presentation
+ * @output createContextMenu: attaches a context menu to any element. It opens
+ * on the element's context request (a held finger or pen, a right click,
+ * Shift+F10 or the context-menu key) or on open(at); destroy removes
+ * every listener and node it added (spec:AST-107 FR8)
+ * @position Public factory, framework-agnostic for its caller: ContextMenu's
+ * own menu renders in an internal React root, so a page without React can
+ * attach one. ContextMenu is built on it (spec:AST-107 FR8, FR7) and hosts
+ * the menu in its own tree (hostContextMenuInReact); useContextMenu is its
+ * React wrapper (FR6), over the factory's own root. Both hand it a
+ * `render` for React rows (contextMenuRows.tsx) and pass later options
+ * through updateContextMenu
+ *
+ * Under the touch model the element's hold runs on UIKit's timeline, with
+ * ContextMenu's press feedback and, on a block element, the lift.
+ *
+ * The `render` slot publishes what the menu's rows read from inside the menu
+ * (its row context, its open state, its layer and layer depth) for its
+ * container, so content a React caller portals into the container keeps the
+ * rows' behavior: a choice closes the menu, a sub-menu drills in or flies out
+ * above it, and a layer in the rows takes Escape before the menu.
+ *
+ * The options mean what ContextMenu's props of the same names mean. The menu
+ * is ContextMenu's: its rows, keys, typeahead, sub-menus, dismissal and
+ * focus return. It lives in a container that carries the theme attributes of
+ * the element's themed ancestor, at the end of the element's nearest dialog
+ * or popover, or of its shadow root or the body: the element's own markup is
+ * untouched (a `li` row keeps its list valid), an event inside the menu never
+ * passes through the element, a modal dialog around the element leaves the
+ * menu usable, opening it leaves an open popover around the element open, and
+ * a shadow root's styles reach it.
+ */
+
+import {use, useLayoutEffect, useRef, useState, type ReactNode} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {
+ DropdownMenuContext,
+ DropdownMenuRootOpenContext,
+ type DropdownMenuContextValue,
+} from '../DropdownMenu/DropdownMenuContext';
+import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';
+import {LayerContext, type LayerContextValue} from '../Layer/LayerContext';
+import {LayerDepthContext} from '../Layer/LayerDepthContext';
+import {DEFAULT_COMPACT_DEFINITION} from '../theme/themeAdaptations';
+import {readPresentation} from '../utils/presentation';
+import {dataAttr} from '../naming';
+import {createPortal, flushSync} from 'react-dom';
+import {
+ attachContextMenuRequests,
+ type ContextMenuForwarded,
+ type ContextMenuRequestOptions,
+} from './contextMenuRequests';
+import {
+ CONTEXT_MENU_TOUCH_HOLD,
+ ContextMenuView,
+ type ContextMenuViewExtras,
+ type ContextMenuAttachedHandle,
+ type ContextMenuAttachment,
+ type ContextMenuAttachedRequest,
+ type ContextMenuOption,
+} from './ContextMenu';
+
+/** A point in client coordinates. */
+export interface ContextMenuPoint {
+ readonly x: number;
+ readonly y: number;
+}
+
+/**
+ * Renders a menu's content into `container` without React; returns a cleanup
+ * that runs when the menu closes.
+ */
+export type ContextMenuContentRenderer = (
+ container: HTMLElement,
+) => (() => void) | undefined;
+
+interface ContextMenuSharedOptions {
+ /** Names the menu for assistive technology. */
+ label?: string;
+ /** While true, the element makes no context request and keeps the browser's own menu. */
+ isDisabled?: boolean;
+ /** Called with true when the menu opens and false when it closes. */
+ onOpenChange?: (isOpen: boolean) => void;
+ /** Where the menu appears, as ContextMenu's `presentation`. */
+ presentation?: AdaptivePresentation;
+}
+
+export type CreateContextMenuOptions = ContextMenuSharedOptions &
+ (
+ | {items: ReadonlyArray; render?: undefined}
+ | {
+ items?: undefined;
+ /** Fills the menu's container with custom content in plain DOM. */
+ render: ContextMenuContentRenderer;
+ }
+ );
+
+/** What createContextMenu returns. */
+export interface ContextMenuController {
+ /** Opens the menu at `at`, client coordinates; at the element without it. */
+ open(at?: ContextMenuPoint): void;
+ /** Closes the menu. */
+ close(): void;
+ /** Closes the menu and removes every listener and node the factory added. */
+ destroy(): void;
+}
+
+/**
+ * @internal What a menu's rows read from inside the menu, published for the
+ * `render` slot's container.
+ */
+export interface ContextMenuRowsContext {
+ readonly menu: DropdownMenuContextValue | null;
+ readonly isOpen: boolean | null;
+ readonly layer: LayerContextValue | null;
+ /** The layer depth inside the menu, which ranks a layer in its rows above it. */
+ readonly depth: number;
+}
+
+interface RowsContextEntry {
+ value: ContextMenuRowsContext;
+ readonly listeners: Set<() => void>;
+}
+
+const rowsContexts = new WeakMap();
+
+function publishRowsContext(
+ container: HTMLElement,
+ value: ContextMenuRowsContext,
+): void {
+ const entry = rowsContexts.get(container);
+ if (entry == null) {
+ rowsContexts.set(container, {value, listeners: new Set()});
+ return;
+ }
+ entry.value = value;
+ for (const listener of entry.listeners) {
+ listener();
+ }
+}
+
+/** @internal The rows context published for `container`, while its menu is open. */
+export function readRowsContext(
+ container: HTMLElement,
+): ContextMenuRowsContext | null {
+ return rowsContexts.get(container)?.value ?? null;
+}
+
+/** @internal Calls `listener` when `container`'s rows context changes. */
+export function subscribeRowsContext(
+ container: HTMLElement,
+ listener: () => void,
+): () => void {
+ const entry = rowsContexts.get(container);
+ entry?.listeners.add(listener);
+ return () => {
+ entry?.listeners.delete(listener);
+ };
+}
+
+/**
+ * The React callers' way in (useContextMenu, ContextMenu): later options,
+ * their Core providers, and ContextMenu's own surface.
+ */
+interface ContextMenuWrapperAccess {
+ update(options: CreateContextMenuOptions): void;
+ bridge(wrap: (menu: ReactNode) => ReactNode): void;
+ view(view: ContextMenuViewExtras): void;
+ destroyFromReact(): void;
+}
+
+const wrapperAccess = new WeakMap<
+ ContextMenuController,
+ ContextMenuWrapperAccess
+>();
+
+/**
+ * @internal Passes later options to a menu createContextMenu attached
+ * (useContextMenu's path): the factory takes its options once, and creating
+ * it again would close a menu that is open.
+ */
+export function updateContextMenu(
+ controller: ContextMenuController,
+ options: CreateContextMenuOptions,
+): void {
+ wrapperAccess.get(controller)?.update(options);
+}
+
+/**
+ * @internal ContextMenu's own surface for the menu it is built on: the
+ * menu's size, width and styles, the cursor anchor inside its trigger, and
+ * whether the trigger is inline.
+ */
+export function viewContextMenu(
+ controller: ContextMenuController,
+ view: ContextMenuViewExtras,
+): void {
+ wrapperAccess.get(controller)?.view(view);
+}
+
+/**
+ * @internal Carries a React caller's Core providers (theme, layer, link,
+ * i18n) into the menu's own root (useContextMenu's and ContextMenu's path).
+ */
+export function bridgeContextMenu(
+ controller: ContextMenuController,
+ wrap: (menu: ReactNode) => ReactNode,
+): void {
+ wrapperAccess.get(controller)?.bridge(wrap);
+}
+
+/** Renders the menu in a React caller's own tree (ContextMenu's path). */
+type ContextMenuReactHost = (menu: ReactNode) => void;
+
+const reactHosts = new WeakMap();
+
+/**
+ * @internal Hosts the menu createContextMenu attaches to `element` next in a
+ * React caller's own tree (ContextMenu's path): called just before
+ * `createContextMenu(element, …)`, the factory renders its menu through
+ * `host`, as a portal into its container, instead of in a root of its own.
+ * The caller's contexts then reach the menu, and the menu unmounts with the
+ * caller's tree.
+ */
+export function hostContextMenuInReact(
+ element: Element,
+ host: ContextMenuReactHost,
+): void {
+ reactHosts.set(element, host);
+}
+
+/**
+ * @internal Destroys a menu from a React effect's cleanup (useContextMenu's
+ * path). React cannot unmount a root while it commits another, so the menu's
+ * own root renders nothing instead, an update React takes in its own time,
+ * and is dropped with its node; the element's request and the menu's node go
+ * at once, as `destroy` does.
+ */
+export function destroyContextMenuFromReact(
+ controller: ContextMenuController,
+): void {
+ wrapperAccess.get(controller)?.destroyFromReact();
+}
+
+/** Whether two option objects hold the same values under the same keys. */
+function isShallowEqual(a: object, b: object): boolean {
+ const aRecord = a as Record;
+ const bRecord = b as Record;
+ const keys = Object.keys(aRecord);
+ return (
+ keys.length === Object.keys(bRecord).length &&
+ keys.every(
+ key =>
+ Object.prototype.hasOwnProperty.call(bRecord, key) &&
+ Object.is(aRecord[key], bRecord[key]),
+ )
+ );
+}
+
+const THEME_ATTRIBUTES = ['data-theme', dataAttr('theme')] as const;
+
+/** The theme attributes of `element`'s nearest themed ancestor, onto `host`. */
+function mirrorTheme(host: HTMLElement, element: Element): void {
+ const themed = element.closest(
+ THEME_ATTRIBUTES.map(attribute => `[${attribute}]`).join(','),
+ );
+ for (const attribute of THEME_ATTRIBUTES) {
+ const value = themed?.getAttribute(attribute);
+ if (value == null) {
+ host.removeAttribute(attribute);
+ } else {
+ host.setAttribute(attribute, value);
+ }
+ }
+}
+
+/**
+ * Where the menu's container belongs, in the element's own tree: the end of
+ * its nearest dialog or popover (a modal dialog leaves everything outside it
+ * inert, and a menu outside an open popover would dismiss it), or of its
+ * shadow root (whose styles reach the menu there), or of the body.
+ */
+function containerParentFor(element: Element): ParentNode {
+ const scope = element.parentElement?.closest('dialog, [popover]');
+ if (scope != null) {
+ return scope;
+ }
+ const root = element.getRootNode();
+ return root instanceof ShadowRoot ? root : element.ownerDocument.body;
+}
+
+/**
+ * The `render` option's content: its callback fills a container, and the
+ * container's rows context is published for content a React caller portals
+ * into it.
+ */
+function RenderedContent({render}: {render: ContextMenuContentRenderer}) {
+ const containerRef = useRef(null);
+ const menu = use(DropdownMenuContext);
+ const isOpen = use(DropdownMenuRootOpenContext);
+ const layer = use(LayerContext);
+ const depth = use(LayerDepthContext);
+ // Declared first, so the container's rows context is out before `render`
+ // runs, and follows the menu after.
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (container != null) {
+ publishRowsContext(container, {menu, isOpen, layer, depth});
+ }
+ }, [menu, isOpen, layer, depth]);
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (container == null) {
+ return;
+ }
+ const cleanup = render(container);
+ return () => {
+ cleanup?.();
+ container.replaceChildren();
+ rowsContexts.delete(container);
+ };
+ }, [render]);
+ return
;
+}
+
+/** One request to forward, numbered so a repeat still reaches the menu. */
+interface Forwarded {
+ readonly seq: number;
+ readonly request: ContextMenuAttachedRequest | 'close';
+}
+
+interface AttachedMenuProps {
+ element: HTMLElement;
+ options: CreateContextMenuOptions;
+ view: ContextMenuViewExtras;
+ forwarded: Forwarded | null;
+ /** The menu's hold, for the element's context request. */
+ configureRequests: ContextMenuAttachment['configureRequests'];
+ onOpenChange: (isOpen: boolean) => void;
+}
+
+/**
+ * ContextMenu's menu, attached to the element: it attaches the element's
+ * context request itself, and open() and close() reach it as forwarded
+ * requests.
+ */
+function AttachedMenu({
+ element,
+ options,
+ view,
+ forwarded,
+ configureRequests,
+ onOpenChange,
+}: AttachedMenuProps) {
+ const handleRef = useRef(null);
+ const [attachment] = useState(() => ({
+ element,
+ handleRef,
+ configureRequests,
+ }));
+ // A plain element that lays out inline keeps the menu at the finger, as
+ // ContextMenu's inline trigger does: it has no preview to lift.
+ const [isInlineElement] = useState(
+ () =>
+ element.ownerDocument.defaultView
+ ?.getComputedStyle(element)
+ .display.startsWith('inline') ?? false,
+ );
+ const handleOpenChange = onOpenChange;
+ useLayoutEffect(() => {
+ if (forwarded == null) {
+ return;
+ }
+ if (forwarded.request === 'close') {
+ handleRef.current?.close();
+ } else {
+ handleRef.current?.open(forwarded.request);
+ }
+ }, [forwarded]);
+ const shared = {
+ isInline: isInlineElement,
+ ...view,
+ attachment,
+ label: options.label,
+ isDisabled: options.isDisabled,
+ presentation: options.presentation,
+ onOpenChange: handleOpenChange,
+ };
+ return options.items !== undefined ? (
+
+ ) : (
+
+ ) : null
+ }
+ />
+ );
+}
+
+/**
+ * Attaches a context menu to `element` (spec:AST-107 FR8). It opens on the
+ * element's context request, at `open(at)`'s point when given, and `destroy`
+ * removes every listener and node it added.
+ */
+export function createContextMenu(
+ element: HTMLElement,
+ initialOptions: CreateContextMenuOptions,
+): ContextMenuController {
+ const doc = element.ownerDocument;
+ let options = initialOptions;
+ let wrap: ((menu: ReactNode) => ReactNode) | null = null;
+ let view: ContextMenuViewExtras = {};
+ let forwarded: Forwarded | null = null;
+ let seq = 0;
+ let isOpen = false;
+ let isDestroyed = false;
+
+ // Not a child of the element: an event inside the menu never passes
+ // through the element on its way to the document.
+ const host = doc.createElement('div');
+ host.setAttribute(dataAttr('context-menu-host'), '');
+ // No box of its own: the menu is in the top layer, and an empty block
+ // beside an inline trigger would break its line.
+ host.style.display = 'contents';
+ // Each open first moves the container to where the element is now: the
+ // end of its dialog or popover, or of its shadow root or the body
+ // (containerParentFor). A shown menu stays put, since moving a node hides
+ // the popovers in it.
+ const placeHost = () => {
+ mirrorTheme(host, element);
+ // ContextMenu gives its menu a place beside its trigger.
+ const parent = view.containerParent ?? containerParentFor(element);
+ if (parent.lastElementChild !== host) {
+ parent.append(host);
+ }
+ };
+ placeHost();
+ const beforeOpen = () => {
+ if (!isOpen && !isDestroyed) {
+ placeHost();
+ }
+ };
+ // A React caller (ContextMenu) renders the menu in its own tree; a page
+ // without React gets a root of the menu's own.
+ const reactHost = reactHosts.get(element) ?? null;
+ reactHosts.delete(element);
+ const root: Root | null = reactHost == null ? createRoot(host) : null;
+
+ const onOpenChange = (next: boolean) => {
+ if (next === isOpen) {
+ return;
+ }
+ isOpen = next;
+ options.onOpenChange?.(next);
+ };
+
+ const render = () => {
+ if (isDestroyed) {
+ return;
+ }
+ const menu = (
+
+ );
+ const content = wrap != null ? wrap(menu) : menu;
+ if (reactHost != null) {
+ reactHost(createPortal(content, host));
+ } else {
+ root?.render(content);
+ }
+ };
+
+ const forward = (request: ContextMenuForwarded) => {
+ if (isDestroyed) {
+ return;
+ }
+ if (request !== 'close') {
+ beforeOpen();
+ }
+ seq += 1;
+ forwarded = {seq, request};
+ render();
+ };
+
+ // The element's context request, from the start, with UIKit's timeline
+ // where the touch model applies; the menu refines its hold once it renders
+ // (the theme's compact definition, and the haptic at the commit).
+ let requestConfig: Pick = {
+ hold: readPresentation(options.presentation, {
+ whenOmitted: 'touch',
+ view: doc.defaultView,
+ compact: DEFAULT_COMPACT_DEFINITION,
+ }).touchModes
+ ? CONTEXT_MENU_TOUCH_HOLD
+ : undefined,
+ };
+ const requests = attachContextMenuRequests(
+ element,
+ {isDisabled: options.isDisabled, ...requestConfig},
+ request => {
+ // A close comes from disabling the menu, inside a render's effects.
+ if (request === 'close') {
+ forward(request);
+ return;
+ }
+ // An open comes from a listener on the element, and commits in the
+ // request's own task, before the next input, as React commits a
+ // request it dispatches itself: inside a shadow root `window.event` is
+ // unset there, so React cannot tell it is a discrete input, and would
+ // commit the open in a later task, where a press outside in between
+ // would find no listener.
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the open must commit before the next input, inside a shadow root too
+ flushSync(() => forward(request));
+ },
+ );
+ function configureRequests(
+ config: Pick,
+ ) {
+ requestConfig = config;
+ requests.update({isDisabled: options.isDisabled, ...requestConfig});
+ }
+ render();
+
+ const controller: ContextMenuController = {
+ open(at) {
+ forward({kind: 'open', point: at ?? null});
+ },
+ close() {
+ forward('close');
+ },
+ destroy() {
+ teardown(false);
+ },
+ };
+ /** `destroy`; from React's commit, the root renders nothing instead. */
+ function teardown(isInReact: boolean) {
+ if (isDestroyed) {
+ return;
+ }
+ const hadFocus = host.contains(doc.activeElement);
+ isDestroyed = true;
+ requests.destroy();
+ if (reactHost != null) {
+ // The menu is a portal in the caller's tree, which it leaves now.
+ reactHost(null);
+ } else if (isInReact) {
+ root?.render(null);
+ } else {
+ root?.unmount();
+ }
+ host.remove();
+ if (isOpen) {
+ isOpen = false;
+ options.onOpenChange?.(false);
+ }
+ if (hadFocus && element.isConnected) {
+ element.focus();
+ }
+ }
+ wrapperAccess.set(controller, {
+ update(nextOptions) {
+ // The same options render nothing new (a React caller passes them on
+ // every render of its own).
+ if (isShallowEqual(options, nextOptions)) {
+ return;
+ }
+ options = nextOptions;
+ requests.update({isDisabled: options.isDisabled, ...requestConfig});
+ render();
+ },
+ view(nextView) {
+ if (isShallowEqual(view, nextView)) {
+ return;
+ }
+ view = nextView;
+ if (!isOpen) {
+ placeHost();
+ }
+ render();
+ },
+ bridge(nextWrap) {
+ if (nextWrap === wrap) {
+ return;
+ }
+ wrap = nextWrap;
+ render();
+ },
+ destroyFromReact() {
+ teardown(true);
+ },
+ });
+ return controller;
+}
diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.ts
index f0f5bc73ff8d1..4140e38063f6a 100644
--- a/packages/core/src/ContextMenu/index.ts
+++ b/packages/core/src/ContextMenu/index.ts
@@ -3,7 +3,8 @@
/**
* @file index.ts
- * @output Exports ContextMenu, ContextMenuItem and related types
+ * @output Exports ContextMenu, ContextMenuItem and related types, and the
+ * headless createContextMenu and useContextMenu (spec:AST-107 FR8)
* @position Public API entry point
*/
@@ -16,6 +17,18 @@ export {
type ContextMenuOption,
} from './ContextMenu';
export type {AdaptivePresentation as MenuPresentation} from '../hooks/useAdaptivePresentation';
+export {
+ createContextMenu,
+ type ContextMenuContentRenderer,
+ type ContextMenuController,
+ type ContextMenuPoint,
+ type CreateContextMenuOptions,
+} from './createContextMenu';
+export {
+ useContextMenu,
+ type UseContextMenuOptions,
+ type UseContextMenuResult,
+} from './useContextMenu';
export {
DropdownMenuItem as ContextMenuItem,
diff --git a/packages/core/src/ContextMenu/useContextMenu.doc.mjs b/packages/core/src/ContextMenu/useContextMenu.doc.mjs
new file mode 100644
index 0000000000000..bab30aebb5bff
--- /dev/null
+++ b/packages/core/src/ContextMenu/useContextMenu.doc.mjs
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useContextMenu',
+ displayName: 'useContextMenu',
+ group: 'Utilities',
+ keywords: [
+ 'context menu',
+ 'right click',
+ 'long press',
+ 'shift f10',
+ 'row actions',
+ 'headless',
+ 'hook',
+ ],
+ params: [
+ {
+ name: 'ref',
+ type: 'RefObject',
+ description:
+ 'A ref to the element that owns the menu, such as a list row. Its markup is untouched: the menu renders outside it.',
+ required: true,
+ },
+ {
+ name: 'options.items',
+ type: 'ContextMenuOption[]',
+ description:
+ "The menu's rows, as ContextMenu's `items`. Give `items` or `menuContent`.",
+ },
+ {
+ name: 'options.menuContent',
+ type: 'ReactNode',
+ description:
+ "Custom menu content as JSX, as ContextMenu's `menuContent`: ContextMenuItem and its siblings work inside it. It renders inside the menu with Astryx's own providers; an app's own contexts (a router, a store, a form) do not reach it.",
+ },
+ {
+ name: 'options.label',
+ type: 'string',
+ description: 'Names the menu for assistive technology.',
+ },
+ {
+ name: 'options.isDisabled',
+ type: 'boolean',
+ description:
+ 'Keeps the menu from opening: the element then makes no request, and the browser keeps its own menu.',
+ },
+ {
+ name: 'options.onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description:
+ 'Called with true when the menu opens and false when it closes.',
+ },
+ {
+ name: 'options.presentation',
+ type: "'popover' | 'bottom-sheet' | 'adaptive'",
+ description:
+ 'Where the menu appears, as ContextMenu\u2019s `presentation`.',
+ },
+ ],
+ returns: [
+ {
+ name: 'open',
+ type: '(at?: {x: number, y: number}) => void',
+ description:
+ "Opens the menu at `at`, in client coordinates, or at the element's bottom-left corner without it.",
+ },
+ {
+ name: 'close',
+ type: '() => void',
+ description: 'Closes the menu.',
+ },
+ ],
+ usage: {
+ description:
+ 'The React wrapper over `createContextMenu`: it attaches the same menu to the element its ref points at, and unmounting removes it. Use it to give an element you already render, such as a list row, a context menu without wrapping it. When a wrapper element is fine, use the ContextMenu component.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Read what `menuContent` needs from your app (a router, a store, a form) in the component, and pass the values in: the menu renders where those contexts do not reach. Use the ContextMenu component when its content must read them itself.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep every action reachable another way too, such as a MoreMenu on the row.',
+ },
+ {
+ guidance: false,
+ description: 'Attach two menus to one element.',
+ },
+ ],
+ accessibility: [
+ {
+ name: 'Keyboard and assistive technology',
+ category: 'Keyboard',
+ description:
+ 'As createContextMenu: Shift+F10 or the context-menu key opens the menu on a focused element, focus starts on the first enabled row, the arrow keys, Home, End and typing move between rows, Escape closes it, and focus returns to the element.',
+ },
+ {
+ name: 'Reduce Motion',
+ category: 'Content',
+ criterion: '2.3.3 Animation from Interactions',
+ description: 'The menu appears as ContextMenu\u2019s does.',
+ },
+ ],
+ },
+ relatedComponents: ['ContextMenu', 'MoreMenu'],
+ relatedHooks: ['createContextMenu'],
+ importPath: '@astryxdesign/core/ContextMenu',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ "React wrapper over createContextMenu: ContextMenu's menu on an element you render, without a wrapper.",
+ paramDescriptions: {
+ ref: 'The element that owns the menu.',
+ 'options.items': "ContextMenu's rows. Give items or menuContent.",
+ 'options.menuContent':
+ "Custom content as JSX; an app's own contexts do not reach it.",
+ 'options.label': 'Names the menu.',
+ 'options.isDisabled': 'Keeps it from opening.',
+ 'options.onOpenChange': '(isOpen) => void.',
+ 'options.presentation': "As ContextMenu's presentation.",
+ },
+ returnDescriptions: {
+ open: '(at?) => void.',
+ close: '() => void.',
+ },
+ usage: {
+ description:
+ 'Attaches the same menu as createContextMenu; unmounting removes it.',
+ bestPractices: [
+ {guidance: true, description: 'Keep each action reachable another way.'},
+ {guidance: false, description: 'Attach two menus to one element.'},
+ ],
+ },
+};
diff --git a/packages/core/src/ContextMenu/useContextMenu.test.tsx b/packages/core/src/ContextMenu/useContextMenu.test.tsx
new file mode 100644
index 0000000000000..5b9588380a9d1
--- /dev/null
+++ b/packages/core/src/ContextMenu/useContextMenu.test.tsx
@@ -0,0 +1,315 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useContextMenu.test.tsx
+ * @input vitest (jsdom), Testing Library, useContextMenu in a component
+ * @output Checks the hook over createContextMenu (spec:AST-107 FR8, FR6): it
+ * attaches to the ref'd element through the public factory, handing it a
+ * `render` for a ReactNode `menuContent` (with the caller's Core providers,
+ * and rows that keep the menu's behavior) or `items`, opens and closes from
+ * what it returns, follows `isDisabled` and `presentation`, and unmounting
+ * removes it all
+ * @position Testing for useContextMenu.tsx
+ */
+
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {use, useRef, useState} from 'react';
+import {createPortal} from 'react-dom';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';
+import {LayerContext} from '../Layer/LayerContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {dataAttr} from '../naming';
+import {createContextMenu} from './createContextMenu';
+import {useContextMenu, type UseContextMenuOptions} from './useContextMenu';
+
+// The real factory, watched: the hook must go through it.
+vi.mock('./createContextMenu', async importOriginal => {
+ const actual = await importOriginal();
+ return {...actual, createContextMenu: vi.fn(actual.createContextMenu)};
+});
+
+/** The options the public factory takes (spec:AST-107 FR8). */
+const FACTORY_OPTIONS = new Set([
+ 'items',
+ 'render',
+ 'label',
+ 'isDisabled',
+ 'onOpenChange',
+ 'presentation',
+]);
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+let controls: {open: (at?: {x: number; y: number}) => void; close: () => void};
+
+function Row(props: UseContextMenuOptions) {
+ const ref = useRef(null);
+ controls = useContextMenu(ref, props);
+ return (
+
+ );
+}
+
+function rightClick(target: Element): MouseEvent {
+ const event = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: 30,
+ clientY: 40,
+ button: 2,
+ });
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ return event;
+}
+
+const menu = () => document.querySelector('[role="menu"]');
+/** Whether the menu's popover is showing (the popover mocks above). */
+const isOpen = () =>
+ menu()?.closest('[popover]')?.hasAttribute('popover-open') === true;
+
+/** A layer inside the menu's content, portaled outside the menu's DOM. */
+function NestedDismissibleLayer({onDismiss}: {onDismiss: () => void}) {
+ const [isLayerOpen, setIsLayerOpen] = useState(true);
+ const containerRef = useRef(null);
+ useLayerDismissal({
+ isActive: isLayerOpen,
+ onDismiss: () => {
+ setIsLayerOpen(false);
+ onDismiss();
+ },
+ getContainer: () => containerRef.current,
+ });
+ // Only the layer depth inside the menu can rank it above the menu.
+ return isLayerOpen
+ ? createPortal(
+
+ Nested layer
+ ,
+ document.body,
+ )
+ : null;
+}
+
+function Probe() {
+ return use(LayerContext) != null ? : null;
+}
+
+describe('useContextMenu', () => {
+ it('opens on a right click on its element, and a choice runs and closes the menu', async () => {
+ const onArchive = vi.fn();
+ render(
);
+ rightClick(screen.getByText('Inbox'));
+ await userEvent
+ .setup()
+ .click(screen.getByRole('menuitem', {name: 'Archive', hidden: true}));
+ expect(onArchive).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(isOpen()).toBe(false));
+ });
+
+ it('keeps the list valid: the menu is not inserted into it', () => {
+ render(
);
+ rightClick(screen.getByText('Inbox'));
+ const list = document.querySelector('ul');
+ expect(
+ Array.from(list?.children ?? []).map(child => child.localName),
+ ).toEqual(['li']);
+ expect(list?.querySelector('[role="menu"]')).toBeNull();
+ });
+
+ it("renders a ReactNode menuContent with the caller's Core providers", () => {
+ render(
+
+
+ Custom
+
+ }
+ />
+
,
+ );
+ rightClick(screen.getByText('Inbox'));
+ expect(
+ screen.getByRole('menuitem', {name: 'Custom', hidden: true}),
+ ).not.toBeNull();
+ expect(screen.queryByTestId('bridged')).not.toBeNull();
+ });
+
+ it('hands the public createContextMenu a `render` for menuContent, and nothing else (spec:AST-107 FR8, FR6)', () => {
+ vi.mocked(createContextMenu).mockClear();
+ render(
+
+ Custom
+
+ }
+ />,
+ );
+ expect(vi.mocked(createContextMenu)).toHaveBeenCalledTimes(1);
+ const [element, options] = vi.mocked(createContextMenu).mock.calls[0] ?? [];
+ expect(element).toBe(screen.getByText('Inbox'));
+ expect(
+ Object.keys(options ?? {}).filter(key => !FACTORY_OPTIONS.has(key)),
+ ).toEqual([]);
+ expect(typeof options?.render).toBe('function');
+ expect(options?.items).toBeUndefined();
+ expect(options?.label).toBe('Inbox actions');
+ });
+
+ it('passes `presentation` to the factory, as ContextMenu does', () => {
+ vi.mocked(createContextMenu).mockClear();
+ render(
);
+ expect(vi.mocked(createContextMenu).mock.calls[0]?.[1]).toMatchObject({
+ presentation: 'popover',
+ });
+ });
+
+ it("a DropdownMenuItem in menuContent keeps the menu's behavior: choosing it closes the menu", async () => {
+ const onArchive = vi.fn();
+ render(
+
}
+ />,
+ );
+ rightClick(screen.getByText('Inbox'));
+ expect(isOpen()).toBe(true);
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByRole('menuitem', {name: 'Archive', hidden: true}),
+ ),
+ );
+ // A key chooses the row: jsdom's pointer click lands on a row the close
+ // has already taken out of the page, which no browser does (the browser
+ // check is the interaction spec's).
+ await userEvent.setup().keyboard('{Enter}');
+ expect(onArchive).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(isOpen()).toBe(false));
+ });
+
+ it('a layer inside menuContent takes Escape before the menu, as in ContextMenu', () => {
+ const onNestedDismiss = vi.fn();
+ render(
+
}
+ />,
+ );
+ rightClick(screen.getByText('Inbox'));
+ expect(isOpen()).toBe(true);
+ const nested = screen.getByRole('button', {
+ name: 'Nested layer',
+ hidden: true,
+ });
+ nested.focus();
+ fireEvent.keyDown(nested, {key: 'Escape'});
+ expect(onNestedDismiss).toHaveBeenCalledOnce();
+ expect(isOpen()).toBe(true);
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(isOpen()).toBe(false);
+ });
+
+ it('open() and close() drive the menu', () => {
+ const onOpenChange = vi.fn();
+ render(
);
+ act(() => {
+ controls.open({x: 10, y: 10});
+ });
+ expect(isOpen()).toBe(true);
+ act(() => {
+ controls.close();
+ });
+ expect(isOpen()).toBe(false);
+ expect(onOpenChange.mock.calls).toEqual([[true], [false]]);
+ });
+
+ it('follows isDisabled: the browser keeps its menu while disabled', () => {
+ const view = render(
);
+ expect(rightClick(screen.getByText('Inbox')).defaultPrevented).toBe(false);
+ expect(isOpen()).toBe(false);
+ view.rerender(
);
+ expect(rightClick(screen.getByText('Inbox')).defaultPrevented).toBe(true);
+ expect(isOpen()).toBe(true);
+ });
+
+ it('unmounting removes the menu and everything it added', () => {
+ const view = render(
);
+ const element = screen.getByText('Inbox');
+ rightClick(element);
+ view.unmount();
+ expect(isOpen()).toBe(false);
+ expect(
+ document.querySelector(`[${dataAttr('context-menu-host')}]`),
+ ).toBeNull();
+ expect(rightClick(element).defaultPrevented).toBe(false);
+ });
+});
+
+describe('useContextMenu: its element and its React roots', () => {
+ it('attaches to the element its ref points at now, when that element changes', () => {
+ function Switching({which}: {which: 'a' | 'b'}) {
+ const ref = useRef(null);
+ useContextMenu(ref, {items: [{label: 'Rename'}], label: 'Row actions'});
+ return (
+
+ {which === 'a' ? (
+
+ A
+
+ ) : (
+
+ B
+
+ )}
+
+ );
+ }
+ const view = render( );
+ view.rerender( );
+ const request = rightClick(screen.getByTestId('row-b'));
+ expect(request.defaultPrevented).toBe(true);
+ expect(isOpen()).toBe(true);
+ });
+
+ it('unmounting leaves React no root to unmount during its own commit, so it logs no error', () => {
+ const errors = vi.spyOn(console, 'error');
+ try {
+ const view = render(
+
}
+ />,
+ );
+ rightClick(screen.getByText('Inbox'));
+ expect(isOpen()).toBe(true);
+ view.unmount();
+ const messages = errors.mock.calls.map(call => String(call[0]));
+ expect(
+ messages.filter(message =>
+ message.includes('synchronously unmount a root'),
+ ),
+ ).toEqual([]);
+ } finally {
+ errors.mockRestore();
+ }
+ });
+});
diff --git a/packages/core/src/ContextMenu/useContextMenu.tsx b/packages/core/src/ContextMenu/useContextMenu.tsx
new file mode 100644
index 0000000000000..33ae785c020a5
--- /dev/null
+++ b/packages/core/src/ContextMenu/useContextMenu.tsx
@@ -0,0 +1,224 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useContextMenu.tsx
+ * @input A ref to the element, and createContextMenu's options with a
+ * ReactNode `menuContent`
+ * @output useContextMenu: the React wrapper over createContextMenu,
+ * returning `{open, close}` (spec:AST-107 FR8, FR6)
+ * @position Public hook over the public factory: it hands createContextMenu
+ * a `render` that portals `menuContent` into the menu's container, carries
+ * the caller's Core providers (theme, layer, link, i18n) into the menu, and
+ * passes later options through updateContextMenu. `menuContent` stays
+ * rendered, in a root the hook owns, into a host the menu's container
+ * adopts (contextMenuRows.tsx), so its first enabled row is there when
+ * focus starts; its rows read the menu's own row context, open state,
+ * layer and layer depth
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ type ReactNode,
+ type RefObject,
+} from 'react';
+import {createPortal} from 'react-dom';
+import {createRoot} from 'react-dom/client';
+import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';
+import type {ContextMenuOption} from './ContextMenu';
+import {
+ createMenuRowsSlot,
+ MenuRows,
+ useCoreBridge,
+ type CoreBridge,
+} from './contextMenuRows';
+import {
+ bridgeContextMenu,
+ destroyContextMenuFromReact,
+ createContextMenu,
+ updateContextMenu,
+ type ContextMenuController,
+ type ContextMenuPoint,
+ type CreateContextMenuOptions,
+} from './createContextMenu';
+
+interface UseContextMenuSharedOptions {
+ /** Names the menu for assistive technology. */
+ label?: string;
+ /** While true, the element makes no context request and keeps the browser's own menu. */
+ isDisabled?: boolean;
+ /** Called with true when the menu opens and false when it closes. */
+ onOpenChange?: (isOpen: boolean) => void;
+ /** Where the menu appears, as ContextMenu's `presentation`. */
+ presentation?: AdaptivePresentation;
+}
+
+export type UseContextMenuOptions = UseContextMenuSharedOptions &
+ (
+ | {items: ReadonlyArray; menuContent?: undefined}
+ | {items?: undefined; menuContent: ReactNode}
+ );
+
+/** What useContextMenu returns. */
+export interface UseContextMenuResult {
+ /** Opens the menu at `at`, client coordinates; at the element without it. */
+ open: (at?: ContextMenuPoint) => void;
+ /** Closes the menu. */
+ close: () => void;
+}
+
+/** `menuContent`, kept rendered in a root the hook owns, into its slot. */
+interface MenuContentPortal {
+ /** The factory's `render`: the container adopts the slot's host. */
+ readonly render: (container: HTMLElement) => () => void;
+ /** Renders `content` with the caller's providers. */
+ draw(content: ReactNode, wrap: CoreBridge): void;
+ unmount(): void;
+}
+
+function createMenuContentPortal(doc: Document): MenuContentPortal {
+ const slot = createMenuRowsSlot(doc);
+ const root = createRoot(doc.createElement('div'));
+ return {
+ render: slot.render,
+ draw(content, wrap) {
+ root.render(
+ createPortal(
+ wrap({content} ),
+ slot.host,
+ ),
+ );
+ },
+ unmount() {
+ slot.host.remove();
+ // Called from an effect's cleanup: React cannot unmount a root while
+ // it commits another, so this one renders nothing instead, an update
+ // React takes in its own time, and is dropped with its node.
+ root.render(null);
+ },
+ };
+}
+
+function factoryOptions(
+ options: UseContextMenuOptions,
+ onOpenChange: (isOpen: boolean) => void,
+ portal: MenuContentPortal | null,
+): CreateContextMenuOptions {
+ const shared = {
+ label: options.label,
+ isDisabled: options.isDisabled,
+ onOpenChange,
+ presentation: options.presentation,
+ };
+ return portal != null
+ ? {...shared, render: portal.render}
+ : {...shared, items: options.items ?? []};
+}
+
+/** The element the hook's menu is attached to, and how to detach it. */
+interface Attached {
+ element: HTMLElement;
+ hasContent: boolean;
+ detach: () => void;
+}
+
+/**
+ * Attaches a context menu to the element `ref` points at (spec:AST-107 FR8):
+ * it opens on that element's context request, and unmounting removes it.
+ * When the ref moves to another element, the menu moves with it.
+ */
+export function useContextMenu(
+ ref: RefObject,
+ options: UseContextMenuOptions,
+): UseContextMenuResult {
+ const wrap = useCoreBridge();
+ const hasContent = options.menuContent !== undefined;
+ const latestRef = useRef({options, wrap});
+ const controllerRef = useRef(null);
+ const portalRef = useRef(null);
+ const attachedRef = useRef(null);
+ const handleOpenChange = useCallback((isOpen: boolean) => {
+ latestRef.current.options.onOpenChange?.(isOpen);
+ }, []);
+
+ useLayoutEffect(() => {
+ latestRef.current = {options, wrap};
+ const controller = controllerRef.current;
+ if (controller == null) {
+ return;
+ }
+ const portal = portalRef.current;
+ updateContextMenu(
+ controller,
+ factoryOptions(options, handleOpenChange, portal),
+ );
+ bridgeContextMenu(controller, wrap);
+ if (portal != null) {
+ portal.draw(options.menuContent, wrap);
+ }
+ });
+
+ // Every commit checks the element the ref points at now: a ref moved to
+ // another element moves the menu with it.
+ useEffect(() => {
+ const element = ref.current;
+ const attached = attachedRef.current;
+ if (
+ attached != null &&
+ attached.element === element &&
+ attached.hasContent === hasContent
+ ) {
+ return;
+ }
+ attached?.detach();
+ attachedRef.current = null;
+ if (element == null) {
+ return;
+ }
+ const latest = latestRef.current;
+ const portal = hasContent
+ ? createMenuContentPortal(element.ownerDocument)
+ : null;
+ portal?.draw(latest.options.menuContent, latest.wrap);
+ const controller = createContextMenu(
+ element,
+ factoryOptions(latest.options, handleOpenChange, portal),
+ );
+ bridgeContextMenu(controller, latest.wrap);
+ controllerRef.current = controller;
+ portalRef.current = portal;
+ attachedRef.current = {
+ element,
+ hasContent,
+ detach: () => {
+ destroyContextMenuFromReact(controller);
+ portal?.unmount();
+ if (controllerRef.current === controller) {
+ controllerRef.current = null;
+ portalRef.current = null;
+ }
+ },
+ };
+ });
+
+ useEffect(
+ () => () => {
+ attachedRef.current?.detach();
+ attachedRef.current = null;
+ },
+ [],
+ );
+
+ return useMemo(
+ () => ({
+ open: (at?: ContextMenuPoint) => controllerRef.current?.open(at),
+ close: () => controllerRef.current?.close(),
+ }),
+ [],
+ );
+}
diff --git a/packages/core/src/Layer/__tests__/inputHold.fixture.ts b/packages/core/src/Layer/__tests__/inputHold.fixture.ts
new file mode 100644
index 0000000000000..84cfc1b93f198
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/inputHold.fixture.ts
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputHold.fixture.ts
+ * @input Nothing: bundled by esbuild and injected into a blank page
+ * @output A page whose whole area is a button (`#under`), a modal dialog
+ * (`#dialog`: text, an action, and a gesture-host tap recognizer on the
+ * dialog itself, an ancestor of the hold's shield), a light-dismissing
+ * popover (`#pop`) and a full-viewport layer (`#lift`) whose content and
+ * tint take the hits while a test may make its root take none, plus
+ * `window.__hold`: open a layer, hold and
+ * release it, read what an element at a point is and what lies past a
+ * hold's shield there, and a log of every
+ * click, tap recognition and popover toggle
+ * @position Browser fixture of inputHold.interaction.browser.spec.ts;
+ * test-only
+ */
+
+import {getGestureHost} from '../../gestures/GestureHost';
+import {TapGestureRecognizer} from '../../gestures/TapGestureRecognizer';
+import {holdInput, isInputShield, type InputHoldScope} from '../inputHold';
+
+type LayerId = 'dialog' | 'pop' | 'lift';
+
+interface HoldLog {
+ clicks: string[];
+ taps: number;
+ toggles: string[];
+}
+
+declare global {
+ interface Window {
+ __hold: {
+ log: HoldLog;
+ open: (id: LayerId) => void;
+ hold: (id: LayerId, scope: InputHoldScope) => void;
+ release: () => void;
+ hitAt: (x: number, y: number) => string;
+ hitPast: (x: number, y: number) => string;
+ };
+ }
+}
+
+document.body.style.margin = '0';
+document.body.innerHTML = `
+ page
+
+ Delete this item?
+ Delete
+
+
+ Copy
+
+ `;
+
+function element(id: string): HTMLElement {
+ const found = document.getElementById(id);
+ if (found == null) {
+ throw new Error(`missing #${id}`);
+ }
+ return found;
+}
+
+const log: HoldLog = {clicks: [], taps: 0, toggles: []};
+
+document.addEventListener(
+ 'click',
+ event => {
+ const target = event.target;
+ if (target instanceof Element) {
+ const button = target.closest('button');
+ if (button != null) {
+ log.clicks.push(button.id);
+ }
+ }
+ },
+ true,
+);
+element('pop').addEventListener('toggle', event => {
+ log.toggles.push(`pop:${event.newState}`);
+});
+
+// A recognizer on the dialog itself sees every touch inside it, the hold's
+// shield included: only the gesture host's touch gate keeps it away.
+const tap = new TapGestureRecognizer({name: 'dialogTap'});
+tap.addTransitionListener((_current, _from, to) => {
+ if (to === 'ended') {
+ log.taps += 1;
+ }
+});
+getGestureHost(document).attach(element('dialog'), tap);
+
+let release: (() => void) | null = null;
+
+window.__hold = {
+ log,
+ open(id) {
+ if (id === 'dialog') {
+ (element('dialog') as HTMLDialogElement).showModal();
+ } else if (id === 'pop') {
+ element('pop').showPopover();
+ } else {
+ element('lift').style.display = 'block';
+ }
+ },
+ hold(id, scope) {
+ release = holdInput(element(id), {
+ until: new Promise(() => {}),
+ scope,
+ });
+ },
+ release() {
+ release?.();
+ release = null;
+ },
+ hitAt(x, y) {
+ return describe(document.elementFromPoint(x, y));
+ },
+ hitPast(x, y) {
+ return describe(
+ document.elementsFromPoint(x, y).find(el => !isInputShield(el)) ?? null,
+ );
+ },
+};
+
+function describe(hit: Element | null): string {
+ if (hit == null) {
+ return 'nothing';
+ }
+ if (isInputShield(hit)) {
+ return `shield:${hit.parentElement?.id ?? ''}`;
+ }
+ return hit.id !== '' ? hit.id : hit.tagName.toLowerCase();
+}
diff --git a/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..c31bc8fe820a5
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/inputHold.interaction.browser.spec.ts
@@ -0,0 +1,348 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputHold.interaction.browser.spec.ts
+ * @input The input-hold fixture bundled with esbuild, a phone-sized
+ * touch screen, and real engine touch input (touchDriver)
+ * @output Browser proof of what the unit tests cannot see: the hold's shield
+ * is the hit target over the whole viewport, above a modal dialog in the
+ * top layer; a tap during a hold reaches no click and no recognizer on the
+ * layer (the gesture host's touch gate) and leaves a light-dismissing
+ * popover open; a layer root that takes no hits itself (pointer-events:
+ * none, or visibility: hidden, its content opting back in) is held all the
+ * same; keys still act during a presentation's input hold; a dismissal's
+ * hold makes the content inert and moves focus out of it, so no key acts
+ * on it either (a focused button that turns inert still takes Enter and
+ * Space in both engines); each release gives input back; a hit test
+ * that skips shields (isInputShield) finds what lies beneath, and
+ * a layer above the held one still wins; a one-finger
+ * pan on the shield scrolls nothing while a pinch on it still zooms the
+ * page (spec:AST-094 FR10, FR18, FR35; Chromium, which pinch-zooms from
+ * injected touches)
+ * @position Browser tests of packages/core/src/Layer/inputHold.ts, run
+ * by the interaction project (`pnpm test:interaction inputHold`)
+ */
+
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {build} from 'esbuild';
+import {expect, test, type Page} from '@playwright/test';
+import {
+ drag,
+ pinch,
+ touchDriver,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+type Point = {x: number; y: number};
+type Scope = 'viewport' | 'layer';
+type LayerId = 'dialog' | 'pop' | 'lift';
+
+interface HoldApi {
+ log: {clicks: string[]; taps: number; toggles: string[]};
+ open: (id: LayerId) => void;
+ hold: (id: LayerId, scope: Scope) => void;
+ release: () => void;
+ hitAt: (x: number, y: number) => string;
+ hitPast: (x: number, y: number) => string;
+}
+
+let bundle = '';
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [
+ path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ 'inputHold.fixture.ts',
+ ),
+ ],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ platform: 'browser',
+ target: 'es2022',
+ });
+ bundle = result.outputFiles[0].text;
+});
+
+async function load(page: Page): Promise {
+ // A real navigation first: touch emulation exposes the Touch Events API to
+ // documents it creates.
+ await page.goto('about:blank');
+ await page.setContent(
+ ' ',
+ );
+ await page.addScriptTag({content: bundle});
+ return touchDriver(page);
+}
+
+type HoldWindow = {__hold: HoldApi};
+
+const open = async (page: Page, id: LayerId) =>
+ page.evaluate(layer => {
+ (window as unknown as HoldWindow).__hold.open(layer);
+ }, id);
+const hold = async (page: Page, id: LayerId, scope: Scope) =>
+ page.evaluate(
+ ([layer, how]) => {
+ (window as unknown as HoldWindow).__hold.hold(layer, how);
+ },
+ [id, scope] as const,
+ );
+const release = async (page: Page) =>
+ page.evaluate(() => {
+ (window as unknown as HoldWindow).__hold.release();
+ });
+const hitAt = async (page: Page, point: Point) =>
+ page.evaluate(
+ at => (window as unknown as HoldWindow).__hold.hitAt(at.x, at.y),
+ point,
+ );
+const hitPast = async (page: Page, point: Point) =>
+ page.evaluate(
+ at => (window as unknown as HoldWindow).__hold.hitPast(at.x, at.y),
+ point,
+ );
+const readLog = async (page: Page) =>
+ page.evaluate(() => (window as unknown as HoldWindow).__hold.log);
+
+async function centre(page: Page, id: string): Promise {
+ const box = await page.locator(`#${id}`).boundingBox();
+ if (box == null) {
+ throw new Error(`#${id} has no box`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+// A tap's click (or its recognition) lands within a few frames.
+const settle = async (page: Page) => page.waitForTimeout(250);
+
+test("during a presentation's input hold on a modal dialog, a tap on it or beside it reaches nothing, keys still act, and the release gives touch back", async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ const message = await centre(page, 'message');
+ const beside = {x: 12, y: 12};
+ await hold(page, 'dialog', 'viewport');
+ // The shield is what a touch hits, on the dialog and over its backdrop.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ expect(await hitAt(page, beside)).toBe('shield:dialog');
+ await driver.tap(action);
+ await driver.tap(message);
+ await settle(page);
+ // No click, and the recognizer on the dialog saw nothing: the gate.
+ expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []});
+ // Keys still act during a presentation's input hold.
+ await page.locator('#action').focus();
+ await page.keyboard.press('Enter');
+ await expect
+ .poll(async () => (await readLog(page)).clicks)
+ .toEqual(['action']);
+ await release(page);
+ expect(await hitAt(page, action)).toBe('action');
+ expect(await hitAt(page, beside)).toBe('dialog');
+ await driver.tap(message);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+});
+
+test('while a dismissal holds it, its content is inert, focus and keys leave it, and the shield still takes every tap; the release restores both', async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ const message = await centre(page, 'message');
+ // The dialog moved focus to its action when it opened.
+ expect(await page.evaluate(() => document.activeElement?.id ?? null)).toBe(
+ 'action',
+ );
+ await hold(page, 'dialog', 'layer');
+ // A key reaches nothing: the focused action left the inert content.
+ await page.keyboard.press('Enter');
+ await page.keyboard.press('Space');
+ await settle(page);
+ expect((await readLog(page)).clicks).toEqual([]);
+ // An inert subtree is no hit target: the shield, in the dialog, is.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ const state = async () =>
+ page.evaluate(() => {
+ const button = document.getElementById('action');
+ button?.focus();
+ return {
+ inert: button?.closest('[inert]') != null,
+ focused: document.activeElement === button,
+ };
+ });
+ expect(await state()).toEqual({inert: true, focused: false});
+ await driver.tap(action);
+ await driver.tap(message);
+ await settle(page);
+ expect(await readLog(page)).toEqual({clicks: [], taps: 0, toggles: []});
+ await release(page);
+ expect(await state()).toEqual({inert: false, focused: true});
+ expect(await hitAt(page, action)).toBe('action');
+ await driver.tap(message);
+ await expect.poll(async () => (await readLog(page)).taps).toBe(1);
+});
+
+test('a light-dismissing popover stays open when a hold takes a tap outside it; after the release the same tap dismisses it', async ({
+ page,
+}) => {
+ const driver = await load(page);
+ await open(page, 'pop');
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const outside = {x: viewport.width / 2, y: viewport.height - 40};
+ expect(await hitAt(page, outside)).toBe('under');
+ await hold(page, 'pop', 'viewport');
+ expect(await hitAt(page, outside)).toBe('shield:pop');
+ await driver.tap(outside);
+ await settle(page);
+ expect(
+ await page.evaluate(() =>
+ document.getElementById('pop')?.matches(':popover-open'),
+ ),
+ ).toBe(true);
+ expect(await readLog(page)).toEqual({
+ clicks: [],
+ taps: 0,
+ toggles: ['pop:open'],
+ });
+ await release(page);
+ await driver.tap(outside);
+ await expect
+ .poll(async () => (await readLog(page)).toggles)
+ .toEqual(['pop:open', 'pop:closed']);
+});
+
+test('a hit test that skips shields sees past a hold: under a held modal dialog’s shield, its own action', async ({
+ page,
+}) => {
+ await load(page);
+ await open(page, 'dialog');
+ const action = await centre(page, 'action');
+ await hold(page, 'dialog', 'viewport');
+ // The opening finger's press resolves its row past the shield.
+ expect(await hitAt(page, action)).toBe('shield:dialog');
+ expect(await hitPast(page, action)).toBe('action');
+ await release(page);
+ expect(await hitAt(page, action)).toBe('action');
+});
+
+test('a layer opened above a held one is what that hit test finds, and past the shield the held layer’s content', async ({
+ page,
+}) => {
+ await load(page);
+ await open(page, 'lift');
+ const liftAction = await centre(page, 'liftAction');
+ await hold(page, 'lift', 'viewport');
+ expect(await hitAt(page, liftAction)).toBe('shield:lift');
+ expect(await hitPast(page, liftAction)).toBe('liftAction');
+ await open(page, 'pop');
+ const popAction = await centre(page, 'popAction');
+ expect(await hitAt(page, popAction)).toBe('popAction');
+ expect(await hitPast(page, popAction)).toBe('popAction');
+});
+
+// A full-viewport layer whose root takes no hits itself and lets its tint
+// and content take them (ContextMenu's lift layer is pointer-events: none):
+// the shield, inside that root, must not inherit that.
+for (const rootStyle of ['pointer-events: none', 'visibility: hidden']) {
+ test(`a layer root with ${rootStyle} (its content opting back in) is held all the same: a tap reaches neither the content nor the page`, async ({
+ page,
+ }) => {
+ const driver = await load(page);
+ await page.evaluate(style => {
+ const lift = document.getElementById('lift');
+ if (lift != null) {
+ lift.style.cssText += `; ${style}`;
+ }
+ }, rootStyle);
+ await open(page, 'lift');
+ const action = await centre(page, 'liftAction');
+ const tint = {x: 12, y: 12};
+ // Unheld, the content and the tint take the hits.
+ expect(await hitAt(page, action)).toBe('liftAction');
+ expect(await hitAt(page, tint)).toBe('tint');
+ await hold(page, 'lift', 'layer');
+ expect(await hitAt(page, action)).toBe('shield:lift');
+ expect(await hitAt(page, tint)).toBe('shield:lift');
+ await driver.tap(action);
+ await driver.tap(tint);
+ await settle(page);
+ expect((await readLog(page)).clicks).toEqual([]);
+ await release(page);
+ expect(await hitAt(page, action)).toBe('liftAction');
+ });
+}
+
+// Page zoom stays the browser's while a layer is held (spec:AST-094 FR10,
+// FR18 and FR35; WCAG 1.4.4): the shield starts no pan, but a pinch on it
+// still zooms the page.
+for (const [id, scope] of [
+ ['pop', 'viewport'],
+ ['dialog', 'layer'],
+] as const) {
+ test(`while a ${scope === 'viewport' ? 'presentation' : 'dismissal'} holds ${id === 'pop' ? 'a popover' : 'a modal dialog'}, a one-finger pan scrolls nothing and a pinch still zooms the page; neither reaches the layer or the page`, async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName === 'webkit',
+ 'needs native scrolling and pinch-zoom from injected touches (Mobile Safari on the simulator)',
+ );
+ const driver = await load(page);
+ const viewport = page.viewportSize();
+ if (viewport == null) {
+ throw new Error('no viewport');
+ }
+ const middle = {x: viewport.width / 2, y: viewport.height / 2};
+ const panUp = drag(
+ {x: middle.x, y: middle.y + 150},
+ {x: middle.x, y: middle.y - 150},
+ // A rest before the lift: no fling outlives the pan.
+ {durationMs: 200, restMs: 150},
+ );
+ // A page that scrolls under the layer: unheld, the same pan scrolls it.
+ await page.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.style.height = '300vh';
+ document.body.append(spacer);
+ });
+ await driver.play(panUp);
+ await expect
+ .poll(async () => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(0);
+ await settle(page);
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await settle(page);
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await open(page, id);
+ await hold(page, id, scope);
+ expect(await hitAt(page, middle)).toBe(`shield:${id}`);
+ await driver.play(panUp);
+ await settle(page);
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await driver.play(
+ pinch({
+ center: middle,
+ fromDistance: 60,
+ toDistance: 220,
+ durationMs: 200,
+ }),
+ );
+ await expect
+ .poll(async () => page.evaluate(() => window.visualViewport?.scale ?? 1))
+ .toBeGreaterThan(1.2);
+ expect(await readLog(page)).toEqual({
+ clicks: [],
+ taps: 0,
+ toggles: id === 'pop' ? ['pop:open'] : [],
+ });
+ });
+}
diff --git a/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts
new file mode 100644
index 0000000000000..c6af8c473c385
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts
@@ -0,0 +1,189 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerExitCopy.interaction.browser.spec.ts
+ * @input The exit copy bundled with esbuild onto a blank fixture page: a
+ * popover layer inside a clipping, transformed panel, an entrance curve
+ * held halfway, and Chromium and WebKit
+ * @output Proof that the engine shows the copy where the layer was drawn:
+ * placed as the layer closes (from script and by the browser's own light
+ * dismiss), it is in the top layer as a manual popover with no `z-index`,
+ * uncut by the clipping panel, and its drawn box equals the layer's drawn
+ * box mid-entrance within half a px; a second copy for the same layer
+ * replaces the first while another layer's copy stays
+ * @position Browser proof for layerExitCopy.ts, run by `pnpm
+ * test:interaction`; jsdom has no layout and no top layer. The refusal
+ * path (Android Chromium 158 refuses a show during another popover's
+ * toggle) is proven on the Android gate emulator (pull request evidence):
+ * these engines do not refuse.
+ */
+
+import {fileURLToPath} from 'node:url';
+import {expect, test, type Page} from '@playwright/test';
+import {build} from 'esbuild';
+
+declare global {
+ interface Window {
+ ExitCopy: typeof import('../layerExitCopy');
+ }
+}
+
+let script = '';
+
+test.beforeAll(async () => {
+ const result = await build({
+ entryPoints: [
+ fileURLToPath(new URL('../layerExitCopy.ts', import.meta.url)),
+ ],
+ bundle: true,
+ write: false,
+ format: 'iife',
+ globalName: 'ExitCopy',
+ target: 'es2022',
+ });
+ script = result.outputFiles[0].text;
+});
+
+const ATTRIBUTE = 'data-exit-copy';
+
+// A real navigation (not setContent): the page keeps its own window. The
+// layer sits in a panel that clips and is transformed: a fixed box placed
+// there would be cut and moved; the top layer is neither.
+async function open(page: Page) {
+ const html = `
+
+
+`;
+ await page.route('http://exit-copy.test/', async route =>
+ route.fulfill({contentType: 'text/html', body: html}),
+ );
+ await page.goto('http://exit-copy.test/');
+}
+
+test('a copy placed as a layer closes mid-entrance is in the top layer, where the layer was drawn', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(
+ async ({attribute}) => {
+ const layer = document.getElementById('layer') as HTMLElement;
+ layer.showPopover();
+ // An entrance halfway through: drawn at 60 % about its top-left corner.
+ const entrance = layer.animate(
+ [
+ {scale: '0.2', transformOrigin: '0 0'},
+ {scale: '1', transformOrigin: '0 0'},
+ ],
+ {duration: 1000, fill: 'both'},
+ );
+ entrance.pause();
+ entrance.currentTime = 500;
+ const drawn = layer.getBoundingClientRect();
+ let copy: HTMLElement | null = null;
+ layer.addEventListener(
+ 'beforetoggle',
+ event => {
+ if ((event).newState === 'closed') {
+ copy = window.ExitCopy.placeLayerExitCopy(layer, attribute);
+ }
+ },
+ {once: true},
+ );
+ layer.hidePopover();
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ const placed = copy as HTMLElement | null;
+ if (placed == null) {
+ return null;
+ }
+ const rect = placed.getBoundingClientRect();
+ return {
+ drawn: [drawn.left, drawn.top, drawn.width, drawn.height],
+ copy: [rect.left, rect.top, rect.width, rect.height],
+ open: placed.matches(':popover-open'),
+ popover: placed.getAttribute('popover'),
+ zIndex: getComputedStyle(placed).zIndex,
+ layerOpen: layer.matches(':popover-open'),
+ };
+ },
+ {attribute: ATTRIBUTE},
+ );
+ expect(result).not.toBeNull();
+ expect(result!.layerOpen).toBe(false);
+ expect(result!.open).toBe(true);
+ expect(result!.popover).toBe('manual');
+ expect(result!.zIndex).toBe('auto');
+ // Mid-entrance the drawn box is not the layout box; the copy holds it.
+ expect(result!.drawn[2]).toBeLessThan(280);
+ result!.copy.forEach((value, index) => {
+ expect(Math.abs(value - result!.drawn[index])).toBeLessThanOrEqual(0.5);
+ });
+});
+
+test('the browser\u2019s own light dismiss gets the copy too, uncut by the clipping panel', async ({
+ page,
+}) => {
+ await open(page);
+ await page.evaluate(attribute => {
+ const layer = document.getElementById('layer') as HTMLElement;
+ layer.showPopover();
+ layer.addEventListener(
+ 'beforetoggle',
+ event => {
+ if ((event).newState === 'closed') {
+ window.ExitCopy.placeLayerExitCopy(layer, attribute);
+ }
+ },
+ {once: true},
+ );
+ }, ATTRIBUTE);
+ // A press outside: the browser closes the layer by itself.
+ await page.mouse.click(360, 700);
+ const result = await page.evaluate(attribute => {
+ const copy = document.querySelector(`[${attribute}]`);
+ if (copy == null) {
+ return null;
+ }
+ const rect = copy.getBoundingClientRect();
+ return {
+ open: copy.matches(':popover-open'),
+ rect: [rect.left, rect.top, rect.width, rect.height],
+ layerOpen: document.getElementById('layer')!.matches(':popover-open'),
+ };
+ }, ATTRIBUTE);
+ expect(result).not.toBeNull();
+ expect(result!.layerOpen).toBe(false);
+ expect(result!.open).toBe(true);
+ // Where the layer stood, at its full size: the 60 x 40 clipping panel and
+ // its 30 px transform neither cut nor moved it.
+ expect(result!.rect).toEqual([40, 120, 280, 200]);
+});
+
+test('a second copy for the same layer replaces the first; another layer\u2019s copy stays', async ({
+ page,
+}) => {
+ await open(page);
+ const result = await page.evaluate(attribute => {
+ const layer = document.getElementById('layer') as HTMLElement;
+ const other = document.getElementById('other') as HTMLElement;
+ layer.showPopover();
+ other.showPopover();
+ const otherCopy = window.ExitCopy.placeLayerExitCopy(other, attribute);
+ const first = window.ExitCopy.placeLayerExitCopy(layer, attribute);
+ const second = window.ExitCopy.placeLayerExitCopy(layer, attribute);
+ return {
+ first: first?.isConnected,
+ second: second?.isConnected && second.matches(':popover-open'),
+ other: otherCopy?.isConnected && otherCopy.matches(':popover-open'),
+ copies: document.querySelectorAll(`[${attribute}]`).length,
+ };
+ }, ATTRIBUTE);
+ expect(result).toEqual({first: false, second: true, other: true, copies: 2});
+});
diff --git a/packages/core/src/Layer/inputHold.test.tsx b/packages/core/src/Layer/inputHold.test.tsx
new file mode 100644
index 0000000000000..836f661c103c3
--- /dev/null
+++ b/packages/core/src/Layer/inputHold.test.tsx
@@ -0,0 +1,231 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {render} from '@testing-library/react';
+import {useRef} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {GestureHost} from '../gestures/GestureHost';
+import {
+ holdInput,
+ isInHeldLayer,
+ isInputShield,
+ useInputHold,
+} from './inputHold';
+
+function deferred() {
+ let resolve: () => void = () => {};
+ let reject: (error: unknown) => void = () => {};
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return {promise, resolve, reject};
+}
+
+/** A layer root with a child, in the document. */
+function mountLayer(): {layer: HTMLElement; child: HTMLElement} {
+ const layer = document.createElement('div');
+ const child = document.createElement('button');
+ layer.append(child);
+ document.body.append(layer);
+ return {layer, child};
+}
+
+const flush = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
+afterEach(() => {
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+});
+
+describe('holdInput', () => {
+ it('holds a presenting layer with a shield over the viewport until its end settles', async () => {
+ const {layer, child} = mountLayer();
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ const end = deferred();
+ holdInput(layer, {until: end.promise, scope: 'viewport'});
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield).not.toBe(child);
+ expect(shield.getAttribute('popover')).toBe('manual');
+ expect(shield.style.position).toBe('fixed');
+ // No pan, and a pinch still zooms the page (spec:AST-094 FR10).
+ expect(shield.style.touchAction).toBe('pinch-zoom');
+ // Its own hit-testing, whatever the layer root's (the browser proof holds
+ // a root that is pointer-events: none).
+ expect(shield.style.pointerEvents).toBe('auto');
+ expect(shield.style.visibility).toBe('visible');
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(isInHeldLayer(shield)).toBe(true);
+ expect(isInHeldLayer(outside)).toBe(false);
+ // Keys and assistive technology stay live while presenting.
+ expect(layer.hasAttribute('inert')).toBe(false);
+ end.resolve();
+ await flush();
+ expect(shield.isConnected).toBe(false);
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('swallows a press and a click on the shield before they reach the page, and leaves a touch its start so a pinch can still zoom', () => {
+ const {layer} = mountLayer();
+ holdInput(layer, {until: new Promise(() => {}), scope: 'viewport'});
+ const shield = layer.lastElementChild as HTMLElement;
+ const seen: string[] = [];
+ for (const type of ['pointerdown', 'click', 'touchstart']) {
+ document.addEventListener(type, () => seen.push(type));
+ }
+ const press = new Event('pointerdown', {bubbles: true, cancelable: true});
+ const click = new MouseEvent('click', {bubbles: true, cancelable: true});
+ const touch = new Event('touchstart', {bubbles: true, cancelable: true});
+ shield.dispatchEvent(press);
+ shield.dispatchEvent(click);
+ shield.dispatchEvent(touch);
+ expect(seen).toEqual([]);
+ expect(press.defaultPrevented).toBe(true);
+ expect(click.defaultPrevented).toBe(true);
+ // Cancelling a touch's start would cancel the page's pinch-zoom too.
+ expect(touch.defaultPrevented).toBe(false);
+ });
+
+ it("holds a dismissing layer: its content inert, the layer itself live under the shield, each element's inert given back", async () => {
+ const {layer, child} = mountLayer();
+ const already = document.createElement('div');
+ already.setAttribute('inert', '');
+ layer.append(already);
+ child.focus();
+ expect(document.activeElement).toBe(child);
+ const end = deferred();
+ holdInput(layer, {until: end.promise, scope: 'layer'});
+ // Focus leaves the content: a focused element that turns inert would
+ // keep its key activation.
+ expect(document.activeElement).not.toBe(child);
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(shield.getAttribute('popover')).toBe('manual');
+ // The layer stays live so the shield inside it catches every hit: an
+ // inert subtree is no hit target.
+ expect(layer.hasAttribute('inert')).toBe(false);
+ expect(shield.hasAttribute('inert')).toBe(false);
+ expect(child.hasAttribute('inert')).toBe(true);
+ expect(isInHeldLayer(child)).toBe(true);
+ end.reject(new Error('interrupted'));
+ await flush();
+ expect(child.hasAttribute('inert')).toBe(false);
+ expect(already.hasAttribute('inert')).toBe(true);
+ expect(shield.isConnected).toBe(false);
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('names a live hold’s shield, and only it, so a hit test can skip it', () => {
+ const {layer, child} = mountLayer();
+ const popover = document.createElement('div');
+ popover.setAttribute('popover', 'manual');
+ document.body.append(popover);
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ const shield = layer.lastElementChild as HTMLElement;
+ expect(isInputShield(shield)).toBe(true);
+ for (const other of [layer, child, popover, null]) {
+ expect(isInputShield(other)).toBe(false);
+ }
+ release();
+ expect(isInputShield(shield)).toBe(false);
+ });
+
+ it('sees slotted content as held: the flat tree, a slotted node to its slot', () => {
+ const host = document.createElement('div');
+ const slotted = document.createElement('button');
+ host.append(slotted);
+ document.body.append(host);
+ const root = host.attachShadow({mode: 'open'});
+ const layer = document.createElement('div');
+ layer.append(document.createElement('slot'));
+ root.append(layer);
+ expect(isInHeldLayer(slotted)).toBe(false);
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ expect(isInHeldLayer(slotted)).toBe(true);
+ release();
+ expect(isInHeldLayer(slotted)).toBe(false);
+ });
+
+ it('takes an animator handle, ending with its finished', async () => {
+ const {layer, child} = mountLayer();
+ const end = deferred();
+ holdInput(layer, {until: {finished: end.promise}, scope: 'layer'});
+ expect(isInHeldLayer(child)).toBe(true);
+ end.resolve();
+ await flush();
+ expect(isInHeldLayer(child)).toBe(false);
+ });
+
+ it('stacks holds on one layer, either scope, under one shield: it comes back when the last one ends', () => {
+ const {layer, child} = mountLayer();
+ const first = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ const second = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'layer',
+ });
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(1);
+ expect(child.hasAttribute('inert')).toBe(true);
+ first();
+ first();
+ expect(isInHeldLayer(child)).toBe(true);
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(1);
+ second();
+ expect(isInHeldLayer(child)).toBe(false);
+ expect(child.hasAttribute('inert')).toBe(false);
+ expect(layer.querySelectorAll('[popover]')).toHaveLength(0);
+ });
+
+ it("registers one touch gate per document, which answers whether a touch's target is held", () => {
+ const addTouchGate = vi.spyOn(GestureHost.prototype, 'addTouchGate');
+ const {layer, child} = mountLayer();
+ holdInput(layer, {until: new Promise(() => {}), scope: 'layer'});
+ const release = holdInput(layer, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ expect(addTouchGate.mock.calls.length).toBeLessThanOrEqual(1);
+ const registered =
+ addTouchGate.mock.calls[0]?.[0] ??
+ ((target: Node) => isInHeldLayer(target));
+ expect(registered(child)).toBe(true);
+ expect(registered(document.body)).toBe(false);
+ release();
+ });
+});
+
+describe('useInputHold', () => {
+ function Bar({isHeld}: {isHeld: boolean}) {
+ const ref = useRef(null);
+ useInputHold(ref, {isHeld, scope: 'layer'});
+ return (
+
+ Back
+
+ );
+ }
+
+ it('holds the layer while asked, and releases it when no longer asked or unmounted', () => {
+ const view = render( );
+ const bar = view.getByTestId('bar');
+ const back = view.getByRole('button', {name: 'Back', hidden: true});
+ expect(back.hasAttribute('inert')).toBe(true);
+ expect(isInHeldLayer(back)).toBe(true);
+ view.rerender( );
+ expect(back.hasAttribute('inert')).toBe(false);
+ view.rerender( );
+ expect(back.hasAttribute('inert')).toBe(true);
+ view.unmount();
+ expect(isInHeldLayer(bar)).toBe(false);
+ });
+});
diff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.ts
new file mode 100644
index 0000000000000..8dab031277803
--- /dev/null
+++ b/packages/core/src/Layer/inputHold.ts
@@ -0,0 +1,328 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file inputHold.ts
+ * @input A layer's root element, what ends the hold (a promise, or an
+ * animator handle's `finished`), and its scope; the gesture host's touch
+ * gates
+ * @output holdInput, useInputHold, isInHeldLayer and
+ * isInputShield: input held away from a layer while its
+ * presentation runs
+ * @position The Layer module's one input hold, for every component
+ * whose layer presents or dismisses under a finger
+ *
+ * UIKit delivers no touch while a presentation runs: until it completes, a
+ * tap reaches nothing, and a dismissal drops every input until it ends
+ * (measured on iOS 26.2 with UIAlertController: taps 400 ms into its
+ * presentation ignored, 450 ms in handled). A hold covers one layer root
+ * until what ends it settles:
+ *
+ * - `scope: 'viewport'` (a presentation): a touch, a pointer press or a
+ * click anywhere reaches nothing. A transparent shield inside the layer
+ * covers the viewport from the top layer, so a tap on it lands inside the
+ * layer (a light-dismissing layer stays open) and starts no pan (iOS
+ * drops that input too while it presents), while a pinch on it still
+ * zooms the page, which stays the browser's (spec:AST-094 FR10, FR18,
+ * FR35; WCAG 1.4.4); the gesture host holds
+ * the layer's touches away from every recognizer. Keys and assistive
+ * technology stay live, as on iOS.
+ * - `scope: 'layer'` (a dismissal, an inert bar): the same shield, and the
+ * layer's content is inert (no focus, key or assistive-technology
+ * activation; a focused element inside it is blurred, since one that turns
+ * inert keeps its key activation). The layer element itself stays live, so
+ * the shield inside
+ * it still catches every hit: an inert subtree is no hit target, and a tap
+ * on it would otherwise land on whatever lies beneath. A modal dialog
+ * still receives its own `cancel` (Escape): the caller ignores it while
+ * held.
+ *
+ * The shield sets its own `pointer-events` and `visibility`, so a layer root
+ * that takes no hits itself (its content or a backdrop child opts back in)
+ * is held all the same. A hit test that must see past held input (a press
+ * the finger that opened the layer continues, captured before the hold
+ * began) skips shields and nothing else: the first element of
+ * `elementsFromPoint` for which `isInputShield` is false, so an
+ * overlay really above the layer still wins. The shield is a manual
+ * popover, so its `toggle` events reach a document listener that logs
+ * every popover's: such a log keeps to its own popovers.
+ *
+ * One hold per layer: holds on a held layer stack, and the layer comes back
+ * when the last one ends (when what ends it settles, resolved or rejected;
+ * when its release runs; on unmount, for the hook). Nothing is written to
+ * the DOM but the shield and the content's `inert` attribute; the host
+ * learns through one touch gate per document that asks `isInHeldLayer`,
+ * walking the flat tree as it does (a slotted node to its slot, a shadow
+ * root to its host).
+ *
+ * SYNC: When modified, update inputHold.test.tsx,
+ * __tests__/inputHold.interaction.browser.spec.ts and the components
+ * that hold their layer (holdInput and useInputHold callers).
+ */
+
+import {useEffect, type RefObject} from 'react';
+import {getGestureHost} from '../gestures/GestureHost';
+import {parentAcrossShadow} from '../gestures/nativeScroll';
+
+/** What a hold covers: the whole viewport, or the layer alone. */
+export type InputHoldScope = 'viewport' | 'layer';
+
+/** What ends a hold: a promise, or an animator handle (its `finished`). */
+export type InputHoldEnd =
+ PromiseLike | {readonly finished: PromiseLike};
+
+export interface InputHoldOptions {
+ /** The hold ends when this settles. */
+ until: InputHoldEnd;
+ /** `'viewport'` while presenting, `'layer'` while dismissing. */
+ scope: InputHoldScope;
+}
+
+interface HeldLayer {
+ viewport: number;
+ layer: number;
+ shield: HTMLElement | null;
+ /** The content a dismissal made inert, and whether each was already. */
+ inertContent: Map | null;
+}
+
+const held = new WeakMap();
+const gatedDocuments = new WeakSet();
+const liveShields = new WeakSet();
+
+/**
+ * Whether `node` is the shield of a live hold. A hit test that must see past
+ * held input takes the first element of `elementsFromPoint` that is not one.
+ */
+export function isInputShield(node: Node | null): boolean {
+ return node != null && liveShields.has(node);
+}
+
+/**
+ * Whether `target` is inside a held layer, walking the flat tree as the
+ * gesture host does (parentAcrossShadow: a slotted node to its slot, a
+ * shadow root to its host).
+ */
+export function isInHeldLayer(target: Node | null): boolean {
+ for (
+ let node: Node | null = target;
+ node != null;
+ node = parentAcrossShadow(node)
+ ) {
+ if (node instanceof Element && held.has(node)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/** One gate per document: the host holds a held layer's touches away. */
+function gate(doc: Document): void {
+ if (gatedDocuments.has(doc)) {
+ return;
+ }
+ gatedDocuments.add(doc);
+ getGestureHost(doc).addTouchGate(isInHeldLayer);
+}
+
+const SWALLOWED = [
+ 'pointerdown',
+ 'pointerup',
+ 'touchstart',
+ 'touchend',
+ 'mousedown',
+ 'mouseup',
+ 'click',
+ 'contextmenu',
+] as const;
+
+const swallow = (event: Event) => {
+ // A touch's start stays uncancelled: cancelling it would cancel the page's
+ // pinch-zoom too. The shield's `touch-action: pinch-zoom` keeps a finger
+ // from panning, and a tap's mouse events and click land on the shield,
+ // which swallows them.
+ if (event.cancelable && event.type !== 'touchstart') {
+ event.preventDefault();
+ }
+ event.stopPropagation();
+};
+
+/** A transparent top-layer cover of the viewport, inside `layer`. */
+function addShield(layer: Element): HTMLElement {
+ const shield = layer.ownerDocument.createElement('div');
+ shield.setAttribute('popover', 'manual');
+ shield.setAttribute('aria-hidden', 'true');
+ Object.assign(shield.style, {
+ position: 'fixed',
+ inset: '0',
+ width: '100vw',
+ height: '100vh',
+ maxWidth: 'none',
+ maxHeight: 'none',
+ margin: '0',
+ padding: '0',
+ border: '0',
+ background: 'transparent',
+ overflow: 'hidden',
+ touchAction: 'pinch-zoom',
+ // The two inherited properties that decide hit-testing, set here so the
+ // shield takes hits whatever its layer root opts out of (a full-viewport
+ // layer that is `pointer-events: none` and lets a backdrop child take the
+ // hits): inherited, they would let a held tap fall through to the page.
+ pointerEvents: 'auto',
+ visibility: 'visible',
+ });
+ for (const type of SWALLOWED) {
+ shield.addEventListener(type, swallow, {capture: true, passive: false});
+ }
+ layer.append(shield);
+ liveShields.add(shield);
+ if (typeof shield.showPopover === 'function') {
+ try {
+ shield.showPopover();
+ } catch {
+ // Not connected, or popovers unsupported: the shield still covers
+ // what it can as a fixed element.
+ }
+ }
+ return shield;
+}
+
+/**
+ * Holds input away from `layer` until `until` settles. Returns the release
+ * (idempotent), for a hold that ends early.
+ */
+export function holdInput(
+ layer: Element,
+ {until, scope}: InputHoldOptions,
+): () => void {
+ gate(layer.ownerDocument);
+ let state = held.get(layer);
+ if (state == null) {
+ state = {viewport: 0, layer: 0, shield: null, inertContent: null};
+ held.set(layer, state);
+ }
+ if (state.shield == null) {
+ state.shield = addShield(layer);
+ }
+ if (scope === 'viewport') {
+ state.viewport += 1;
+ } else {
+ state.layer += 1;
+ if (state.layer === 1) {
+ state.inertContent = makeContentInert(layer, state.shield);
+ }
+ }
+ let isReleased = false;
+ const release = () => {
+ if (isReleased) {
+ return;
+ }
+ isReleased = true;
+ const current = held.get(layer);
+ if (current == null) {
+ return;
+ }
+ if (scope === 'viewport') {
+ current.viewport -= 1;
+ } else {
+ current.layer -= 1;
+ if (current.layer === 0 && current.inertContent != null) {
+ restoreInert(current.inertContent);
+ current.inertContent = null;
+ }
+ }
+ if (current.viewport === 0 && current.layer === 0) {
+ if (current.shield != null) {
+ liveShields.delete(current.shield);
+ current.shield.remove();
+ }
+ held.delete(layer);
+ }
+ };
+ const end = 'finished' in until ? until.finished : until;
+ void Promise.resolve(end).then(release, release);
+ return release;
+}
+
+/**
+ * Makes the layer's content inert, the shield aside, and moves focus out of
+ * it: an element that turns inert while focused keeps its focus, and with it
+ * its key activation (Enter and Space still click a focused button), until
+ * the engine's focus fixup runs, if it runs at all (measured in Chromium and
+ * WebKit). Blurring it leaves focus on the document, as that fixup does.
+ */
+function makeContentInert(
+ layer: Element,
+ shield: Element,
+): Map {
+ const content = new Map();
+ for (const child of layer.children) {
+ if (child !== shield) {
+ content.set(child, child.hasAttribute('inert'));
+ child.setAttribute('inert', '');
+ }
+ }
+ const focused = deepActiveElement(layer.ownerDocument);
+ if (
+ focused instanceof HTMLElement &&
+ [...content.keys()].some(child => isInFlatTree(child, focused))
+ ) {
+ focused.blur();
+ }
+ return content;
+}
+
+/** The focused element, inside any shadow roots on the way down. */
+function deepActiveElement(doc: Document): Element | null {
+ let active = doc.activeElement;
+ while (active?.shadowRoot?.activeElement != null) {
+ active = active.shadowRoot.activeElement;
+ }
+ return active;
+}
+
+/** Whether `node` is `root` or inside it, walking the flat tree. */
+function isInFlatTree(root: Node, node: Node): boolean {
+ for (
+ let current: Node | null = node;
+ current != null;
+ current = parentAcrossShadow(current)
+ ) {
+ if (current === root) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function restoreInert(content: Map): void {
+ for (const [element, wasInert] of content) {
+ if (!wasInert) {
+ element.removeAttribute('inert');
+ }
+ }
+}
+
+/**
+ * Holds input away from the layer behind `ref` while `isHeld` is true (an
+ * inert bar, a presentation driven by state); released when `isHeld` turns
+ * false or the component unmounts.
+ */
+export function useInputHold(
+ ref: RefObject,
+ {isHeld, scope}: {isHeld: boolean; scope: InputHoldScope},
+): void {
+ useEffect(() => {
+ const layer = ref.current;
+ if (!isHeld || layer == null) {
+ return;
+ }
+ // Released by the cleanup alone.
+ return holdInput(layer, {
+ until: new Promise(() => {}),
+ scope,
+ });
+ }, [ref, isHeld, scope]);
+}
diff --git a/packages/core/src/Layer/layerExitCopy.test.ts b/packages/core/src/Layer/layerExitCopy.test.ts
new file mode 100644
index 0000000000000..ef0306fc46687
--- /dev/null
+++ b/packages/core/src/Layer/layerExitCopy.test.ts
@@ -0,0 +1,387 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerExitCopy.test.ts
+ * @input vitest (jsdom), layerExitCopy
+ * @output Checks the static copy a closing layer leaves for its close to
+ * play on: out of reach and out of the accessibility tree, no ids or form
+ * names, only in the top layer (hidden until a refused show succeeds, none
+ * without the popover API), on the layer's layout box with the transform
+ * it was drawn with, one per layer, scrolled where the layer was
+ * @position Testing; the browser proofs are in
+ * __tests__/layerExitCopy.interaction.browser.spec.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {placeLayerExitCopy} from './layerExitCopy';
+
+const BOX = {left: 41, top: 204, width: 320, height: 253};
+const ATTRIBUTE = 'data-test-exit';
+
+/** A layer drawn on BOX (jsdom has no layout). */
+function layer(): HTMLElement {
+ const host = document.createElement('section');
+ document.body.appendChild(host);
+ const element = document.createElement('div');
+ element.id = 'layer';
+ element.setAttribute('popover', 'auto');
+ element.style.setProperty('position-anchor', '--trigger');
+ element.style.setProperty('scale', '0.5 0.4');
+ element.style.setProperty('opacity', '0.3');
+ element.style.setProperty('transition', 'opacity 1s');
+ element.innerHTML =
+ '';
+ host.appendChild(element);
+ element.getBoundingClientRect = () => ({
+ ...BOX,
+ x: BOX.left,
+ y: BOX.top,
+ right: BOX.left + BOX.width,
+ bottom: BOX.top + BOX.height,
+ toJSON: () => ({}),
+ });
+ // Its layout box, which a fixed layer's offset box reports in viewport px.
+ for (const [name, value] of [
+ ['offsetLeft', BOX.left],
+ ['offsetTop', BOX.top],
+ ['offsetWidth', BOX.width],
+ ['offsetHeight', BOX.height],
+ ] as const) {
+ Object.defineProperty(element, name, {configurable: true, value});
+ }
+ return element;
+}
+
+describe('placeLayerExitCopy', () => {
+ const originalShow = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'showPopover',
+ );
+ /** The popover API, stood in for (jsdom has none), or taken away. */
+ const popoverApi = (present: boolean) => {
+ if (present) {
+ const show = vi.fn();
+ Object.defineProperty(HTMLElement.prototype, 'showPopover', {
+ configurable: true,
+ writable: true,
+ value: show,
+ });
+ return show;
+ }
+ Reflect.deleteProperty(HTMLElement.prototype, 'showPopover');
+ return null;
+ };
+ afterEach(() => {
+ if (originalShow == null) {
+ Reflect.deleteProperty(HTMLElement.prototype, 'showPopover');
+ } else {
+ Object.defineProperty(HTMLElement.prototype, 'showPopover', originalShow);
+ }
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ const place = (element: HTMLElement) => {
+ const copy = placeLayerExitCopy(element, ATTRIBUTE);
+ if (copy == null) {
+ throw new Error('no copy');
+ }
+ return copy;
+ };
+
+ it('puts a static copy right after the layer, out of reach and out of the accessibility tree', () => {
+ popoverApi(true);
+ const element = layer();
+ const copy = place(element);
+ expect(copy.previousElementSibling).toBe(element);
+ expect(copy.hasAttribute(ATTRIBUTE)).toBe(true);
+ expect(copy.getAttribute('aria-hidden')).toBe('true');
+ expect(copy.hasAttribute('inert')).toBe(true);
+ expect(copy.id).toBe('');
+ expect(copy.querySelectorAll('[id]')).toHaveLength(0);
+ // The content is the layer's, classes and all.
+ expect(copy.querySelector('.list')?.textContent).toBe('One');
+ expect(copy.style.getPropertyValue('pointer-events')).toBe('none');
+ });
+
+ it('takes the copy out of every form and radio group, so the live selection stays', () => {
+ popoverApi(true);
+ const element = layer();
+ element.insertAdjacentHTML(
+ 'beforeend',
+ ' ',
+ );
+ const live = element.querySelector('input[value="m"]')!;
+ const copy = place(element);
+ expect(copy.querySelectorAll('[name]')).toHaveLength(0);
+ // Every cloned control names a form that cannot exist, so none has an
+ // owner, whatever the copy stands inside.
+ expect(
+ [...copy.querySelectorAll('input')].map(node =>
+ node.getAttribute('form'),
+ ),
+ ).toEqual(['', '', '']);
+ expect(live.checked).toBe(true);
+ expect(live.getAttribute('name')).toBe('size');
+ });
+
+ it('leaves a form around the layer valid while the copy stands in it', () => {
+ popoverApi(true);
+ const element = layer();
+ const form = document.createElement('form');
+ element.parentElement!.append(form);
+ form.append(element);
+ element.insertAdjacentHTML(
+ 'beforeend',
+ ' ',
+ );
+ // The live layer's own fields are the form's while it is open.
+ expect(form.checkValidity()).toBe(false);
+ const copy = place(element);
+ // The copy stands right after the layer, so inside the form; its
+ // controls belong to no form, and the live fields are unchanged.
+ expect(copy.closest('form')).toBe(form);
+ expect([...form.elements]).toHaveLength(3);
+ for (const node of copy.querySelectorAll('input, select, textarea')) {
+ expect((node as HTMLInputElement).form).toBeNull();
+ }
+ });
+
+ it('keeps one copy per layer: a second takes only that layer\u2019s first away', () => {
+ popoverApi(true);
+ const element = layer();
+ // Another layer beside it, closing too, with its own copy.
+ const other = layer();
+ element.parentElement!.append(other);
+ const otherCopy = place(other);
+ const first = place(element);
+ const second = place(element);
+ expect(first.isConnected).toBe(false);
+ expect(second.isConnected).toBe(true);
+ expect(otherCopy.isConnected).toBe(true);
+ expect(document.querySelectorAll(`[${ATTRIBUTE}]`)).toHaveLength(2);
+ });
+
+ it('stands on the layer\u2019s box, free of the live layer\u2019s anchoring and motion', () => {
+ popoverApi(true);
+ const element = layer();
+ const copy = place(element);
+ expect(copy.style.getPropertyValue('position')).toBe('fixed');
+ expect(copy.style.getPropertyValue('left')).toBe('41px');
+ expect(copy.style.getPropertyValue('top')).toBe('204px');
+ expect(copy.style.getPropertyValue('width')).toBe('320px');
+ expect(copy.style.getPropertyValue('height')).toBe('253px');
+ for (const property of [
+ 'position-anchor',
+ 'scale',
+ 'opacity',
+ 'transition',
+ ]) {
+ expect(copy.style.getPropertyValue(property), property).toBe('');
+ }
+ expect(copy.style.getPropertyValue('animation-name')).toBe('none');
+ // No alignment against the anchor it left (a phone menu's anchor-center).
+ expect(copy.style.getPropertyValue('justify-self')).toBe('normal');
+ expect(copy.style.getPropertyValue('align-self')).toBe('normal');
+ });
+
+ it('holds where a layer still entering was drawn: its layout box, with the transform it was drawn with', () => {
+ popoverApi(true);
+ const element = layer();
+ // Mid-entrance: drawn at half size about its top-left corner, so its
+ // drawn rect is not its layout box.
+ element.getBoundingClientRect = () => ({
+ left: 41,
+ top: 204,
+ width: 160,
+ height: 126.5,
+ x: 41,
+ y: 204,
+ right: 201,
+ bottom: 330.5,
+ toJSON: () => ({}),
+ });
+ for (const [name, value] of [
+ ['offsetLeft', 41],
+ ['offsetTop', 204],
+ ['offsetWidth', 320],
+ ['offsetHeight', 253],
+ ] as const) {
+ Object.defineProperty(element, name, {configurable: true, value});
+ }
+ element.getAnimations = () =>
+ [
+ {effect: {target: element, pseudoElement: null}},
+ ] as unknown as Animation[];
+ const presented: Record = {
+ scale: '0.5',
+ 'transform-origin': '0px 0px',
+ width: '320.4px',
+ height: '253px',
+ 'box-sizing': 'border-box',
+ };
+ const original = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation((node, pseudo) =>
+ node === element
+ ? ({
+ getPropertyValue: (property: string) => presented[property] ?? '',
+ } as CSSStyleDeclaration)
+ : original(node, pseudo),
+ );
+ const copy = place(element);
+ // Laid out where the layer is, at its used size, fractions kept...
+ expect(copy.style.getPropertyValue('left')).toBe('41px');
+ expect(copy.style.getPropertyValue('top')).toBe('204px');
+ expect(copy.style.getPropertyValue('width')).toBe('320.4px');
+ expect(copy.style.getPropertyValue('height')).toBe('253px');
+ // ...and drawn as it was drawn.
+ expect(copy.style.getPropertyValue('scale')).toBe('0.5');
+ expect(copy.style.getPropertyValue('transform-origin')).toBe('0px 0px');
+ });
+
+ it('shows the copy only in the top layer, as a manual popover, with no z-index', () => {
+ const show = popoverApi(true)!;
+ const element = layer();
+ const copy = place(element);
+ expect(copy.getAttribute('popover')).toBe('manual');
+ expect(show).toHaveBeenCalledTimes(1);
+ expect(show.mock.contexts[0]).toBe(copy);
+ expect(copy.style.getPropertyValue('z-index')).toBe('');
+ expect(copy.style.getPropertyValue('display')).toBe('');
+ // The UA's popover inset does not over-constrain the box.
+ expect(copy.style.getPropertyValue('right')).toBe('auto');
+ expect(copy.style.getPropertyValue('bottom')).toBe('auto');
+ });
+
+ it('waits, hidden, when the browser refuses the show during the closing toggle, and shows once it is over', async () => {
+ const show = popoverApi(true)!;
+ // Android Chromium 158 refuses a show inside another popover's toggle.
+ show.mockImplementationOnce(() => {
+ throw new DOMException(
+ 'Invalid to show a popover during another show operation',
+ 'InvalidStateError',
+ );
+ });
+ const element = layer();
+ let copy: HTMLElement | null = null;
+ expect(() => {
+ copy = place(element);
+ }).not.toThrow();
+ // Not shown yet, and nothing stands in for the top layer: the UA keeps a
+ // popover that is not open out of view.
+ expect(copy!.isConnected).toBe(true);
+ expect(copy!.style.getPropertyValue('display')).toBe('');
+ expect(copy!.style.getPropertyValue('z-index')).toBe('');
+ expect(show).toHaveBeenCalledTimes(1);
+ // The script that closed the layer is over: shown.
+ await Promise.resolve();
+ expect(show).toHaveBeenCalledTimes(2);
+ expect(copy!.isConnected).toBe(true);
+ });
+
+ it('tries again in the next frame, and takes the copy away if the browser still refuses', async () => {
+ const show = popoverApi(true)!;
+ show.mockImplementation(() => {
+ throw new DOMException('refused', 'InvalidStateError');
+ });
+ const frames: FrameRequestCallback[] = [];
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const element = layer();
+ const copy = place(element);
+ await Promise.resolve();
+ expect(frames).toHaveLength(1);
+ frames[0](0);
+ expect(show).toHaveBeenCalledTimes(3);
+ expect(copy.isConnected).toBe(false);
+ });
+
+ it('does not reach for the top layer for a copy already taken away', async () => {
+ const show = popoverApi(true)!;
+ show.mockImplementationOnce(() => {
+ throw new DOMException('refused', 'InvalidStateError');
+ });
+ const copy = place(layer());
+ copy.remove();
+ await Promise.resolve();
+ expect(show).toHaveBeenCalledTimes(1);
+ });
+
+ it('places no copy without the popover API: the close is immediate', () => {
+ popoverApi(false);
+ const element = layer();
+ expect(placeLayerExitCopy(element, ATTRIBUTE)).toBeNull();
+ expect(document.querySelector(`[${ATTRIBUTE}]`)).toBeNull();
+ });
+
+ it('starts as the layer looks: values its running animations hold are written onto the copy', () => {
+ popoverApi(true);
+ const element = layer();
+ const dialog = element.querySelector('[role="dialog"]')!;
+ const list = element.querySelector('.list')!;
+ // A compositor curve on the layer and one on its dialog; the list has none.
+ element.getAnimations = () =>
+ [element, dialog].map(target => ({
+ effect: {target, pseudoElement: null},
+ })) as unknown as Animation[];
+ const presented = new Map>([
+ [element, {opacity: '0.7', 'transform-origin': '160px 0px'}],
+ [dialog, {translate: '0px 12px', opacity: '0.5'}],
+ ]);
+ const original = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation((node, pseudo) => {
+ const values = presented.get(node);
+ if (values == null) {
+ return original(node, pseudo);
+ }
+ return {
+ getPropertyValue: (property: string) => values[property] ?? '',
+ } as CSSStyleDeclaration;
+ });
+ const copy = place(element);
+ expect(copy.style.getPropertyValue('opacity')).toBe('0.7');
+ expect(copy.style.getPropertyValue('transform-origin')).toBe('160px 0px');
+ const copyDialog = copy.querySelector('[role="dialog"]')!;
+ expect(copyDialog.style.getPropertyValue('translate')).toBe('0px 12px');
+ expect(copyDialog.style.getPropertyValue('opacity')).toBe('0.5');
+ // Nothing is written where nothing runs.
+ expect(
+ copy.querySelector('.list')!.getAttribute('style'),
+ ).toBe(list.getAttribute('style'));
+ });
+
+ it.each(['iframe', 'object', 'embed', 'video', 'audio', 'canvas'])(
+ 'copies a %s as an empty box of its size, so nothing loads or plays again',
+ tag => {
+ popoverApi(true);
+ const element = layer();
+ const live = document.createElement(tag);
+ live.className = 'media';
+ live.style.setProperty('margin', '4px');
+ Object.defineProperty(live, 'offsetWidth', {value: 320});
+ Object.defineProperty(live, 'offsetHeight', {value: 180});
+ element.querySelector('.list')!.appendChild(live);
+ const copy = place(element);
+ expect(copy.querySelector(tag)).toBeNull();
+ const box = copy.querySelector('.list > .media')!;
+ expect(box.tagName).toBe('SPAN');
+ expect(box.childNodes).toHaveLength(0);
+ expect(box.style.getPropertyValue('width')).toBe('320px');
+ expect(box.style.getPropertyValue('height')).toBe('180px');
+ expect(box.style.getPropertyValue('margin')).toBe('4px');
+ // The live one is untouched.
+ expect(element.querySelector(tag)).toBe(live);
+ },
+ );
+
+ it('keeps scrolled content where it was scrolled to', () => {
+ popoverApi(true);
+ const element = layer();
+ const list = element.querySelector('.list')!;
+ list.scrollTop = 120;
+ const copy = place(element);
+ expect(copy.querySelector('.list')!.scrollTop).toBe(120);
+ });
+});
diff --git a/packages/core/src/Layer/layerExitCopy.ts b/packages/core/src/Layer/layerExitCopy.ts
new file mode 100644
index 0000000000000..024872cedf2ef
--- /dev/null
+++ b/packages/core/src/Layer/layerExitCopy.ts
@@ -0,0 +1,335 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file layerExitCopy.ts
+ * @input A layer's popover element as it closes
+ * @output Exports `placeLayerExitCopy`: a static, inert copy of the layer put
+ * where the layer is drawn, in the top layer, for a touch presentation's
+ * close to play on, and `LayerExitBox`
+ * @position Layer runtime helper for a touch presentation that animates a
+ * popover out: the one exit copy a layer may have
+ * (architecture:layer-runtime INV13, architecture:component-style-authoring
+ * INV7)
+ *
+ * The browser hides a popover the moment it closes (a pick, Escape, its own
+ * light dismiss), so a close that has to stay on screen plays on a copy taken
+ * as the popover closes: same place, same size, same inherited theme, and the
+ * same look, values its running animations hold included (a clone keeps only
+ * inline styles, and a compositor curve holds its value outside them). It is
+ * laid out on the layer's own box and carries the transform the layer was
+ * drawn with, so a copy taken mid-entrance holds where it was drawn. The copy
+ * has no ids, no form names and no form owner (a cloned checked radio would
+ * otherwise take the live group's selection, and a named field would
+ * submit), is `inert` and hidden from assistive technology, and takes no
+ * pointer events. Embedded content (an iframe, an object or embed, media, a
+ * canvas) stands in the copy as an empty box of its size: a deep copy would
+ * load or play it again (an iframe navigates, autoplay restarts, a canvas
+ * comes back blank). A layer has one copy: placing another for the same layer
+ * takes the previous one away; other layers' copies stay.
+ *
+ * It is shown only in the top layer, as a manual popover, so a clipping,
+ * transformed or sticky ancestor neither cuts nor moves it; a fixed box or a
+ * larger `z-index` is no substitute (spec:AST-027 FR8). Where the browser
+ * refuses the show during the closing popover's own toggle (Android Chromium
+ * 158: "Invalid to show a popover during another show operation"), the copy
+ * waits, hidden, and shows once the toggle is over: after the script that
+ * closed the layer or, failing that, in the next frame before it paints. A
+ * browser without the popover API, or one that still refuses, gets no copy,
+ * and the close is immediate. Its owner animates it and removes it when its
+ * spring settles; nothing on the main thread runs per frame while it moves.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/layerExitCopy.test.ts
+ * - /packages/core/src/Layer/__tests__/layerExitCopy.interaction.browser.spec.ts
+ * - /docs/architecture/layer-runtime.md
+ */
+
+/** A box in viewport px. */
+export interface LayerExitBox {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+/**
+ * Properties a running animation may hold, which the copy takes from what
+ * the layer presents.
+ */
+const PRESENTED_PROPERTIES = [
+ 'translate',
+ 'rotate',
+ 'scale',
+ 'transform',
+ 'transform-origin',
+ 'opacity',
+] as const;
+
+/** Inline properties the copy must not keep from the live layer. */
+const LIVE_ONLY_PROPERTIES = [
+ 'position-anchor',
+ 'position-area',
+ 'position-try-fallbacks',
+ 'inset',
+ 'right',
+ 'bottom',
+ 'scale',
+ 'opacity',
+ 'transition',
+] as const;
+
+/**
+ * Writes onto `copy` what `element` and its subtree present through running
+ * animations: the copy starts as the layer looks, not as its inline styles
+ * say.
+ */
+function commitPresented(element: HTMLElement, copy: HTMLElement): void {
+ const view = element.ownerDocument.defaultView;
+ if (view == null || typeof element.getAnimations !== 'function') {
+ return;
+ }
+ const animated = new Set();
+ for (const animation of element.getAnimations({subtree: true})) {
+ const effect = animation.effect as KeyframeEffect | null;
+ if (effect?.target != null && effect.pseudoElement == null) {
+ animated.add(effect.target);
+ }
+ }
+ if (animated.size === 0) {
+ return;
+ }
+ const sources = [element, ...element.querySelectorAll('*')];
+ const copies = [copy, ...copy.querySelectorAll('*')];
+ sources.forEach((source, index) => {
+ const target = copies[index];
+ if (!animated.has(source) || !(target instanceof view.Element)) {
+ return;
+ }
+ const computed = view.getComputedStyle(source);
+ const {style} = target as HTMLElement;
+ for (const property of PRESENTED_PROPERTIES) {
+ style.setProperty(property, computed.getPropertyValue(property));
+ }
+ });
+}
+
+/** The properties that move a box without moving its layout. */
+const TRANSFORM_PROPERTIES = [
+ 'transform',
+ 'translate',
+ 'scale',
+ 'rotate',
+] as const;
+
+/** Each layer's copy: placing another for the same layer replaces it. */
+/** The elements a `