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/cli-component-name-case.md b/.changeset/cli-component-name-case.md new file mode 100644 index 0000000000000..bd1bd6d0617d3 --- /dev/null +++ b/.changeset/cli-component-name-case.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[fix] `astryx component` matches component and hook names case for case, and only in the file that exports the name. A lowercased name such as `list` or `badge` is now unknown, with the component it matches by case suggested, instead of opening List's or Badge's doc. A module that only shares a name's spelling, such as a lowercase `button.ts` table elsewhere in Core, no longer opens the nearest doc either, and `--source` no longer reads it. + +@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/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..ea6ee44bda14a --- /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. The host follows the primary pointer when it changes; what it attaches under a fine pointer is in the every-pointer changeset (`gestures-every-pointer.md`). 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-every-pointer.md b/.changeset/gestures-every-pointer.md new file mode 100644 index 0000000000000..30ec76582c1ae --- /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 finger's or a pen's hold that does something keeps text unselected under any primary pointer, a touchscreen laptop's included, while a mouse keeps its released behavior (FR41). 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 is a finger's only: it stays off under a mouse, a trackpad and a pen, and takes no `allowedPointerTypes`, 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/list-dividers-hide-on-press.md b/.changeset/list-dividers-hide-on-press.md new file mode 100644 index 0000000000000..0af8460ffdca3 --- /dev/null +++ b/.changeset/list-dividers-hide-on-press.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] In a `List` with `hasDividers`, a touch press hides the dividers on either side of the pressed row, so the pressed row reads as one unbroken highlight; both come back the moment the finger lifts, while the highlight fades. This applies under any finger (a coarse primary pointer); with a mouse the dividers stay drawn. + +@vjeux diff --git a/.changeset/list-row-press-compositor.md b/.changeset/list-row-press-compositor.md new file mode 100644 index 0000000000000..df7f0f38f7256 --- /dev/null +++ b/.changeset/list-row-press-compositor.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] A list row's touch press release keeps fading while the page runs script. `ListItem`, `Item` and `TreeList` rows used to stay fully pressed after the finger lifted until the main thread was free, and every frame of the fade repainted the row; the release now runs on the compositor, with the same color, clock and curve as before. Under a finger, while a row is pressed and through its release, the press paints on the row's `::before` and the row is its own stacking context; at rest nothing of it applies, so a row's own `::before` decoration and its children's stacking are as they were. During a press the layer is the row's `::before`, so a caller's decoration there takes the layer's box and paint for that time (a page stylesheet keeps the properties it sets); decoration that should stay through a press belongs on `::after` or a child element. With a mouse or trackpad the row is unchanged: no layer and no new stacking context. + +@vjeux diff --git a/.changeset/list-selection-hold.md b/.changeset/list-selection-hold.md new file mode 100644 index 0000000000000..222de0bbf1579 --- /dev/null +++ b/.changeset/list-selection-hold.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[chore] Internal: under a finger, a list row tapped to push can stay selected while the pushed screen covers it, then deselect as the screen pops, as a UIKit table row does; with a mouse the press releases at the lift as before. The hold that drives it (`List/selectionHold.ts`) is internal to core, so no public export changes. The deselect runs on the compositor, and a divided list keeps the dividers around the held row hidden. + +@vjeux diff --git a/.changeset/long-press-one-source.md b/.changeset/long-press-one-source.md new file mode 100644 index 0000000000000..a73cf7b961b6d --- /dev/null +++ b/.changeset/long-press-one-source.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: `useLongPress` (ContextMenu's long press, and 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/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/press-coarse-device-mouse-keyboard.md b/.changeset/press-coarse-device-mouse-keyboard.md new file mode 100644 index 0000000000000..0c640fa632b72 --- /dev/null +++ b/.changeset/press-coarse-device-mouse-keyboard.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] On a phone or tablet, a press made with a mouse, a trackpad or the Space key now shows the pressed state. Touch devices drop the CSS `:active` press so a finger only sees the touch press model, but that rule keys on the device's primary pointer, so a tablet with a trackpad and keyboard (or a phone with a mouse) lost the pressed state for every press that was not a finger. The touch press controller now paints those presses on such devices with the same pixels a desktop press has: at once, held while the button or key is down, faded at the release. As on a desktop, Space paints only a focused button that is itself the pressed surface (a checkbox's or radio's row stays at rest), and a menu row keeps the menu's own highlight. Desktop presses and finger presses are unchanged. + +@vjeux diff --git a/.changeset/press-control-profile.md b/.changeset/press-control-profile.md new file mode 100644 index 0000000000000..9f544c3f1e944 --- /dev/null +++ b/.changeset/press-control-profile.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Under a finger, a button, card, link or other control now highlights in the frame the finger lands, as UIKit's controls do, instead of after a 150 ms delay; inside a scroller it still waits that delay (a flick paints nothing), and a scroll that takes a held press cancels it with no fade. List rows (Item, TreeList) wait the 150 ms delay only inside a scroll view, and are cancelled by 10 px of travel. `usePressFeedback` is unchanged: a local pressable it marks is tracked as a control. The press controller now keeps only two passive listeners on the document at rest and attaches the rest while a press is live. A mouse on a desktop keeps `:active`. + +@vjeux diff --git a/.changeset/press-fine-pointer.md b/.changeset/press-fine-pointer.md new file mode 100644 index 0000000000000..a9b96c2ed8dcc --- /dev/null +++ b/.changeset/press-fine-pointer.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] A press with a mouse or a pen now shows the same pressed state a finger's does, on every device. It paints at once when the button goes down (no delay, even in a scrolling list), holds while it is down, and fades at the release on the same clock a finger's press uses, in place of the browser's `:active`. A right click, a ctrl-click on macOS and a pen's barrel button paint nothing, and a Space press is unchanged. A press on a link or a button inside a pressable row (a link in a radio option's description, for example) no longer paints the row, under a finger or a mouse. + +@vjeux diff --git a/.changeset/press-paint-reduced-motion.md b/.changeset/press-paint-reduced-motion.md new file mode 100644 index 0000000000000..1cc27a1d89c3d --- /dev/null +++ b/.changeset/press-paint-reduced-motion.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Under Reduce Motion the shared press paint's release follows design:reduced-motion: with a coarse primary pointer it is the system cross-fade (its duration and curve from `reducedMotionFadeConsts`), and with any other pointer it completes at the lift with no animation. + +@vjeux diff --git a/.changeset/press-release-compositor.md b/.changeset/press-release-compositor.md new file mode 100644 index 0000000000000..0b002a8d343b9 --- /dev/null +++ b/.changeset/press-release-compositor.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Under a coarse primary pointer (a touch screen as the main input), a button's or a card's touch press release now runs on the compositor: it keeps fading while the page's script is busy instead of freezing at full strength and snapping off, and it paints nothing per frame. There, every control's touch release (Button, the cards, and the other controls on the shared overlay, such as Switch, Link, Tab and CheckboxInput) follows UIButton's highlight release, 250 ms ease-in-out instead of 200 ms ease-out; a list row's stays on the deselect clock; and under reduced motion the release is an opacity cross-fade of 200 ms or less. With any other pointer, a finger on a touch screen beside a mouse included, nothing changes. Under a coarse primary pointer, while a press is on or fading, Button paints it on its own `::before` and sets `isolation: isolate`; at rest it adds neither, so a `::before` you style, through `xstyle` or a `className` rule, merges into that layer only during a press. Style a child element to keep it unchanged. + +@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/segmented-control-drag-to-select.md b/.changeset/segmented-control-drag-to-select.md new file mode 100644 index 0000000000000..17e9a74dfe68e --- /dev/null +++ b/.changeset/segmented-control-drag-to-select.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] SegmentedControl: under a finger, on a touch device (a coarse primary pointer), the control tracks the touch. Dragging the selected segment carries the selection along with the finger, and the segment nearest the finger is chosen when it lets go (`onChange` fires once, at the lift). While the selection is dragged, the selected label's colour follows it, with a margin around each boundary so a finger resting on one never flickers; label weights change only at the lift, so nothing reflows under the finger. A tap selects through the browser's own click, and a pressed segment shows the shared pressed overlay; nothing lifts or dims. A vertical drag that starts on the control still scrolls the page. A commit the item's `onClick` vetoes sends the selection back at once; one a controlled parent adopts later lands without a bounce. With Reduce Motion nothing chases or travels: at the lift the selection cross-fades (`design:reduced-motion`). Keyboard and assistive technology keep the click; no element is added. + +@vjeux diff --git a/.changeset/segmented-control-every-pointer.md b/.changeset/segmented-control-every-pointer.md new file mode 100644 index 0000000000000..f44b11288a3f9 --- /dev/null +++ b/.changeset/segmented-control-every-pointer.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] SegmentedControl: a mouse or a pen drags the selection as a finger does (`spec:AST-094` FR43). A drag from the selected segment carries it with the pointer and the release commits the segment nearest the pointer (`onChange` fires once, at the release); a drag that starts on another segment commits where it lifts. A click still selects with the theme's color transition, a drag selects no text, and under a mouse or a pen the selection settles on the theme's state-change spring rather than UIKit's. Keyboard and assistive technology keep the click. + +@vjeux diff --git a/.changeset/segmented-control-selection-slide.md b/.changeset/segmented-control-selection-slide.md new file mode 100644 index 0000000000000..cd695d0b4e6a7 --- /dev/null +++ b/.changeset/segmented-control-selection-slide.md @@ -0,0 +1,6 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] SegmentedControl: under a finger the selection slides to the new segment on UIKit's spring, whether a tap, an arrow key or a new `value` moved it. The selection indicator is the control's own pseudo-element, so no element is added. The motion runs on the compositor and keeps moving while the main thread is busy. With Reduce Motion nothing travels or scales: the old selection fades out where it is as the new one fades in (`design:reduced-motion`). The spring is UIKit's measured one, an internal motion role no theme retunes, and no theme value lengthens the Reduce Motion fade. With a mouse the color fade stays. +@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/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsx index 881f53db5430d..78bfb30e335de 100644 --- a/apps/storybook/stories/List.stories.tsx +++ b/apps/storybook/stories/List.stories.tsx @@ -7,7 +7,7 @@ * @position Storybook demonstrations for List consumers */ -import {useState} from 'react'; +import {useRef, useState, type MouseEvent} from 'react'; import * as stylex from '@stylexjs/stylex'; import type {Meta, StoryObj} from '@storybook/react'; import {List, ListItem} from '@astryxdesign/core/List'; @@ -18,6 +18,12 @@ import {Icon} from '@astryxdesign/core/Icon'; import {Switch} from '@astryxdesign/core/Switch'; import {Heading, Text} from '@astryxdesign/core/Text'; import {VStack} from '@astryxdesign/core/Layout'; +import {Button} from '@astryxdesign/core/Button'; +// The selection hold is internal to core (no public API records it yet). +import { + holdSelection, + type SelectionHold as RowSelectionHold, +} from '../../../packages/core/src/List/selectionHold'; import { Cog6ToothIcon, BellIcon, @@ -408,3 +414,118 @@ export const HeaderInFlexParent: Story = { }, }, }; + +function SelectionHoldDemo() { + const hold = useRef(null); + const slider = useRef(null); + const [open, setOpen] = useState(null); + const [progress, setProgress] = useState(0); + const push = (label: string) => (event: MouseEvent) => { + // In the same task as the activation that pushes. + hold.current = holdSelection(event.target); + setProgress(0); + setOpen(label); + }; + const settle = async ( + to: 0 | 1, + timing?: Parameters[1], + {followSlider = false}: {followSlider?: boolean} = {}, + ) => { + const current = hold.current; + // A slow pop shows where it is on the slider (written to the input, no + // render per frame), so a finger that takes the slider over mid-flight + // continues from the value on screen. (Off for the regular pop, whose + // proof counts every paint.) + const following = {frame: 0}; + const follow = () => { + if (current != null && slider.current != null) { + slider.current.value = String(current.presentation()); + } + following.frame = requestAnimationFrame(follow); + }; + if (followSlider) { + following.frame = requestAnimationFrame(follow); + } + // No hold under a mouse: the screen just pops. + const arrived = current == null || (await current.animate(to, timing)); + cancelAnimationFrame(following.frame); + if (!arrived) { + // Interrupted (a finger took the progress over mid-flight): the hold + // stays where the finger left it. + return; + } + if (to === 1) { + setOpen(null); + current?.end(true); + current?.focus({preventScroll: true}); + hold.current = null; + } else { + current?.end(false); + setProgress(0); + } + }; + return ( + + + {['Inbox', 'Sent', 'Drafts'].map(label => ( + } + /> + ))} + + {open != null && ( + + {open} (pushed) +
`; + 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 +303,1066 @@ 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( + `
${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('wheel and pen input', () => { + /** A non-passive wheel listener: Chromium then waits for the page itself. */ + const listenNonPassively = (page: Page) => + page.evaluate(() => + window.addEventListener('wheel', () => {}, {passive: false}), + ); + /** The wheel steps the page received. */ + const wheelsOf = async (page: Page) => + (await readInputLog(page)).filter(r => r.type === 'wheel'); + + test('a wheel step reaches the page as exactly its deltas, trusted, with Control when held, by the time wheel() resolves on a page whose wheel listeners are all passive', async ({ + page, + }) => { + await fixture(page); + const driver = await webInputDriver(page); + test.skip(!driver.wheels, WHEEL_SKIP); + await driver.wheel({x: 60, y: 520, dy: 120}); + // The input log listens passively, so Chromium answers the dispatch + // before the page has the step: read right after the call. + expect(await wheelsOf(page)).toHaveLength(1); + await driver.wheel({x: 60, y: 520, dx: 30, dy: -40, ctrl: true}); + const wheels = await wheelsOf(page); + expect(wheels).toHaveLength(2); + // Chromium's phone context has a device scale factor of 3: the driver + // multiplies back what Chromium divides by, so the page sees CSS px. + expect(wheels[0]).toMatchObject({ + isTrusted: true, + deltaX: 0, + deltaY: 120, + deltaMode: 0, + ctrlKey: false, + x: 60, + y: 520, + }); + expect(wheels[1]).toMatchObject({ + isTrusted: true, + deltaX: 30, + deltaY: -40, + deltaMode: 0, + ctrlKey: true, + }); + }); + + test('a wheel step reaches the page by the time wheel() resolves with a non-passive wheel listener too', async ({ + page, + }) => { + await fixture(page); + const driver = await webInputDriver(page); + test.skip(!driver.wheels, WHEEL_SKIP); + await listenNonPassively(page); + await driver.wheel({x: 60, y: 520, dy: 80}); + expect(await wheelsOf(page)).toHaveLength(1); + await driver.wheel({x: 60, y: 520, dy: -20, ctrl: true}); + const wheels = await wheelsOf(page); + expect(wheels).toHaveLength(2); + expect(wheels[0]).toMatchObject({ + isTrusted: true, + deltaY: 80, + ctrlKey: false, + }); + expect(wheels[1]).toMatchObject({ + isTrusted: true, + deltaY: -20, + ctrlKey: true, + }); + }); + + test('a pen stroke reaches the page as trusted pen pointers, with its pressure, at its scripted times', async ({ + page, + }) => { + await fixture(page); + const driver = await webInputDriver(page); + test.skip(!driver.pens, PEN_SKIP); + await driver.pen([ + {x: 100, y: 100, t: 0, pressure: 0.3}, + {x: 100, y: 140, t: 50, pressure: 0.6}, + {x: 100, y: 180, t: 100, pressure: 0.6}, + ]); + const log = await readInputLog(page); + const down = log.find(r => r.type === 'pointerdown'); + const moves = log.filter(r => r.type === 'pointermove'); + const up = log.find(r => r.type === 'pointerup'); + expect(down).toMatchObject({ + isTrusted: true, + pointerType: 'pen', + x: 100, + y: 100, + }); + expect(down?.pressure).toBeCloseTo(0.3, 2); + expect(moves.at(-1)).toMatchObject({pointerType: 'pen', y: 180}); + expect(moves.at(-1)?.pressure).toBeCloseTo(0.6, 2); + expect(up).toMatchObject({isTrusted: true, pointerType: 'pen'}); + // The scripted 100 ms between the first and last points reach the page. + expect( + (moves.at(-1)?.timeStamp ?? NaN) - (down?.timeStamp ?? NaN), + ).toBeCloseTo(100, 0); + }); + + test('a stroke sent right after a navigation presses where it is scripted', async ({ + page, + }) => { + // The driver exists before the page navigates, and the stroke goes out + // the moment the page has loaded: the press must not take the previous + // document's page scale (about:blank's, in the phone project). + const driver = await webInputDriver(page); + test.skip(!driver.pens, PEN_SKIP); + await fixture(page); + await driver.pen([ + {x: 100, y: 100, t: 0, pressure: 0.5}, + {x: 100, y: 120, t: 30, pressure: 0.5}, + ]); + const down = (await readInputLog(page)).find(r => r.type === 'pointerdown'); + expect(down).toMatchObject({pointerType: 'pen', x: 100, y: 100}); + }); + + test('says which inputs it has: WebKit in a phone context has no wheel and no pen', async ({ + page, + browserName, + }) => { + await fixture(page); + const driver = await webInputDriver(page); + if (browserName === 'chromium') { + expect({wheels: driver.wheels, pens: driver.pens}).toEqual({ + wheels: true, + pens: true, + }); + return; + } + expect({wheels: driver.wheels, pens: driver.pens}).toEqual({ + wheels: false, + pens: false, + }); + await expect(driver.wheel({x: 60, y: 520, dy: 120})).rejects.toThrow( + WHEEL_SKIP, + ); + await expect(driver.pen([{x: 100, y: 100, t: 0}])).rejects.toThrow( + PEN_SKIP, + ); + }); + + test.describe('in a desktop context', () => { + test.use({isMobile: false, hasTouch: false, deviceScaleFactor: 1}); + + test('a wheel step reaches the page as exactly its deltas in both engines', async ({ + page, + }) => { + await fixture(page); + const driver = await webInputDriver(page); + expect(driver.wheels).toBe(true); + await driver.wheel({x: 60, y: 520, dy: 120}); + expect(await wheelsOf(page)).toHaveLength(1); + await driver.wheel({x: 60, y: 520, dx: -25, dy: 0, ctrl: true}); + const wheels = await wheelsOf(page); + expect(wheels).toHaveLength(2); + expect(wheels[0]).toMatchObject({ + isTrusted: true, + deltaX: 0, + deltaY: 120, + deltaMode: 0, + ctrlKey: false, + }); + expect(wheels[1]).toMatchObject({ + isTrusted: true, + deltaX: -25, + deltaY: 0, + deltaMode: 0, + ctrlKey: true, + }); + }); + }); +}); + test.describe('curve sampling', () => { test('a CSS transition samples onto its cubic-bezier to 0.05 px', async ({ page, @@ -307,6 +1428,81 @@ test.describe('curve sampling', () => { }); }); +// A full-size veil on the fixture's box, drawn by its ::before. +const VEIL_STYLE = + "#box::before { content: ''; position: absolute; inset: 0; background: #000; opacity: 0; }"; + +test.describe('pseudo-element animations', () => { + test('sampleCurve reads a ::before animation when given its pseudo-element', async ({ + page, + }) => { + await fixture(page); + const box = page.locator('#box'); + await box.evaluate((el, veil) => { + const style = document.createElement('style'); + style.textContent = veil; + document.head.append(style); + el.animate( + [ + {opacity: 0, transform: 'translateY(0px)'}, + {opacity: 1, transform: 'translateY(40px)'}, + ], + {duration: 300, easing: 'linear', pseudoElement: '::before'}, + ); + }, VEIL_STYLE); + await holdAnimations(page, box); + const samples = await sampleCurve(box, [0, 75, 150, 225, 300], { + pseudoElement: '::before', + }); + // Labelled by the veil's own clock: the last read just inside its end. + expect(samples.at(-1)).toMatchObject({t: 300, presentedAt: 299.5}); + const fade = compareCurve(curveOf(samples, 'opacity'), t => t / 300, 0.005); + expect(fade.maxError, JSON.stringify(fade.worst)).toBeLessThanOrEqual( + 0.005, + ); + const move = compareCurve( + curveOf(samples, 'translateY'), + t => (40 * t) / 300, + 0.05, + ); + expect(move.maxError, JSON.stringify(move.worst)).toBeLessThanOrEqual(0.05); + // Without it, the box itself, which does not move. + const [boxAt150] = await sampleCurve(box, [150]); + expect(boxAt150.opacity).toBe(1); + expect(boxAt150.transform.translateY).toBe(0); + }); + + test('waitForRest waits out a ::before animation', async ({page}) => { + await fixture(page); + const box = page.locator('#box'); + await box.evaluate((el, veil) => { + const style = document.createElement('style'); + style.textContent = veil; + document.head.append(style); + (window as unknown as {__veil: Animation}).__veil = el.animate( + [{opacity: 0}, {opacity: 1}], + { + duration: 600, + easing: 'linear', + fill: 'forwards', + pseudoElement: '::before', + }, + ); + }, VEIL_STYLE); + // Its subtree read includes the element's pseudo-elements. + await waitForRest(box); + const veil = await box.evaluate(element => { + const a = (window as unknown as {__veil: Animation}).__veil; + return { + playState: a.playState, + currentTime: Number(a.currentTime), + opacity: getComputedStyle(element, '::before').opacity, + }; + }); + expect(veil).toMatchObject({playState: 'finished', opacity: '1'}); + }); +}); + test.describe('holding', () => { test('a sample at an end reports the time it was read at', async ({page}) => { await fixture(page); @@ -961,6 +2157,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 +2306,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 +2379,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'); @@ -1144,45 +2484,64 @@ test.describe('animation state', () => { // A 300 ms delay plays last when going backward: the curve starts at once. let watch = await watchAnimations(box); - let readyAt = await box.evaluate(async (el, keyframes) => { + let begunAt = await box.evaluate(async (el, keyframes) => { const animation = el.animate(keyframes, {duration: 400, delay: 300}); animation.reverse(); await animation.ready; - return performance.timeOrigin + performance.now(); + // When it began, by its own clock read at one instant: a run going + // backward starts at its end, so its current time has come down from + // there by as much as the timeline has moved since (through the rate). + // performance.now() read after `ready` drifts later under load. + const end = Number(animation.effect?.getComputedTiming().endTime ?? 0); + return ( + performance.timeOrigin + + Number(document.timeline.currentTime) - + (end - Number(animation.currentTime)) / Math.abs(animation.playbackRate) + ); }, frames); const [delayed] = await watch.started(); - expect(Math.abs(delayed.from - readyAt)).toBeLessThan(50); + expect(Math.abs(delayed.from - begunAt)).toBeLessThan(50); expect(delayed.to - delayed.from).toBeCloseTo(400, 0); await box.evaluate(el => el.getAnimations().forEach(a => a.finish())); // A short one that ended before the look keeps its curve inside its life. watch = await watchAnimations(box); - readyAt = await box.evaluate(async (el, keyframes) => { + begunAt = await box.evaluate(async (el, keyframes) => { const animation = el.animate(keyframes, {duration: 60}); animation.reverse(); await animation.ready; - return performance.timeOrigin + performance.now(); + const end = Number(animation.effect?.getComputedTiming().endTime ?? 0); + return ( + performance.timeOrigin + + Number(document.timeline.currentTime) - + (end - Number(animation.currentTime)) / Math.abs(animation.playbackRate) + ); }, frames); await page.waitForTimeout(200); const [ended] = await watch.started(); expect(ended.finishedAt).not.toBeNull(); - expect(Math.abs(ended.from - readyAt)).toBeLessThan(50); + expect(Math.abs(ended.from - begunAt)).toBeLessThan(50); expect(ended.to).toBeLessThanOrEqual((ended.finishedAt ?? 0) + 1); // One the page cancels when it ends keeps its start. watch = await watchAnimations(box); - readyAt = await box.evaluate(async (el, keyframes) => { + begunAt = await box.evaluate(async (el, keyframes) => { const animation = el.animate(keyframes, {duration: 60}); animation.addEventListener('finish', () => animation.cancel(), { once: true, }); animation.reverse(); await animation.ready; - return performance.timeOrigin + performance.now(); + const end = Number(animation.effect?.getComputedTiming().endTime ?? 0); + return ( + performance.timeOrigin + + Number(document.timeline.currentTime) - + (end - Number(animation.currentTime)) / Math.abs(animation.playbackRate) + ); }, frames); await page.waitForTimeout(200); const [cancelled] = await watch.started(); - expect(Math.abs(cancelled.from - readyAt)).toBeLessThan(50); + expect(Math.abs(cancelled.from - begunAt)).toBeLessThan(50); expect(cancelled.to - cancelled.from).toBeCloseTo(60, 0); // Read right after finish(), before the finish event is delivered: the @@ -1429,6 +2788,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 +3001,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..73ba38af0d61f 100644 --- a/internal/interaction-harness/src/index.ts +++ b/internal/interaction-harness/src/index.ts @@ -12,10 +12,14 @@ * 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'; +export * from './webInput'; 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/touch.ts b/internal/interaction-harness/src/touch.ts index 1c16c4b1f82e0..3a5803d1e6cef 100644 --- a/internal/interaction-harness/src/touch.ts +++ b/internal/interaction-harness/src/touch.ts @@ -265,6 +265,13 @@ export interface InputRecord { readonly x?: number; readonly y?: number; readonly touches?: number; + /** A pointer event's pressure (a pen's, 0–1). */ + readonly pressure?: number; + /** A wheel step's deltas, mode and Control key (webInput.ts). */ + readonly deltaX?: number; + readonly deltaY?: number; + readonly deltaMode?: number; + readonly ctrlKey?: boolean; readonly target: string; } @@ -276,20 +283,21 @@ const INPUT_LOG_SCRIPT = `(() => { ? node.tagName.toLowerCase() + (node.id ? '#' + node.id : '') + (node.getAttribute('aria-label') ? '[' + node.getAttribute('aria-label') + ']' : '') : String(node && node.nodeName); const types = ['pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'touchstart', 'touchmove', - 'touchend', 'touchcancel', 'click', 'contextmenu', 'gotpointercapture', 'lostpointercapture']; + 'touchend', 'touchcancel', 'click', 'contextmenu', 'gotpointercapture', 'lostpointercapture', 'wheel']; for (const type of types) { // Bubble phase on window, so defaultPrevented reflects the page's own handlers. window.addEventListener(type, event => { const record = {type, timeStamp: event.timeStamp, isTrusted: event.isTrusted, cancelable: event.cancelable, defaultPrevented: event.defaultPrevented, target: describe(event.target)}; - if ('pointerId' in event) Object.assign(record, {pointerId: event.pointerId, pointerType: event.pointerType, x: event.clientX, y: event.clientY}); + if ('pointerId' in event) Object.assign(record, {pointerId: event.pointerId, pointerType: event.pointerType, x: event.clientX, y: event.clientY, pressure: event.pressure}); + if (type === 'wheel') Object.assign(record, {deltaX: event.deltaX, deltaY: event.deltaY, deltaMode: event.deltaMode, ctrlKey: event.ctrlKey, x: event.clientX, y: event.clientY}); if (event.touches) Object.assign(record, {touches: event.touches.length, x: event.changedTouches[0] && event.changedTouches[0].clientX, y: event.changedTouches[0] && event.changedTouches[0].clientY}); log.push(record); }, {passive: true}); } })()`; -/** Records every pointer/touch/click the page receives (install before navigation). */ +/** Records every pointer, touch, click and wheel step the page receives (install before navigation). */ export async function installInputLog(page: Page): Promise { await page.addInitScript(INPUT_LOG_SCRIPT); } 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/interaction-harness/src/webInput.ts b/internal/interaction-harness/src/webInput.ts new file mode 100644 index 0000000000000..267b4d7a02503 --- /dev/null +++ b/internal/interaction-harness/src/webInput.ts @@ -0,0 +1,250 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file webInput.ts + * @input Uses a Playwright `Page` (Chromium or WebKit) + * @output `webInputDriver(page)`: a wheel step (`wheel({x, y, dx, dy, ctrl})`) + * and a pen stroke (`pen(points)`) as REAL engine input, for proofs that + * the same motion works for every pointer, not only a finger + * (`spec:AST-100` FR4). + * @position The non-touch half of the input drivers; touch.ts is the touch + * half and owns the input log both are read through. Untrusted DOM events + * are not input (a component can tell them apart with `isTrusted`), so both + * go through the engine's own input pipeline. + * + * Chromium: CDP `Input.dispatchMouseEvent`. + * - A wheel step is a `mouseWheel` event at (x, y). Chromium divides the + * deltas it delivers by the device scale factor times the visual viewport's + * scale, so the driver multiplies them back: the page receives exactly `dx` + * and `dy` CSS px, in pixel mode (`deltaMode` 0). `ctrl` holds Control, as a + * trackpad pinch arrives. On a page whose wheel listeners are all passive + * (every page with the input log), Chromium answers the dispatch at once + * and delivers the step to the page afterwards, so `wheel` waits, through a + * one-shot passive listener, until the page has the step. + * - A pen stroke is pressed at its first point, moved through every point and + * released at the last, with `pointerType: 'pen'`, a pressure and an + * optional tilt, each event stamped with its scripted time: the page + * receives trusted pen pointer events (and the compatibility mouse events) + * with those timestamps. The stroke starts once the page has presented two + * frames: the press goes out with no page round trip, so right after a + * navigation it could carry the previous document's page scale (about:blank + * scales a press at 100 px to 41 px in the phone project). + * + * WebKit (Playwright's Linux build): `page.mouse.wheel` in a desktop context + * (`isMobile: false`, `hasTouch: false`), waiting the same way. The step + * moves the mouse to (x, y) first (a `pointermove`) and holds Control as a key, + * which Chromium's step does neither. WebKit's mobile emulation has no + * wheel input, and Playwright has no pen for WebKit: both throw, naming the + * reason, so a proof skips on the driver's flags instead. + * + * SYNC: Keep the engine limits above equal to the README's table and to the + * harness self-test (../src/harness.interaction.browser.spec.ts). + */ + +import type {CDPSession, JSHandle, Page} from '@playwright/test'; +import type {Engine} from './touch'; + +/** One wheel step: the page receives exactly `dx`, `dy` CSS px. */ +export interface WheelInput { + readonly x: number; + readonly y: number; + readonly dx?: number; + readonly dy?: number; + /** Hold Control during the step (a trackpad pinch arrives as a ctrl wheel). */ + readonly ctrl?: boolean; +} + +/** A point of a pen stroke. */ +export interface PenPoint { + readonly x: number; + readonly y: number; + /** Ms after the stroke's first point. */ + readonly t: number; + /** 0–1 (default 0.5) while the pen touches. */ + readonly pressure?: number; + /** Degrees, -90–90 (default 0). */ + readonly tiltX?: number; + readonly tiltY?: number; +} + +export interface WebInputDriver { + readonly engine: Engine; + /** Whether `wheel` works in this page (WebKit's mobile emulation has none). */ + readonly wheels: boolean; + /** Whether `pen` works in this page (Chromium only). */ + readonly pens: boolean; + wheel(input: WheelInput): Promise; + /** Presses at the first point, moves through all of them, releases at the last; paced on the wall clock. */ + pen(points: readonly PenPoint[]): Promise; +} + +/** Why a proof skips when the driver has no wheel in this page. */ +export const WHEEL_SKIP = + "WebKit's mobile emulation has no wheel input: run wheel proofs in a desktop context"; +/** Why a proof skips when the driver has no pen. */ +export const PEN_SKIP = + 'Playwright has no pen input for WebKit: pen proofs run in Chromium'; + +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +/** How long `wheel` waits for the page to receive its step. */ +const WHEEL_DELIVERY_MS = 2000; + +/** + * Arms a one-shot passive capture listener for the page's next wheel step, + * before the step is dispatched. Passive, so the page's own listeners keep + * deciding whether the engine waits for it. (The promise sits in an object: + * a handle to a bare promise would wait for it to settle.) + */ +function armWheel(page: Page): Promise}>> { + return page.evaluateHandle(() => ({ + received: new Promise(resolve => { + window.addEventListener('wheel', () => resolve(), { + capture: true, + once: true, + passive: true, + }); + }), + })); +} + +/** Waits until the armed listener has seen the step; throws past the limit. */ +async function untilReceived( + page: Page, + armed: JSHandle<{received: Promise}>, +): Promise { + const received = await page.evaluate( + ([box, ms]) => + Promise.race([ + box.received.then(() => true), + new Promise(resolve => setTimeout(() => resolve(false), ms)), + ]), + [armed, WHEEL_DELIVERY_MS] as const, + ); + await armed.dispose(); + if (!received) { + throw new Error( + `webInputDriver: the page did not receive the wheel step within ${WHEEL_DELIVERY_MS} ms (is the point inside the viewport, over the main document?)`, + ); + } +} + +async function chromiumWebInput(page: Page): Promise { + const cdp: CDPSession = await page.context().newCDPSession(page); + return { + engine: 'chromium', + wheels: true, + pens: true, + async wheel({x, y, dx = 0, dy = 0, ctrl = false}) { + const scale = await page.evaluate( + () => window.devicePixelRatio * (window.visualViewport?.scale ?? 1), + ); + const armed = await armWheel(page); + await cdp.send('Input.dispatchMouseEvent', { + type: 'mouseWheel', + x, + y, + deltaX: dx * scale, + deltaY: dy * scale, + modifiers: ctrl ? 2 : 0, + }); + await untilReceived(page, armed); + }, + async pen(points) { + if (points.length === 0) { + return; + } + // Two presented frames first: the press reaches the compositor with no + // page round trip, and right after a navigation it could still carry + // the previous document's page scale. The harness's own frames, not a + // frozen timer gate's (story.ts). + await page.evaluate( + () => + new Promise(resolve => { + const gate = ( + window as unknown as { + __harnessTimerGate?: {frame?: typeof requestAnimationFrame}; + } + ).__harnessTimerGate; + const frame = + gate?.frame ?? window.requestAnimationFrame.bind(window); + frame(() => frame(() => resolve())); + }), + ); + const startWall = Date.now(); + const startStamp = Date.now() / 1000; + const events = [ + {type: 'mousePressed' as const, point: points[0]}, + ...points.slice(1).map(point => ({type: 'mouseMoved' as const, point})), + {type: 'mouseReleased' as const, point: points[points.length - 1]}, + ]; + for (const {type, point} of events) { + const wait = startWall + point.t - Date.now(); + if (wait > 0) { + await sleep(wait); + } + await cdp.send('Input.dispatchMouseEvent', { + type, + x: point.x, + y: point.y, + button: 'left', + buttons: type === 'mouseReleased' ? 0 : 1, + clickCount: type === 'mouseMoved' ? 0 : 1, + pointerType: 'pen', + force: type === 'mouseReleased' ? 0 : (point.pressure ?? 0.5), + tiltX: point.tiltX ?? 0, + tiltY: point.tiltY ?? 0, + timestamp: startStamp + point.t / 1000, + }); + } + }, + }; +} + +async function webkitWebInput(page: Page): Promise { + // Playwright refuses a wheel in a WebKit context that emulates a phone: read + // the option it reads, the context's `isMobile`. + const mobile = + (page.context() as unknown as {_options?: {isMobile?: boolean}})._options + ?.isMobile === true; + return { + engine: 'webkit', + wheels: !mobile, + pens: false, + async wheel({x, y, dx = 0, dy = 0, ctrl = false}) { + if (mobile) { + throw new Error(`webInputDriver: ${WHEEL_SKIP}`); + } + await page.mouse.move(x, y); + if (ctrl) { + await page.keyboard.down('Control'); + } + try { + const armed = await armWheel(page); + await page.mouse.wheel(dx, dy); + await untilReceived(page, armed); + } finally { + if (ctrl) { + await page.keyboard.up('Control'); + } + } + }, + async pen() { + throw new Error(`webInputDriver: ${PEN_SKIP}`); + }, + }; +} + +/** Wheel and pen input for the page's engine. Firefox is not supported (no project). */ +export async function webInputDriver(page: Page): Promise { + const name = page.context().browser()?.browserType().name(); + if (name === 'chromium') { + return chromiumWebInput(page); + } + if (name === 'webkit') { + return webkitWebInput(page); + } + throw new Error( + `webInputDriver: no wheel or pen input path for ${name ?? 'this browser'}`, + ); +} diff --git a/internal/test-utils/src/setup.ts b/internal/test-utils/src/setup.ts index 440b32ff22b3c..991bb056f0816 100644 --- a/internal/test-utils/src/setup.ts +++ b/internal/test-utils/src/setup.ts @@ -12,6 +12,8 @@ /// import '@testing-library/jest-dom/vitest'; import {configure} from '@testing-library/react'; +import {afterEach} from 'vitest'; +import {__resetClickGuardForTest} from '../../../packages/core/src/utils/clickGuard'; // Text queries (getByText/findByText/…) target VISIBLE text. Astryx's // `useAnnounce` renders a visually-hidden aria-live region @@ -25,6 +27,15 @@ import {configure} from '@testing-library/react'; // Keeps the jsdom defaults (script, style). configure({defaultIgnore: 'script, style, [data-astryx-live-region]'}); +// The click guard (packages/core/src/utils/clickGuard.ts) is armed per +// document by a gesture that already acted and disarms itself 400 ms later. +// A test that ends inside that window would leave the timer to fire after +// the environment tears its window down, during a later file. Disarm every +// guard as each test ends. +afterEach(() => { + __resetClickGuardForTest(); +}); + // Polyfill for matchMedia (not supported in jsdom). // // `(hover: hover)` reports TRUE: jsdom models a desktop browser driven by a 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 ( +
+
row
+
+ ); +} 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/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs index 0c2477d56c29a..c550849f082ae 100644 --- a/packages/cli/api/component/_adapter.mjs +++ b/packages/cli/api/component/_adapter.mjs @@ -31,6 +31,7 @@ import { docStem, findComponentReadme, findComponentSource, + findExportedComponentSource, findExternalComponentDoc, findIntegrationComponent, integrationMemberEntry, @@ -431,13 +432,14 @@ export function legacyExternalKeeps(cwd, dirName, owners) { /** * The core source file for `dirName` (the no-scope `--source` path reads core - * directly — it does NOT fall back to externals or fuzzy search). + * directly — it does NOT fall back to externals or fuzzy search). Only the + * file that exports the component or hook of that exact name counts. * @param {string} coreDir * @param {string} dirName * @returns {string | null} */ export function resolveCoreSourcePath(coreDir, dirName) { - return findComponentSource(coreDir, dirName); + return findExportedComponentSource(coreDir, dirName); } /** @@ -487,7 +489,14 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) { results.length > topTied.length ? results[topTied.length].score : 0; const gap = topScore - secondScore; - if (topScore >= 90 && topTied.length === 1 && gap >= 20) { + // Names are case-sensitive: a name that matches a component only by + // case (`badge` for Badge) is not that component. It gets the + // suggestion, not the doc. + const caseOnly = + topTied.length === 1 && + topTied[0].name !== dirName && + topTied[0].name.toLowerCase() === dirName.toLowerCase(); + if (!caseOnly && topScore >= 90 && topTied.length === 1 && gap >= 20) { resolvedName = topTied[0].name; readmePath = findComponentReadme(coreDir, resolvedName); resolvedOwnerPackage = CORE_PACKAGE; diff --git a/packages/cli/api/component/component.test.mjs b/packages/cli/api/component/component.test.mjs index d05159b51778a..05a09fdae311c 100644 --- a/packages/cli/api/component/component.test.mjs +++ b/packages/cli/api/component/component.test.mjs @@ -236,17 +236,49 @@ describe('component dispatcher — name resolution', () => { SLOW, ); + // `button`, `switch`, `slider` and `list` are also the names of motion + // tables (motion/uikit/.ts) in core's UIKit work; `list` and `badge` + // match a component (List, Badge) by case alone. + it.each(['button', 'switch', 'slider', 'list', 'badge'])( + 'is case-SENSITIVE: the lowercased name %s is unknown', + async name => { + let err; + try { + await component(name, {cwd}); + } catch (e) { + err = e; + } + expect(err).toBeDefined(); + expect(err.code).toBe('ERR_UNKNOWN_COMPONENT'); + }, + SLOW, + ); + it( - 'is case-SENSITIVE: a lowercased name is unknown', + 'suggests the component a lowercased name matches by case', async () => { let err; try { - await component('button', {cwd}); + await component('badge', {cwd}); } catch (e) { err = e; } - expect(err).toBeDefined(); expect(err.code).toBe('ERR_UNKNOWN_COMPONENT'); + expect(err.suggestions?.[0]?.name).toBe('Badge'); + }, + SLOW, + ); + + it( + 'reads no source for a lowercased name, even where a module has its spelling', + async () => { + let err; + try { + await component('button', {cwd, source: true}); + } catch (e) { + err = e; + } + expect(err?.code).toBe('ERR_NO_SOURCE'); }, SLOW, ); diff --git a/packages/cli/clients/cli/commands/component.test.mjs b/packages/cli/clients/cli/commands/component.test.mjs index e2cd910265a39..9f2bf3c695532 100644 --- a/packages/cli/clients/cli/commands/component.test.mjs +++ b/packages/cli/clients/cli/commands/component.test.mjs @@ -253,7 +253,12 @@ describe('findComponentReadme', () => { const srcDir = path.join(tmpDir, 'src'); const stackDir = path.join(srcDir, 'Stack'); fs.mkdirSync(stackDir, {recursive: true}); - fs.writeFileSync(path.join(stackDir, 'XDSStackItem.tsx'), ''); + // The sub-component's file exports it: only a file that exports the name + // counts. + fs.writeFileSync( + path.join(stackDir, 'XDSStackItem.tsx'), + 'export function XDSStackItem() {}', + ); fs.writeFileSync( path.join(stackDir, 'Stack.doc.mjs'), 'export const docs = {}', diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjs index c1e6ff3f5bb35..351f35e15bed5 100644 --- a/packages/cli/foundation/discovery/component-discovery.mjs +++ b/packages/cli/foundation/discovery/component-discovery.mjs @@ -544,8 +544,11 @@ export function findComponentReadme(coreDir, name) { } // Sub-component fallback: find the source file, then walk up - // looking for any .doc.mjs in the same or parent directories - const sourcePath = findComponentSource(coreDir, name); + // looking for any .doc.mjs in the same or parent directories. Only a file + // that exports the component or hook `name` counts (see + // findExportedComponentSource): a lowercase module elsewhere in the tree, + // such as a motion table, must not pick up the nearest doc. + const sourcePath = findExportedComponentSource(coreDir, name); if (sourcePath) { let dir = path.dirname(sourcePath); while (dir.startsWith(srcDir)) { @@ -637,6 +640,31 @@ export function findComponentSource(coreDir, name) { return searchDir(srcDir); } +// A name a Core doc documents: a component (PascalCase, as JSX requires of a +// component) or a hook (`use` followed by PascalCase). Matched case for case: +// `button` is not `Button`. +const DOCUMENTED_NAME_RE = /^(?:use)?[A-Z][A-Za-z0-9]*$/; + +/** + * The source file of the component or hook `name`, found anywhere in Core: the + * name must be a component's or a hook's, matched case for case, and the file + * found for it must export it (bare or `XDS`-prefixed). Any other module that + * shares the name's spelling, such as the motion table + * `motion/uikit/button.ts`, is not that component. + * @param {string} coreDir + * @param {string} name + * @returns {string | null} + */ +export function findExportedComponentSource(coreDir, name) { + if (!DOCUMENTED_NAME_RE.test(name)) return null; + const sourcePath = findComponentSource(coreDir, name); + if (sourcePath == null) return null; + return moduleExportsName(sourcePath, name) || + moduleExportsName(sourcePath, `XDS${name}`) + ? sourcePath + : null; +} + /** * Compute the Levenshtein (edit) distance between two strings. * Used for fuzzy-matching component names. Dependency-free. diff --git a/packages/cli/foundation/discovery/component-discovery.test.mjs b/packages/cli/foundation/discovery/component-discovery.test.mjs index 74cab3355c5e6..875cf18c392ed 100644 --- a/packages/cli/foundation/discovery/component-discovery.test.mjs +++ b/packages/cli/foundation/discovery/component-discovery.test.mjs @@ -18,6 +18,7 @@ import { discoverComponents, familyMember, findComponentReadme, + findExportedComponentSource, findComponentSource, resolveImportPath, discoverExternalComponentsGrouped, @@ -229,6 +230,48 @@ describe('familyMember', () => { }); }); +describe('a doc is found only for a component or hook name its source exports', () => { + it('ignores lowercase modules that share a name, and files that do not export it', () => { + const core = mkTmp('as-cd-names-'); + const write = (rel, text) => { + fs.mkdirSync(path.dirname(path.join(core, 'src', rel)), {recursive: true}); + fs.writeFileSync(path.join(core, 'src', rel), text); + }; + write('motion/useAnimator.ts', 'export function useAnimator() {}\n'); + write('motion/useAnimator.doc.mjs', "export const docs = {name: 'useAnimator'};\n"); + // Motion tables beside a doc: modules, not components. + write('motion/uikit/button.ts', 'export const button = {};\n'); + write('motion/uikit/slider.ts', 'export const slider = {};\n'); + write('motion/uikit/switch.ts', 'export const switchTable = {};\n'); + write('Stack/Stack.tsx', 'export function Stack() {}\n'); + write('Stack/Stack.doc.mjs', "export const docs = {name: 'Stack'};\n"); + // A sub-component the parent's folder documents. + write('Stack/StackItem.tsx', 'export function StackItem() {}\n'); + // A PascalCase file that exports no binding of its name. + write('Stack/StackTypes.ts', 'export type StackProps = {gap: number};\n'); + for (const name of ['button', 'slider', 'switch']) { + expect(findComponentReadme(core, name), name).toBeNull(); + expect(findExportedComponentSource(core, name), name).toBeNull(); + } + expect(findComponentReadme(core, 'StackTypes')).toBeNull(); + expect(findComponentReadme(core, 'StackItem')).toBe( + path.join(core, 'src', 'Stack', 'Stack.doc.mjs'), + ); + expect(findExportedComponentSource(core, 'StackItem')).toBe( + path.join(core, 'src', 'Stack', 'StackItem.tsx'), + ); + expect(findComponentReadme(core, 'useAnimator')).toBe( + path.join(core, 'src', 'motion', 'useAnimator.doc.mjs'), + ); + }); + + it('finds no doc for a lowercased name in the real core', () => { + for (const name of ['button', 'list', 'scroll', 'switch', 'slider']) { + expect(findComponentReadme(CORE, name), name).toBeNull(); + } + }); +}); + describe('findComponentReadme / findComponentSource / resolveImportPath', () => { it('finds the doc + source for a top-level component', () => { expect(findComponentReadme(CORE, 'Button')).toMatch(/Button\.doc\.mjs$/); diff --git a/packages/core/package.json b/packages/core/package.json index 8bd491e6273cb..59a7b26167438 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -859,6 +859,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/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs index d0c7c2eacfa3c..e4659769fb800 100644 --- a/packages/core/src/Button/Button.doc.mjs +++ b/packages/core/src/Button/Button.doc.mjs @@ -22,6 +22,7 @@ export const docs = { {guidance: false, description: 'Place more than one primary button in the same view; this dilutes the visual hierarchy.'}, {guidance: false, description: 'Use the destructive variant without a confirmation step for irreversible actions like deleting data.'}, {guidance: false, description: 'Use a button for navigation. If it only takes the user to another page, use a link instead. Buttons are for actions like saving, deleting, or submitting.'}, + {guidance: false, description: "Restyle Button's `::before` (through `xstyle` or a `className` rule) and expect it to hold through a touch press: under a coarse primary pointer, while a press is on or fading, Button paints the press on that pseudo-element (`z-index: -1`, its opacity animated), so your styles merge into the press layer for that moment. At rest Button adds nothing there. Style a child element instead."}, ], accessibility: [ { @@ -407,6 +408,7 @@ export const docsDense = { {guidance: false, description: 'Multiple primary buttons in one view; dilutes hierarchy.'}, {guidance: false, description: 'Destructive without confirmation for irreversible actions.'}, {guidance: false, description: 'Button for navigation; use a link if it only takes the user to another page.'}, + {guidance: false, description: 'xstyle or className on ::before: under a coarse primary pointer it is the touch press layer while a press is on or fading (z-index -1, opacity animated); nothing at rest.'}, ], }, propDescriptions: { diff --git a/packages/core/src/Button/Button.spec.md b/packages/core/src/Button/Button.spec.md index f915b54b4221d..9103ad132b87f 100644 --- a/packages/core/src/Button/Button.spec.md +++ b/packages/core/src/Button/Button.spec.md @@ -37,15 +37,15 @@ system_specs: [spec:AST-005, spec:AST-085, spec:AST-086] ## Contract at a glance -| Area | Contract | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Public contract | None changes. This record states the shipped Button surface: `label`, variant, size, elevation, content mode, loading and `clickAction`, `isInterruptible`, disabled, tooltip, width, form attributes, and link mode. | -| Behavior | A named native ` ); diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts new file mode 100644 index 0000000000000..56e9a35a85f16 --- /dev/null +++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts @@ -0,0 +1,2422 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SegmentedControl.interaction.browser.spec.ts + * @input The built SegmentedControl stories ("Default", "Selection motion"), + * real touch input (Chromium CDP / WebKit's input command) and the + * interaction harness + * @output Interaction and animation proofs for the touch layer: a tap, an + * arrow key and a programmatic change slide the lens (the radiogroup's + * ::before) on UIKit's spring (sampled curve vs the spring) at its resting + * size, the surface lands where the segment paints it + * (pixels), the titles switch at once with no second copy, a change + * mid-flight keeps position and velocity, Reduce Motion drops the travel, + * RTL, the slide keeps moving through a blocked main thread, no Layout or + * Paint per frame, assistive technology sees no extra node; under a finger + * no lift by default and the shared pressed overlay with no dim, the drag, + * the commit at the lift through the item's click (a veto, a parent that + * adopts later), the selected face during a drag, scrolling, text + * selection; a mouse keeps today's control; storyboards. + * @position Browser layer of the SegmentedControl selection motion + * (useSegmentedSelectionMotion.ts); the unit layers are + * useSegmentedSelectionMotion.test.ts and motion/uikit/segmented.test.ts. + * + * The oracles come from the harness (`springStep`, `cubicBezier`): math that + * shares nothing with the code under test, fed the UIKit constants + * (response 0.40 s and damping ratio 0.85 for the slide), read from + * UISegmentedControl on the iOS 26.2 simulator. + */ + +import { + expect, + test, + type Browser, + type BrowserContext, + type Locator, + type Page, +} from '@playwright/test'; +// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned. +import {PNG} from 'pngjs'; +import { + animationStoryboard, + blockMainThread, + busyWindowProof, + castStoryboard, + compareCurve, + countBetween, + freezeTimers, + installLongTaskLog, + installTimerGate, + MARKER_RGB, + openStory, + readLongTasks, + releaseAnimations, + springStep, + startScreencast, + thawTimers, + timeline, + touchDriver, + traceRendering, + trackMarker, + tap as touchTap, + drag as touchDrag, + touchStoryboard, + toTouchEvents, + waitForAnimation, + webInputDriver, + withStorybook, + writeEvidence, + PEN_SKIP, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +/** UIKit's slide, from the constants table (motion/uikit/segmented.ts). */ +const SLIDE = {response: 0.4, dampingFraction: 0.85} as const; +/** How far past the end segments the lens follows a finger. */ +const DRAG_OVERSHOOT = 11; +/** design:reduced-motion DR2: a cross-fade, opacity only, 200 ms or less. */ +const RM_MAX_FADE_MS = 200; + +interface SegmentBox { + value: string; + x: number; + y: number; + width: number; + height: number; +} + +interface Control { + driver: TouchDriver; + /** + * The radiogroup. Its ::before is the lens; under Reduced Motion its + * ::after shows the surface that fades out. + */ + group: Locator; + segment: (value: string) => Locator; + boxes: () => Promise; + tapSegment: (value: string) => Promise; +} + +async function openControl( + page: Page, + storyId = 'core-segmentedcontrol--default', + groupName = 'View mode', + { + direction, + }: { + direction?: 'rtl'; + } = {}, +): Promise { + await installLongTaskLog(page); + if (direction == null) { + await openStory(page, storybook(), storyId); + } else { + // Storybook's highlight module reads the style of every element on each + // DOM insertion; openStory turns it off, and this navigation does the + // same, so frame and long-task proofs measure the control alone. + await page.addInitScript(() => { + ( + globalThis as unknown as {__STORYBOOK_HIGHLIGHT_INITIALIZED?: boolean} + ).__STORYBOOK_HIGHLIGHT_INITIALIZED = true; + }); + // Storybook's direction toolbar (a global, not an arg). + await page.goto( + `${storybook()}/iframe.html?id=${storyId}&viewMode=story&globals=direction:${direction}`, + ); + await page.locator('#storybook-root > *').first().waitFor(); + await page.evaluate(async () => { + await document.fonts.ready; + await new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + }); + } + const driver = await touchDriver(page); + const group = page.getByRole('radiogroup', {name: groupName, exact: true}); + await expect(group).toBeVisible(); + const segment = (value: string) => group.locator(`[data-value="${value}"]`); + // Boxes in the track's padding-box coordinates, the lens's own space. + const boxes = async () => + group.evaluate(track => { + const trackRect = track.getBoundingClientRect(); + return [...track.querySelectorAll('[role="radio"]')].map( + element => { + const rect = element.getBoundingClientRect(); + return { + value: element.dataset.value ?? '', + x: rect.left - trackRect.left - track.clientLeft, + y: rect.top - trackRect.top - track.clientTop, + width: rect.width, + height: rect.height, + }; + }, + ); + }); + const tapSegment = async (value: string) => { + const box = await segment(value).boundingBox(); + if (box == null) { + throw new Error(`no segment ${value}`); + } + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + }; + return {driver, group, segment, boxes, tapSegment}; +} + +/** One of the radiogroup's two layers: the lens or the ::after. */ +type Layer = '::before' | '::after'; + +/** + * A layer's presented geometry, as computed now: laid out on a box and + * scaled around its center, so `center` is its layout center plus its + * translate, and `x` its presented left edge. + */ +async function readLayer( + group: Locator, + layer: Layer = '::before', +): Promise<{ + visible: boolean; + opacity: number; + x: number; + center: number; + width: number; + height: number; + sx: number; + sy: number; +}> { + return group.evaluate((element, pseudo) => { + const style = getComputedStyle(element, pseudo); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + const translate = + style.translate === 'none' ? 0 : parseFloat(style.translate); + const width = parseFloat(style.width) * sx; + const center = + parseFloat(style.left) + parseFloat(style.width) / 2 + translate; + return { + visible: style.visibility === 'visible', + opacity: Number(style.opacity), + x: center - width / 2, + center, + width, + height: parseFloat(style.height) * sy, + sx, + sy, + }; + }, layer); +} + +/** Resolves once the lens is hidden again: the surface handed back. */ +async function expectLensHidden( + control: Control, + timeout = 3000, +): Promise { + await expect + .poll(async () => (await readLayer(control.group)).visible, {timeout}) + .toBe(false); +} + +/** + * The lens's running animations (the radiogroup's ::before), described as + * the harness's `waitForAnimation` describes an element's. + */ +async function waitForLens( + control: Control, + { + minProgressMs = 1, + timeout = 5000, + }: {minProgressMs?: number; timeout?: number} = {}, +): Promise<{from: number; to: number; durationMs: number; easing: string}[]> { + // Installs the harness's curve-end reader and waits for the control to move. + await waitForAnimation(control.group, {minProgressMs, timeout}); + const deadline = Date.now() + timeout; + for (;;) { + const found = await control.group.evaluate((group, minProgress) => { + const curveEnd = ( + window as unknown as {__harnessCurveEnd: (a: Animation) => number} + ).__harnessCurveEnd; + return group + .getAnimations({subtree: true}) + .filter(a => { + const effect = a.effect as KeyframeEffect | null; + return ( + effect?.target === group && + effect.pseudoElement === '::before' && + a.playState === 'running' && + a.startTime != null && + Number(a.currentTime ?? 0) >= minProgress + ); + }) + .map(a => { + const effect = a.effect as KeyframeEffect; + const timing = effect.getComputedTiming(); + const startedAt = performance.timeOrigin + Number(a.startTime); + return { + from: startedAt + (timing.delay ?? 0), + to: startedAt + curveEnd(a), + durationMs: Number(timing.duration ?? 0), + easing: effect.getTiming().easing ?? 'linear', + }; + }); + }, minProgressMs); + if (found.length > 0) { + return found; + } + if (Date.now() > deadline) { + throw new Error('waitForLens: no lens animation started'); + } + await new Promise(resolve => setTimeout(resolve, 4)); + } +} + +/** + * Pauses the lens's running animations (both of the radiogroup's + * pseudo-elements: the lens and its shadow) into the harness's held set, so + * `releaseAnimations` moves exactly them. A pseudo-element has no inline + * style, so the animator holds each value it sets with a finished, filling + * animation, which every running one overrides: those are left alone. + */ +async function holdLens( + control: Control, +): Promise<{easing: string; durationMs: number; pseudo: string}[]> { + return control.group.evaluate(group => { + const held = group.getAnimations({subtree: true}).filter(a => { + const effect = a.effect as KeyframeEffect | null; + return ( + effect?.target === group && + effect.pseudoElement != null && + a.playState !== 'finished' + ); + }); + for (const animation of held) { + animation.pause(); + } + (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld = held; + return held.map(a => ({ + easing: String((a.effect as KeyframeEffect).getTiming().easing), + durationMs: Number(a.effect?.getComputedTiming().duration ?? 0), + pseudo: String((a.effect as KeyframeEffect).pseudoElement), + })); + }); +} + +/** + * The lens's presented geometry at each held time: `x` its translate (the + * center's offset from its layout box's), `center` in the track's + * coordinates, and its presented size. + */ +async function sampleLens( + group: Locator, + times: ReadonlyArray, +): Promise< + { + t: number; + x: number; + center: number; + width: number; + height: number; + visible: boolean; + }[] +> { + return group.evaluate((element, ts) => { + const held = + (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? []; + const base = getComputedStyle(element, '::before'); + const left = parseFloat(base.left); + const width = parseFloat(base.width); + const height = parseFloat(base.height); + return ts.map(t => { + for (const animation of held) { + const end = Number(animation.effect?.getComputedTiming().endTime ?? 0); + animation.currentTime = Math.min(t, end - 0.5); + } + const style = getComputedStyle(element, '::before'); + const x = style.translate === 'none' ? 0 : parseFloat(style.translate); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + return { + t, + x, + center: left + width / 2 + x, + width: width * sx, + height: height * sy, + visible: style.visibility === 'visible', + }; + }); + }, times); +} + +const centerOf = (box: SegmentBox) => box.x + box.width / 2; + +/** + * Records, on the page's clock (epoch ms), each moment a control's lens + * hands its surface back (it is hidden again). The animator's keyframes hold + * the end state for a few seconds past the curve, so an animation's end time + * is not when the slide is over; the hand-back is. + */ +async function recordHandBacks(page: Page): Promise<() => Promise> { + await page.evaluate(() => { + const times: number[] = []; + (window as unknown as {__handBacks: number[]}).__handBacks = times; + const shown = (group: HTMLElement) => + group.style.getPropertyValue('--_segmented-lens-visibility') === + 'visible'; + for (const group of document.querySelectorAll( + '[role="radiogroup"]', + )) { + let visible = shown(group); + new MutationObserver(() => { + const now = shown(group); + if (visible && !now) { + times.push(performance.timeOrigin + performance.now()); + } + visible = now; + }).observe(group, {attributes: true, attributeFilter: ['style']}); + } + }); + return async () => + page.evaluate( + () => (window as unknown as {__handBacks: number[]}).__handBacks, + ); +} + +/** + * Paints the lens in the harness's marker colour, then lets a frame show it: + * the lens has no element to carry the marker chip, and the frames find it by + * its colour. + */ +async function paintLensMarker(control: Control): Promise { + await control.group.evaluate((group, rgb) => { + group.style.setProperty( + '--_segmented-lens-background-color', + `rgb(${rgb.join(', ')})`, + ); + group.style.setProperty('--_segmented-lens-background-image', 'none'); + }, MARKER_RGB); + await control.group.evaluate( + async () => + new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ), + ); +} + +/** The box of one segment; a missing segment is a broken story, not a pass. */ +function boxOf(boxes: ReadonlyArray, value: string): SegmentBox { + const box = boxes.find(b => b.value === value); + if (box == null) { + throw new Error(`no segment "${value}" in ${JSON.stringify(boxes)}`); + } + return box; +} + +test('a tap slides the selected surface to the new segment on UIKit’s spring, at its resting size', async ({ + page, +}, testInfo) => { + const control = await openControl(page); + // Under a finger the segments leave the change to this motion: no CSS + // transition runs a second, main-thread version of it. + for (const value of ['grid', 'list', 'table']) { + await expect(control.segment(value)).toHaveCSS( + 'transition-property', + 'none', + ); + } + const from = boxOf(await control.boxes(), 'grid'); + // Hold the clock still, and each of the lens's animations at its birth, so + // a slow engine cannot reach the hold after the slide has moved on. + await installTimerGate(page); + await holdLensAnimationsAtBirth(page); + await control.tapSegment('table'); + await freezeTimers(page); + const held = await page.evaluate(() => { + (window as unknown as {__restoreAnimate: () => void}).__restoreAnimate(); + return ( + window as unknown as {__harnessHeld: Animation[]} + ).__harnessHeld.map( + a => (a.effect as KeyframeEffect).getComputedTiming().easing, + ); + }); + // Baked curves: the lens's translate and scale; nothing on the ::after (no + // lift, so no shadow). + expect(held.length).toBeGreaterThanOrEqual(2); + expect(held.every(easing => easing === 'linear')).toBe(true); + const samples = await sampleLens(control.group, timeline(600)); + await releaseAnimations(page); + await thawTimers(page); + // The value commits at the lift, as UISegmentedControl's valueChanged does. + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + // Where Table is once its title has its new weight: where the lens aims. + const to = boxOf(await control.boxes(), 'table'); + expect(samples.every(s => s.visible)).toBe(true); + // The center travels on the slide spring... + const center = compareCurve( + samples.map(s => ({t: s.t, value: s.center})), + t => + centerOf(from) + (centerOf(to) - centerOf(from)) * springStep(SLIDE, t), + 0.25, + ); + // ...and the width follows Grid's to Table's on the same spring; nothing + // lifts it (a pressed thumb's lift is a theme's, none by default). + const width = compareCurve( + samples.map(s => ({t: s.t, value: s.width})), + t => from.width + (to.width - from.width) * springStep(SLIDE, t), + 0.25, + ); + const height = compareCurve( + samples.map(s => ({t: s.t, value: s.height})), + () => to.height, + 0.25, + ); + await writeEvidence( + 'curves/segmented-slide', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {from, to, held, samples, center, width, height}, + null, + 1, + ), + }, + testInfo, + ); + expect(center.maxError, JSON.stringify(center.worst)).toBeLessThanOrEqual( + 0.25, + ); + expect(width.maxError, JSON.stringify(width.worst)).toBeLessThanOrEqual(0.25); + expect(height.maxError, JSON.stringify(height.worst)).toBeLessThanOrEqual( + 0.25, + ); + // It lands and hands back. + await expectLensHidden(control); +}); + +test('the surface lands exactly where the segment paints it', async ({ + page, +}) => { + const control = await openControl(page); + // The surfaces are compared, not the titles: text drawn over a composited + // layer (the lens) loses subpixel antialiasing where the platform uses it, + // and gets it back at the hand-back (a desktop Linux runner does; phones + // antialias text in grayscale either way). + await page.addStyleTag({ + content: '[role="radiogroup"] * { color: transparent !important; }', + }); + // Gate timers: the hand-back runs from the slide's completion timer, which + // must wait while the landed frame is photographed. + await installTimerGate(page); + await control.tapSegment('list'); + await waitForLens(control); + await freezeTimers(page); + // The slide runs its course on the compositor; with the + // timers held the hand-back waits, so this is the last frame of the slide: + // the lens carries the surface, the segment's own is hidden. + await page.waitForTimeout(1500); + const landed = await control.group.screenshot({animations: 'allow'}); + expect( + await control.segment('list').evaluate(el => el.style.backgroundColor), + ).toBe('transparent'); + await thawTimers(page); + await expectLensHidden(control); + expect( + await control.segment('list').evaluate(el => el.getAttribute('style')), + ).toBeFalsy(); + const rest = await control.group.screenshot({animations: 'allow'}); + const a = PNG.sync.read(landed); + const b = PNG.sync.read(rest); + expect([a.width, a.height]).toEqual([b.width, b.height]); + // The hand-back is invisible: the same pixels before and after it, but for + // the surface's outline, which each engine snaps to device pixels its own + // way for a composited layer and for a segment's own background (within + // two device pixels). + const edges = await control.group.evaluate(group => { + const ratio = window.devicePixelRatio || 1; + const host = group.getBoundingClientRect(); + const segment = group.querySelector('[data-value="list"]'); + if (segment == null) { + throw new Error('no List segment'); + } + const box = segment.getBoundingClientRect(); + const radius = parseFloat(getComputedStyle(segment).borderTopLeftRadius); + return { + left: (box.left - host.left) * ratio, + right: (box.right - host.left) * ratio, + top: (box.top - host.top) * ratio, + bottom: (box.bottom - host.top) * ratio, + radius: (Number.isFinite(radius) ? radius : 0) * ratio, + }; + }); + const nearEdge = (x: number, y: number) => { + const halfWidth = (edges.right - edges.left) / 2; + const halfHeight = (edges.bottom - edges.top) / 2; + const r = Math.min(edges.radius, halfWidth, halfHeight); + const qx = Math.abs(x - (edges.left + halfWidth)) - (halfWidth - r); + const qy = Math.abs(y - (edges.top + halfHeight)) - (halfHeight - r); + const distance = + Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + + Math.min(Math.max(qx, qy), 0) - + r; + return Math.abs(distance) < 2; + }; + let differing = 0; + for (let y = 0; y < a.height; y++) { + for (let x = 0; x < a.width; x++) { + const i = (y * a.width + x) * 4; + const delta = Math.max( + Math.abs(a.data[i] - b.data[i]), + Math.abs(a.data[i + 1] - b.data[i + 1]), + Math.abs(a.data[i + 2] - b.data[i + 2]), + ); + if (delta > 10 && !nearEdge(x + 0.5, y + 0.5)) { + differing++; + } + } + } + expect(differing).toBe(0); +}); + +test('the titles switch at once with the selection: no second copy of a title is ever mounted', async ({ + page, +}) => { + const control = await openControl(page); + const elements = await control.group.evaluate( + group => group.querySelectorAll('*').length, + ); + await control.tapSegment('table'); + await waitForLens(control); + // Mid-slide, as many elements as at rest, and nothing animates Table's + // title's weight or color: it already shows its selected rendering. (Its + // opacity comes back from the press's dim.) + expect( + await control.group.evaluate(group => group.querySelectorAll('*').length), + ).toBe(elements); + expect( + await control.segment('table').evaluate(element => + element + .getAnimations({subtree: true}) + .flatMap(a => + (a.effect as KeyframeEffect) + .getKeyframes() + .flatMap(k => Object.keys(k)), + ) + .filter(key => key === 'color' || key === 'fontWeight'), + ), + ).toEqual([]); +}); + +test('a second tap mid-flight retargets from what is on screen, keeping its velocity', async ({ + page, +}) => { + const control = await openControl(page); + await control.tapSegment('table'); + await waitForLens(control, {minProgressMs: 60}); + const describe = async () => + control.group.evaluate(async group => { + const animations = group.getAnimations({subtree: true}).filter(a => { + const effect = a.effect as KeyframeEffect; + return ( + effect.target === group && + effect.pseudoElement === '::before' && + a.playState === 'running' && + effect.getKeyframes().length > 2 && + 'translate' in (effect.getKeyframes()[0] ?? {}) + ); + }); + animations.reverse(); + // A call starts when the browser commits it: wait for its start time. + await Promise.all(animations.map(async a => a.ready)); + // The lens's layout box: its center is the reference `x` is measured + // from (it moves when the destination changes). + const style = getComputedStyle(group, '::before'); + const origin = parseFloat(style.left) + parseFloat(style.width) / 2; + return animations.map(a => ({ + startTime: a.startTime as number, + duration: Number(a.effect?.getComputedTiming().duration), + keyframes: (a.effect as KeyframeEffect).getKeyframes().map(k => ({ + offset: k.computedOffset, + x: origin + parseFloat(String(k.translate)), + })), + }))[0]; + }); + const first = await describe(); + await control.tapSegment('list'); + await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true'); + const second = await describe(); + expect(second.startTime).toBeGreaterThan(first.startTime); + // The first curve, read where the second one starts. + const at = ( + curve: typeof first, + time: number, + ): {value: number; slope: number} => { + const offset = (time - curve.startTime) / curve.duration; + const k = curve.keyframes; + for (let i = 0; i + 1 < k.length; i++) { + if (offset <= k[i + 1].offset) { + const span = k[i + 1].offset - k[i].offset; + const f = span === 0 ? 0 : (offset - k[i].offset) / span; + return { + value: k[i].x + (k[i + 1].x - k[i].x) * f, + slope: + span === 0 ? 0 : (k[i + 1].x - k[i].x) / (span * curve.duration), + }; + } + } + return {value: k[k.length - 1].x, slope: 0}; + }; + const old = at(first, second.startTime); + const fresh = at(second, second.startTime + 0.001); + // No jump at the retarget: at most the travel of 2 ms (the animator's clock + // and the document timeline can disagree by a fraction of a frame). + expect(Math.abs(fresh.value - old.value)).toBeLessThan( + Math.max(0.5, Math.abs(old.slope) * 2), + ); + // ...and the velocity carries over (px/ms, within 10 %), read on both + // curves at the instant the second one starts. A segment's slope is the + // curve's velocity at the segment's middle (the browser draws straight + // lines between keyframes), not at its ends: comparing the two segments' + // slopes directly would compare velocities half a segment apart on each + // curve, which differ by the spring's acceleration over those spans. + const velocityAt = (curve: typeof first, time: number): number => { + const k = curve.keyframes; + const middles: {t: number; v: number}[] = []; + for (let i = 0; i + 1 < k.length; i++) { + const span = k[i + 1].offset - k[i].offset; + if (span > 0) { + middles.push({ + t: + curve.startTime + + ((k[i].offset + k[i + 1].offset) / 2) * curve.duration, + v: (k[i + 1].x - k[i].x) / (span * curve.duration), + }); + } + } + // Between the two middles around `time`; before the first one (the second + // curve at its own start), extrapolated from the first two. + const next = middles.findIndex(middle => middle.t >= time); + const j = next === -1 ? middles.length - 1 : Math.max(next, 1); + const a = middles[j - 1]; + const b = middles[j]; + return a.v + ((b.v - a.v) * (time - a.t)) / (b.t - a.t); + }; + const before = velocityAt(first, second.startTime); + const after = velocityAt(second, second.startTime); + expect( + Math.abs(after - before), + JSON.stringify({before, after}), + ).toBeLessThan(Math.abs(before) * 0.1 + 0.02); + // It lands on the second segment's center. + const list = boxOf(await control.boxes(), 'list'); + expect(second.keyframes.at(-1)?.x).toBeCloseTo(centerOf(list), 1); +}); + +test('a change mid-flight paints no press over the lens on the segment it leaves', async ({ + page, +}) => { + const control = await openControl(page); + await control.tapSegment('table'); + // The app changes the selection while the lens is still on its way and the + // tap on Table is still fading (a second touch would end that fade itself). + const paint = await control.group.evaluate(async group => { + const segment = (value: string): HTMLElement => { + const element = group.querySelector( + `[data-value="${value}"]`, + ); + if (element == null) { + throw new Error(`no segment ${value}`); + } + return element; + }; + segment('list').click(); + // The layout effect that retargets has run once the frame is drawn. + await new Promise(resolve => requestAnimationFrame(resolve)); + const table = segment('table'); + const style = getComputedStyle(table); + return { + press: table.getAttribute('data-astryx-press'), + image: style.backgroundImage, + color: style.backgroundColor, + lensVisible: getComputedStyle(group, '::before').visibility === 'visible', + }; + }); + await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true'); + expect(paint.press, 'the tap on Table is still fading').not.toBeNull(); + expect(paint.lensVisible).toBe(true); + // Table paints nothing of its own until the lens lands: its press would + // cover the lens, which sits under the segments' backgrounds. + expect(paint.image).toBe('none'); + expect(paint.color).toBe('rgba(0, 0, 0, 0)'); + // Once the lens lands, Table gets its own styles back. + await expectLensHidden(control); + await expect + .poll(async () => + control.segment('table').evaluate(element => element.style.cssText), + ) + .toBe(''); +}); + +test('an arrow key and a programmatic change slide the selection too', async ({ + page, +}) => { + const control = await openControl( + page, + 'core-segmentedcontrol--selection-motion', + 'Period', + ); + // An arrow key on the focused segment: selection follows focus. + await control.segment('day').focus(); + await page.keyboard.press('ArrowRight'); + await expect(control.segment('week')).toHaveAttribute('aria-checked', 'true'); + const [keyed] = await waitForLens(control); + expect(keyed.easing).toBe('linear'); + await releaseAnimations(page, {finish: true}); + // A change made by the app (the button sets the value from outside). + const button = page.getByRole('button', {name: 'Next period'}); + const box = await button.boundingBox(); + if (box == null) { + throw new Error('no button'); + } + await control.driver.tap({ + x: box.x + box.width / 2, + y: box.y + box.height / 2, + }); + await expect(control.segment('month')).toHaveAttribute( + 'aria-checked', + 'true', + ); + const animations = await waitForLens(control); + expect(animations.length).toBeGreaterThan(0); +}); + +test('Reduce Motion (design:reduced-motion): no travel or scale; the old surface fades out where it is as the new one fades in, opacity only, in 200 ms or less', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const control = await openControl(page); + // Grid where it rests before the tap (the surface that fades out there); + // Table once its title has its new weight (where the lens fades in). + const grid = boxOf(await control.boxes(), 'grid'); + const {samples, titleFades} = await sampleReducedMotionChange(page, control); + const boxes = await control.boxes(); + const table = boxOf(boxes, 'table'); + // Over in 200 ms or less (DR2); the titles switch at once. + const fadeEnd = fadeEndOf(samples); + expect(fadeEnd).toBeGreaterThan(0); + expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS); + expect(samples[samples.length - 1].entering?.opacity).toBe(1); + // No title cross-fades; the pressed title's dim fades on the same clock. + for (const duration of titleFades) { + expect(duration).toBeLessThanOrEqual(RM_MAX_FADE_MS); + } + for (const {t, entering, leaving} of samples) { + const label = JSON.stringify({t, entering, leaving}); + expect(entering, label).not.toBeNull(); + // The new surface: at Table from the first frame, full size; only its + // opacity changes (DR1). + expect(Math.abs((entering?.x ?? 0) - table.x), label).toBeLessThan(0.5); + expect(Math.abs((entering?.width ?? 0) - table.width), label).toBeLessThan( + 0.5, + ); + expect(entering?.sx, label).toBe(1); + expect(entering?.sy, label).toBe(1); + // The old surface, while it shows: at Grid, full size. + if (leaving != null && leaving.opacity > 0.001) { + expect(Math.abs(leaving.x - grid.x), label).toBeLessThan(0.5); + expect(Math.abs(leaving.width - grid.width), label).toBeLessThan(0.5); + expect(leaving.sx, label).toBe(1); + // One surface's worth of paint between the two. + expect( + Math.abs((entering?.opacity ?? 0) + leaving.opacity - 1), + label, + ).toBeLessThan(0.02); + } + } + expect(samples[0].leaving?.opacity ?? 0).toBeGreaterThan(0.9); + expect(samples[0].entering?.opacity ?? 1).toBeLessThan(0.1); + // Then the segment paints its own surface again, and the leaving surface + // is gone. + await expectLensHidden(control); + expect((await readLayer(control.group, '::after')).visible).toBe(false); + await expect(control.segment('table')).not.toHaveCSS( + 'background-color', + 'rgba(0, 0, 0, 0)', + ); +}); + +test('Reduce Motion: a theme’s durations cannot lengthen the fade or bring back travel (design:reduced-motion DR4)', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const control = await openControl(page); + // A theme's motion is its duration scale; a slow one changes nothing here. + await page.evaluate(() => { + const root = document.documentElement.style; + for (const name of ['fast', 'medium', 'slow']) { + for (const suffix of ['', '-min', '-max']) { + root.setProperty(`--duration-${name}${suffix}`, '1200ms'); + } + } + }); + const {samples, titleFades} = await sampleReducedMotionChange(page, control); + const fadeEnd = fadeEndOf(samples); + expect(fadeEnd).toBeGreaterThan(0); + expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS); + // No visible surface ever moves, scales or resizes. + const first = samples[0]; + for (const {t, entering, leaving} of samples) { + const label = JSON.stringify({t, entering, leaving}); + expect(entering?.x, label).toBe(first.entering?.x); + expect(entering?.width, label).toBe(first.entering?.width); + expect(entering?.sx, label).toBe(1); + if (leaving != null && leaving.opacity > 0.001) { + expect(leaving.x, label).toBe(first.leaving?.x); + expect(leaving.sx, label).toBe(1); + } + } + // No title cross-fades; the pressed title's dim fades on the same clock. + for (const duration of titleFades) { + expect(duration).toBeLessThanOrEqual(RM_MAX_FADE_MS); + } +}); + +interface SurfaceSample { + opacity: number; + sx: number; + sy: number; + x: number; + width: number; +} + +/** + * Taps Table under Reduced Motion with the lens's animations held from + * their birth, and reads both surfaces (the lens fading in, the ::after fading + * out) every 8 ms of their animations, and the title fades' durations. + */ +async function sampleReducedMotionChange( + page: Page, + control: Control, + act: () => Promise = async () => control.tapSegment('table'), +): Promise<{ + samples: { + t: number; + entering: SurfaceSample | null; + leaving: SurfaceSample | null; + }[]; + titleFades: number[]; +}> { + await installTimerGate(page); + await holdLensAnimationsAtBirth(page); + await act(); + await expect + .poll(async () => + page.evaluate( + () => + (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld + .length, + ), + ) + .toBeGreaterThan(1); + await freezeTimers(page); + await page.evaluate(() => { + (window as unknown as {__restoreAnimate: () => void}).__restoreAnimate(); + }); + const samples = await control.group.evaluate(group => { + const held = (window as unknown as {__harnessHeld: Animation[]}) + .__harnessHeld; + const read = (pseudo: '::before' | '::after') => { + const style = getComputedStyle(group, pseudo); + if (style.visibility !== 'visible') { + return null; + } + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + return { + opacity: Number(style.opacity), + sx, + sy, + x: + (parseFloat(style.left) || 0) + + (style.translate === 'none' ? 0 : parseFloat(style.translate)), + width: parseFloat(style.width), + }; + }; + const out = []; + for (let t = 0; t <= 1000; t += 8) { + for (const animation of held) { + const animationEnd = Number( + animation.effect?.getComputedTiming().endTime ?? 0, + ); + animation.currentTime = Math.min(t, Math.max(0, animationEnd - 0.5)); + } + out.push({ + t, + entering: read('::before'), + leaving: read('::after'), + }); + } + return out; + }); + const titleFades = await control.group.evaluate(group => + [...group.querySelectorAll('[data-segment-title]')].flatMap(element => + element + .getAnimations() + .map(a => Number(a.effect?.getComputedTiming().duration)), + ), + ); + await releaseAnimations(page); + await thawTimers(page); + return {samples, titleFades}; +} + +/** The last sampled time either surface's opacity is still on its way. */ +function fadeEndOf( + samples: { + t: number; + entering: SurfaceSample | null; + leaving: SurfaceSample | null; + }[], +): number { + const last = samples[samples.length - 1]; + return Math.max( + 0, + ...samples + .filter( + ({entering, leaving}) => + Math.abs((entering?.opacity ?? 0) - (last.entering?.opacity ?? 0)) > + 0.002 || + Math.abs((leaving?.opacity ?? 0) - (last.leaving?.opacity ?? 0)) > + 0.002, + ) + .map(({t}) => t), + ); +} + +/** + * Pauses every animation started on the lens (the radiogroup's pseudo-elements + * it) the moment it is created, into the harness's held set; + * `__restoreAnimate` puts `Element.animate` back. + */ +async function holdLensAnimationsAtBirth(page: Page): Promise { + await page.evaluate(() => { + const original = Element.prototype.animate; + const held: Animation[] = []; + const w = window as unknown as { + __harnessHeld: Animation[]; + __restoreAnimate: () => void; + }; + w.__harnessHeld = held; + w.__restoreAnimate = () => { + Element.prototype.animate = original; + }; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ): Animation { + const animation = original.apply(this, args); + const [, options] = args; + if ( + this.getAttribute('role') === 'radiogroup' && + typeof options === 'object' && + options?.pseudoElement != null + ) { + animation.pause(); + held.push(animation); + } + return animation; + }; + }); +} + +test('with a mouse a click selects with the theme’s color transition and shows no lens', async ({ + browser, +}) => { + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 1024, height: 768}, + }); + try { + const page = await context.newPage(); + await openStory(page, storybook(), 'core-segmentedcontrol--default'); + // This context's pointer is fine (a context without touch can still + // match a coarse one). + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const group = page.getByRole('radiogroup', { + name: 'View mode', + exact: true, + }); + await expect(group).toBeVisible(); + // The lens shows nothing (no pseudo-element, or a hidden one) and no + // custom property is written on the radiogroup. + const noLens = async () => + group.evaluate(element => { + const lens = getComputedStyle(element, '::before'); + return ( + (lens.content === 'none' || + lens.content === 'normal' || + lens.visibility === 'hidden') && + !element.getAttribute('style')?.includes('--_segmented') + ); + }); + expect(await noLens()).toBe(true); + await expect(group.locator('[data-value="list"]')).toHaveCSS( + 'transition-property', + 'color, background-color, box-shadow', + ); + await group.locator('[data-value="table"]').click(); + await expect(group.locator('[data-value="table"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + expect(await noLens()).toBe(true); + } finally { + await context.close(); + } +}); + +test('the slide plays UISegmentedControl’s measured spring, an internal motion role: no theme setting retunes it', async ({ + page, +}) => { + const control = await openControl(page); + // Neither the variable a theme role once had nor a slow duration scale + // changes the slide. + await page.evaluate(() => { + const root = document.documentElement.style; + root.setProperty('--motion-segmented-control-selection-spring', '0.25s 0'); + for (const name of ['fast', 'medium', 'slow']) { + root.setProperty(`--duration-${name}`, '1200ms'); + } + }); + const from = boxOf(await control.boxes(), 'grid'); + await control.tapSegment('table'); + await waitForLens(control); + await holdLens(control); + const samples = await sampleLens(control.group, timeline(400)); + await releaseAnimations(page); + // Where Table is once its title has its new weight: where the lens aims. + const to = boxOf(await control.boxes(), 'table'); + const fit = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.center})), + t => + centerOf(from) + (centerOf(to) - centerOf(from)) * springStep(SLIDE, t), + 0.25, + ); + expect(fit.maxError, JSON.stringify(fit.worst)).toBeLessThanOrEqual(0.25); + // ...not the spring the variable names. + const variable = {response: 0.25, dampingFraction: 1} as const; + const other = compareCurve( + samples.map(sample => ({t: sample.t, value: sample.center})), + t => + centerOf(from) + + (centerOf(to) - centerOf(from)) * springStep(variable, t), + 0.25, + ); + expect(other.maxError).toBeGreaterThan(5); +}); + +test('RTL: the surface slides toward the tapped segment', async ({page}) => { + const control = await openControl( + page, + 'core-segmentedcontrol--default', + 'View mode', + {direction: 'rtl'}, + ); + const grid = boxOf(await control.boxes(), 'grid'); + await control.tapSegment('table'); + await waitForLens(control); + await holdLens(control); + const [start, end] = await sampleLens(control.group, [0, 2000]); + // Where Table is once its title has its new weight. + const table = boxOf(await control.boxes(), 'table'); + // The first segment is on the right in RTL. + expect(grid.x).toBeGreaterThan(table.x); + expect(start.center).toBeCloseTo(centerOf(grid), 1); + expect(end.center).toBeCloseTo(centerOf(table), 1); + // On screen, not only in the numbers: held at its last frame, the lens + // covers the tapped segment exactly (its box in viewport pixels). + const [lensBox, tableBox] = await Promise.all([ + control.group.evaluate(group => { + const style = getComputedStyle(group, '::before'); + const host = group.getBoundingClientRect(); + const translate = + style.translate === 'none' ? 0 : parseFloat(style.translate); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + const width = parseFloat(style.width); + const height = parseFloat(style.height); + const left = host.left + group.clientLeft + parseFloat(style.left); + const top = host.top + group.clientTop + parseFloat(style.top); + return { + x: left + width / 2 + translate - (width * sx) / 2, + y: top + height / 2 - (height * sy) / 2, + width: width * sx, + height: height * sy, + }; + }), + control.segment('table').boundingBox(), + ]); + await releaseAnimations(page); + expect(tableBox).not.toBeNull(); + for (const key of ['x', 'y', 'width', 'height'] as const) { + expect( + Math.abs(lensBox[key] - (tableBox?.[key] ?? NaN)), + `${key}: ${JSON.stringify({lensBox, tableBox})}`, + ).toBeLessThan(0.5); + } +}); + +test('Reduce Motion: a drag leaves the lens parked, commits at the lift, and the selection cross-fades there (design:reduced-motion: a touch release fades)', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const control = await openControl(page); + const grid = boxOf(await control.boxes(), 'grid'); + const selections = await recordSelections(control.group); + const parked: boolean[] = []; + let liftAt = 0; + const {samples} = await sampleReducedMotionChange(page, control, async () => { + const played = await control.driver.play( + touchDrag( + await clientCenter(control, 'grid'), + await clientCenter(control, 'table'), + {durationMs: 400, restMs: 100}, + ), + { + onEvent: async step => { + if (step.type === 'touchMove') { + // No lift, no chase: no lens, the selected segment paints itself. + parked.push(!(await presentedNow(control)).visible); + } + }, + }, + ); + liftAt = played.find(event => event.type === 'touchEnd')?.dispatchedAt ?? 0; + }); + expect(parked.length).toBeGreaterThan(5); + expect(parked.every(Boolean)).toBe(true); + // The segment under the finger at the lift, once. + const changes = await selections(); + expect(changes.map(change => change.value)).toEqual(['table']); + expect(changes[0].at).toBeGreaterThanOrEqual(liftAt - 5); + // Then it cross-fades: the lens fades in on Table (where Table is with its + // new title weight), full size and still, while the ::after fades out on + // Grid, in 200 ms or less (DR1, DR2). + const table = boxOf(await control.boxes(), 'table'); + const fadeEnd = fadeEndOf(samples); + expect(fadeEnd).toBeGreaterThan(0); + expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS); + for (const {t, entering, leaving} of samples) { + const label = JSON.stringify({t, entering, leaving}); + expect(Math.abs((entering?.x ?? 0) - table.x), label).toBeLessThan(0.5); + expect(entering?.sx, label).toBe(1); + if (leaving != null && leaving.opacity > 0.001) { + expect(Math.abs(leaving.x - grid.x), label).toBeLessThan(0.5); + expect(leaving.sx, label).toBe(1); + } + } + await expectLensHidden(control); +}); + +test('the slide 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 control = await openControl(page); + const cast = await startScreencast(page); + await control.tapSegment('table'); + // Running and composited before the block. + const [slide] = await waitForLens(control, {minProgressMs: 16}); + // The lens has no element to carry the harness's marker chip: paint the + // lens itself in the marker colour for the frames to find it. + await paintLensMarker(control); + const block = await blockMainThread(page, 500); + await page.waitForTimeout(250); + const castFrames = await cast.stop(); + const tracked = await trackMarker(page, castFrames); + const proof = busyWindowProof( + tracked, + {from: block.from, to: Math.min(block.to, slide.to)}, + {axis: 'x', settledWithin: 1}, + ); + await writeEvidence( + 'busy-main-thread/segmented-slide', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + block, + slide, + proof, + frames: tracked.map(f => ({ + t: +(f.t - block.from).toFixed(1), + x: f.box?.x ?? null, + })), + }, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, castFrames, { + name: 'segmented-slide-busy-main-thread', + zero: block.from, + from: block.from - 40, + to: Math.min(block.to, slide.to) + 40, + columns: 8, + cellScale: 0.35, + data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}), + }); + await film.write(testInfo, {block, slide}); + expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2); + expect(proof.changed).toBeGreaterThanOrEqual(proof.frames - 3); +}); + +test('the slide does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + await openControl(page, 'core-segmentedcontrol--selection-motion', 'Period'); + // A change the app makes (a DOM click on the story's button): the same + // slide, with no touch press model, focus ring or keyboard hint beside it. + const next = page.getByRole('button', {name: 'Next period'}); + // The story's two controls share the value, so both slide; each lands (and + // hands its surface back) on its own clock. + const groups = page.getByRole('radiogroup'); + await expect(groups).toHaveCount(2); + const handBacks = await recordHandBacks(page); + let start = 0; + const started = Date.now(); + const trace = await traceRendering(page, async () => { + await next.evaluate(button => (button as HTMLButtonElement).click()); + const slides = await Promise.all( + [0, 1].map(async i => (await waitForAnimation(groups.nth(i)))[0]), + ); + start = Math.max(...slides.map(slide => slide.from)); + // Wait in the test runner, not in the page: polling the page would force + // style and layout work of its own into the window being measured. + await new Promise(resolve => setTimeout(resolve, 1500)); + }); + const landed = await handBacks(); + expect(landed).toHaveLength(2); + // The steady part of the slides: their first frame commits the selection + // and the first hand-back ends it. + const during = countBetween(trace, start + 50, Math.min(...landed) - 50); + expect(Math.min(...landed) - start).toBeGreaterThan(500); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); + // No long task once the slides run. The click's own task (React renders the + // story and the motion starts both slides) ends at their first frame: it is + // the change's work, not the slides', and its length follows the machine's + // load. + const sinceSlides = (tasks: ReadonlyArray<{start: number}>) => + tasks.filter(task => task.start >= start); + expect(sinceSlides(trace.longTasks)).toEqual([]); + expect( + sinceSlides(await readLongTasks(page, {from: started, to: Date.now()})), + ).toEqual([]); +}); + +test('assistive technology sees the same radios: the lens is decoration with no element', async ({ + page, +}) => { + const control = await openControl(page); + await control.tapSegment('list'); + await expect(control.group).toMatchAriaSnapshot(` + - radiogroup "View mode": + - radio "Grid" + - radio "List" [checked] + - radio "Table" + `); +}); + +test( + 'storyboard: tap to slide, and a second tap mid-flight', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const control = await openControl(page); + await installTimerGate(page); + const measure = async () => { + const [sample] = await control.group.evaluate(element => { + const style = getComputedStyle(element, '::before'); + const x = style.translate === 'none' ? 0 : parseFloat(style.translate); + return [ + { + x: parseFloat(style.left) + parseFloat(style.width) / 2 + x, + scaleX: style.scale === 'none' ? 1 : parseFloat(style.scale), + visible: style.visibility === 'visible', + }, + ]; + }); + return sample; + }; + await control.tapSegment('table'); + await waitForLens(control); + await freezeTimers(page); + const {storyboard: slideBoard} = await animationStoryboard(page, { + name: 'segmented-tap-slide', + times: timeline(700), + clip: control.group, + scope: control.group, + measure, + columns: 8, + cellScale: 1, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await slideBoard.write(testInfo); + const xs = slideBoard.frames.map(f => f.data.x as number); + const boxes = await control.boxes(); + const table = boxOf(boxes, 'table'); + // The center rises to the destination's, overshoots a little, settles. + expect(xs.at(-1)).toBeCloseTo(centerOf(table), 0); + expect(Math.max(...xs)).toBeGreaterThan(centerOf(table)); + expect(Math.max(...xs) - centerOf(table)).toBeLessThan(2); + + // A second tap 80 ms into a slide back to the first segment. + await control.tapSegment('grid'); + await waitForLens(control, {minProgressMs: 80}); + await control.tapSegment('list'); + await waitForLens(control); + await freezeTimers(page); + const {storyboard: retargetBoard} = await animationStoryboard(page, { + name: 'segmented-retarget', + times: timeline(700), + clip: control.group, + scope: control.group, + measure, + columns: 8, + cellScale: 1, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await retargetBoard.write(testInfo); + const retargetXs = retargetBoard.frames.map(f => f.data.x as number); + // Where List is now: the titles' weights changed with the selection. + const list = boxOf(await control.boxes(), 'list'); + expect(retargetXs.at(-1)).toBeCloseTo(centerOf(list), 0); + // Continuous: no frame-to-frame jump larger than the fastest frame of a + // fresh slide would make. + for (let i = 1; i < retargetXs.length; i++) { + expect(Math.abs(retargetXs[i] - retargetXs[i - 1])).toBeLessThan(25); + } + }, +); + +/** Records each selection change (value, epoch ms on the page's clock). */ +async function recordSelections( + group: Locator, +): Promise<() => Promise<{value: string; at: number}[]>> { + await group.evaluate(track => { + const changes: {value: string; at: number}[] = []; + (window as unknown as {__selections: typeof changes}).__selections = + changes; + new MutationObserver(records => { + for (const record of records) { + const element = record.target as HTMLElement; + if (element.getAttribute('aria-checked') === 'true') { + changes.push({ + value: element.dataset.value ?? '', + at: performance.timeOrigin + performance.now(), + }); + } + } + }).observe(track, { + subtree: true, + attributes: true, + attributeFilter: ['aria-checked'], + }); + }); + return async () => + group.evaluate( + () => + (window as unknown as {__selections: {value: string; at: number}[]}) + .__selections, + ); +} + +/** The lens's presented center and size right now (no hold). */ +async function presentedNow(control: Control) { + return control.group.evaluate(element => { + const style = getComputedStyle(element, '::before'); + const x = style.translate === 'none' ? 0 : parseFloat(style.translate); + const [sx, sy = sx] = + style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number); + return { + center: parseFloat(style.left) + parseFloat(style.width) / 2 + x, + width: parseFloat(style.width) * sx, + height: parseFloat(style.height) * sy, + visible: style.visibility === 'visible', + }; + }); +} + +/** A segment's center in client coordinates. */ +async function clientCenter(control: Control, value: string) { + const box = await control.segment(value).boundingBox(); + if (box == null) { + throw new Error(`no segment ${value}`); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; +} + +test('holding the selected segment lifts nothing by default (a theme’s pressed-thumb lift turns it on): no lens and no shadow; letting go changes nothing', async ({ + page, +}) => { + const control = await openControl(page); + const selections = await recordSelections(control.group); + // Every time the radiogroup's style shows a pseudo-element layer. + await control.group.evaluate(group => { + const shown: string[] = []; + (window as unknown as {__layersShown: string[]}).__layersShown = shown; + new MutationObserver(() => { + const lens = group.style.getPropertyValue('--_segmented-lens-visibility'); + const after = group.style.getPropertyValue( + '--_segmented-after-visibility', + ); + if (lens !== '' || after !== '') { + shown.push(`lens=${lens} after=${after}`); + } + }).observe(group, {attributes: true, attributeFilter: ['style']}); + }); + await control.driver.play( + touchTap(await clientCenter(control, 'grid'), {holdMs: 700}), + ); + expect( + await page.evaluate( + () => (window as unknown as {__layersShown: string[]}).__layersShown, + ), + ).toEqual([]); + // The selected segment kept painting its own surface throughout. + expect( + await control + .segment('grid') + .evaluate(element => + (element as HTMLElement).style.getPropertyValue('background-color'), + ), + ).toBe(''); + expect(await selections()).toEqual([]); +}); + +test('a drag from the selected segment carries the lens and commits once, at the lift', async ({ + page, +}) => { + const control = await openControl(page); + const boxes = await control.boxes(); + const selections = await recordSelections(control.group); + const from = await clientCenter(control, 'grid'); + const to = await clientCenter(control, 'table'); + const midDrag: {finger: number; lens: number; width: number; at: number}[] = + []; + const played = await control.driver.play( + touchDrag(from, to, {durationMs: 600, restMs: 200}), + { + onEvent: async (step, index) => { + if (step.type === 'touchMove' && index % 6 === 0) { + const now = await presentedNow(control); + midDrag.push({ + finger: step.changed[0].x, + lens: now.center, + width: now.width, + at: Date.now(), + }); + } + }, + }, + ); + const lift = played.find(event => event.type === 'touchEnd'); + const changes = await selections(); + expect(changes.map(change => change.value)).toEqual(['table']); + // Not before the finger let go. + expect(changes[0].at).toBeGreaterThanOrEqual((lift?.dispatchedAt ?? 0) - 5); + // The lens followed the finger at its resting size (trailing it on the + // tracking spring, by less than the width of a segment). + const trackLeft = (await control.group.boundingBox())?.x ?? 0; + for (const sample of midDrag.slice(2)) { + // Nothing lifts it: its width stays a segment's. + expect(sample.width).toBeLessThan(boxOf(boxes, 'grid').width + 12); + const lag = sample.finger - trackLeft - sample.lens; + expect(lag).toBeGreaterThan(-2); + expect(lag).toBeLessThan(40); + } + await expectLensHidden(control); +}); + +test('letting go between segments commits the one nearest the finger', async ({ + page, +}) => { + for (const [progress, expected] of [ + [0.4, 'grid'], + [0.6, 'list'], + ] as const) { + const control = await openControl(page); + const selections = await recordSelections(control.group); + const from = await clientCenter(control, 'grid'); + const list = await clientCenter(control, 'list'); + const to = {x: from.x + (list.x - from.x) * progress, y: from.y}; + await control.driver.play( + touchDrag(from, to, {durationMs: 300, restMs: 200}), + ); + await expectLensHidden(control); + await expect(control.segment(expected)).toHaveAttribute( + 'aria-checked', + 'true', + ); + expect((await selections()).map(change => change.value)).toEqual( + expected === 'grid' ? [] : [expected], + ); + } +}); + +test('past the end segment the lens stops 11 pt beyond its center', async ({ + page, +}) => { + const control = await openControl(page); + const table = boxOf(await control.boxes(), 'table'); + const from = await clientCenter(control, 'grid'); + const end = await control.segment('table').boundingBox(); + if (end == null) { + throw new Error('no table segment'); + } + const script = touchDrag( + from, + {x: end.x + end.width + 60, y: from.y}, + {durationMs: 500, restMs: 700}, + ); + const lastMove = toTouchEvents(script).length - 2; + let resting: {center: number} | null = null; + await control.driver.play(script, { + onEvent: async (_step, index) => { + if (index === lastMove) { + // The finger rests 60 pt past the control; the chase settles. + await page.waitForTimeout(450); + resting = await presentedNow(control); + } + }, + }); + expect(resting).not.toBeNull(); + const center = (resting as unknown as {center: number}).center; + expect(Math.abs(center - (centerOf(table) + DRAG_OVERSHOOT))).toBeLessThan( + 1.5, + ); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); +}); + +test('a drag that starts on another segment leaves the lens alone and commits where it lets go', async ({ + page, +}) => { + const control = await openControl(page); + const selections = await recordSelections(control.group); + const from = await clientCenter(control, 'list'); + const to = await clientCenter(control, 'table'); + const visibleDuringDrag: boolean[] = []; + await control.driver.play( + touchDrag(from, to, {durationMs: 400, restMs: 100}), + { + onEvent: async step => { + if (step.type === 'touchMove') { + visibleDuringDrag.push((await presentedNow(control)).visible); + } + }, + }, + ); + expect(visibleDuringDrag.length).toBeGreaterThan(5); + expect(visibleDuringDrag.every(visible => !visible)).toBe(true); + // Lift position wins, as in UIKit. + expect((await selections()).map(change => change.value)).toEqual(['table']); +}); + +test('a finger on an unselected segment shows the shared pressed overlay and dims nothing; the lift commits it', async ({ + page, +}) => { + const control = await openControl(page); + const list = control.segment('list'); + const shown = async () => + list.evaluate(element => ({ + press: element.getAttribute('data-astryx-press'), + image: getComputedStyle(element).backgroundImage, + opacity: getComputedStyle(element).opacity, + title: getComputedStyle( + element.querySelector('[data-segment-title]') as Element, + ).opacity, + })); + const playing = control.driver.play( + touchTap(await clientCenter(control, 'list'), {holdMs: 400}), + ); + // The system's press paint, as everywhere else under a finger: the press + // controller marks the segment once it believes the press, and the shared + // overlay paints it. + await expect.poll(async () => (await shown()).press).toBe('on'); + const held = await shown(); + // While the controller paints, the overlay is its image layer. + expect(held.image).toContain('gradient'); + // Nothing dims: not the segment, not its title. + expect({opacity: held.opacity, title: held.title}).toEqual({ + opacity: '1', + title: '1', + }); + await playing; + await expect(list).toHaveAttribute('aria-checked', 'true'); + await expect(list).toHaveCSS('opacity', '1'); + await expect(list).not.toHaveAttribute('data-pressed'); +}); + +test('during a drag the selected face follows the lens as a colour, with no weight swap mid-drag, and the commit keeps it as shown', async ({ + page, +}) => { + const control = await openControl(page); + const read = async (value: string) => + control + .segment(value) + .locator('[data-segment-title]') + .evaluate(element => { + const style = getComputedStyle(element); + return {weight: style.fontWeight, color: style.color}; + }); + const selected = await read('grid'); + const unselected = await read('list'); + expect(selected.color).not.toBe(unselected.color); + const boxes = await control.boxes(); + const list = boxOf(boxes, 'list'); + const table = boxOf(boxes, 'table'); + const groupBox = await control.group.boundingBox(); + const seen: { + finger: number; + grid: {weight: string; color: string}; + list: {weight: string; color: string}; + table: {weight: string; color: string}; + }[] = []; + await control.driver.play( + touchDrag( + await clientCenter(control, 'grid'), + await clientCenter(control, 'table'), + {durationMs: 600, restMs: 300}, + ), + { + onEvent: async step => { + if (step.type === 'touchMove') { + seen.push({ + finger: step.changed[0].x - (groupBox?.x ?? 0), + grid: await read('grid'), + list: await read('list'), + table: await read('table'), + }); + } + }, + }, + ); + expect(seen.length).toBeGreaterThan(5); + // No title changes weight mid-drag: the segments never reflow under it. + for (const s of seen) { + expect(s.grid.weight).toBe(selected.weight); + expect(s.list.weight).toBe(unselected.weight); + expect(s.table.weight).toBe(unselected.weight); + } + // The face trails the finger with the lens, never ahead of it. + const gapMiddle = (list.x + list.width + table.x) / 2; + for (const s of seen.filter(s => s.finger < gapMiddle - 1)) { + expect(s.table.color, `finger at ${s.finger}`).toBe(unselected.color); + } + expect(seen.at(-1)?.table.color).toBe(selected.color); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + // The commit takes the face over: no borrowed style is left. + expect( + await control.group.evaluate(group => + [...group.querySelectorAll('[data-segment-title]')] + .map(title => title.style.cssText) + .join(''), + ), + ).toBe(''); + expect((await read('table')).weight).toBe(selected.weight); +}); + +test('a slow ±3 px dither across a boundary changes the selected face at most once', async ({ + page, +}) => { + const control = await openControl(page); + const colorOf = async (value: string) => + control + .segment(value) + .locator('[data-segment-title]') + .evaluate(element => getComputedStyle(element).color); + const selectedColor = await colorOf('grid'); + const faced = async () => { + for (const value of ['list', 'grid', 'table']) { + if (value !== 'grid' && (await colorOf(value)) === selectedColor) { + return value; + } + } + return 'grid'; + }; + const boxes = await control.boxes(); + const grid = boxOf(boxes, 'grid'); + const list = boxOf(boxes, 'list'); + const groupBox = await control.group.boundingBox(); + const y = (groupBox?.y ?? 0) + (groupBox?.height ?? 0) / 2; + const boundary = (groupBox?.x ?? 0) + (grid.x + grid.width + list.x) / 2; + const start = await clientCenter(control, 'grid'); + // Held on Grid, carried to the boundary, then dithered ±3 px, 70 ms a step. + const script = [ + {t: 0, fingers: [{id: 0, x: start.x, y}]}, + {t: 300, fingers: [{id: 0, x: boundary, y}]}, + ...Array.from({length: 24}, (_, i) => ({ + t: 700 + i * 70, + fingers: [{id: 0, x: boundary + (i % 2 === 0 ? 3 : -3), y}], + })), + {t: 700 + 24 * 70 + 50, fingers: []}, + ]; + const faces: string[] = []; + await control.driver.play(script, { + onEvent: async step => { + if (step.type === 'touchMove' && step.t >= 700) { + faces.push(await faced()); + } + }, + }); + const changes = faces.filter((face, i) => i > 0 && face !== faces[i - 1]); + expect(changes.length, faces.join(' ')).toBeLessThanOrEqual(1); +}); + +test('a drag held just past a boundary: at the lift the selected colour snaps to the segment nearest the finger, which it commits', async ({ + page, +}) => { + const control = await openControl(page); + const boxes = await control.boxes(); + const grid = boxOf(boxes, 'grid'); + const list = boxOf(boxes, 'list'); + const groupBox = await control.group.boundingBox(); + const y = (groupBox?.y ?? 0) + (groupBox?.height ?? 0) / 2; + const boundary = (groupBox?.x ?? 0) + (grid.x + grid.width + list.x) / 2; + const start = await clientCenter(control, 'grid'); + const selections = await recordSelections(control.group); + // Held on Grid, carried 3 px past the boundary, rested, lifted. + await control.driver.play([ + {t: 0, fingers: [{id: 0, x: start.x, y}]}, + {t: 300, fingers: [{id: 0, x: boundary - 10, y}]}, + {t: 400, fingers: [{id: 0, x: boundary + 3, y}]}, + {t: 900, fingers: []}, + ]); + await page.waitForTimeout(400); + // The hysteresis kept the colour on Grid while held; the lift commits List, + // the nearest, and the colour snaps there with the selection. + await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true'); + expect((await selections()).map(change => change.value)).toEqual(['list']); +}); + +test('a tap’s commit is the browser’s own click (spec:AST-094 FR11)', async ({ + page, +}) => { + const control = await openControl(page); + await control.segment('table').evaluate(element => { + const w = window as unknown as {__trusted: boolean[]}; + w.__trusted = []; + element.addEventListener( + 'click', + event => w.__trusted.push(event.isTrusted), + { + capture: true, + }, + ); + }); + // The engine's tap path: Playwright's WebKit synthesises the browser's + // click only from its tap gesture, not from a raw touch sequence (the + // harness README's engine limits); Chromium's touch input does either way. + await control.driver.tap(await clientCenter(control, 'table')); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + await page.waitForTimeout(400); + expect( + await page.evaluate( + () => (window as unknown as {__trusted: boolean[]}).__trusted, + ), + ).toEqual([true]); +}); + +/** + * Counts the clicks that reach a segment and, with `veto`, prevents them the + * way an item's consumer `onClick` would (`event.preventDefault()`), which + * the item's own handler honours. + */ +async function watchClicks( + control: Control, + value: string, + {veto = false}: {veto?: boolean} = {}, +): Promise<() => Promise> { + await control.segment(value).evaluate((element, shouldVeto) => { + const counter = {count: 0}; + (element as unknown as {__clicks: typeof counter}).__clicks = counter; + element.addEventListener( + 'click', + event => { + counter.count++; + if (shouldVeto) { + event.preventDefault(); + } + }, + {capture: true}, + ); + }, veto); + return async () => + control + .segment(value) + .evaluate( + element => + (element as unknown as {__clicks: {count: number}}).__clicks.count, + ); +} + +test('a tap commits through the item’s click: its onClick runs once and can veto with preventDefault()', async ({ + page, +}) => { + const control = await openControl(page); + const clicks = await watchClicks(control, 'table'); + const selections = await recordSelections(control.group); + await control.driver.play( + touchTap(await clientCenter(control, 'table'), {holdMs: 80}), + ); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + // Once: the browser's own click for the touch selects nothing again. + await page.waitForTimeout(400); + expect(await clicks()).toBe(1); + expect((await selections()).map(change => change.value)).toEqual(['table']); +}); + +test('a tap whose browser click comes late (a busy main thread) runs the item’s click once', async ({ + page, +}) => { + const control = await openControl(page); + const clicks = await watchClicks(control, 'table'); + const selections = await recordSelections(control.group); + // The lift arms a 300 ms wait for the browser's click; block the main + // thread for 450 ms right after, so the browser's click for this tap comes + // only after the wait ran out. + await page.evaluate(() => { + const original = window.setTimeout; + const patched = ( + handler: TimerHandler, + ms?: number, + ...rest: unknown[] + ): number => { + const id = original(handler, ms, ...rest); + if (ms === 300) { + window.setTimeout = original; + const end = performance.now() + 450; + while (performance.now() < end) { + // busy: the main thread is blocked + } + } + return id; + }; + window.setTimeout = patched as typeof window.setTimeout; + }); + await control.driver.tap(await clientCenter(control, 'table')); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + await page.waitForTimeout(800); + expect(await clicks()).toBe(1); + expect((await selections()).map(change => change.value)).toEqual(['table']); +}); + +test('a vetoed tap selects nothing, and the lens goes back to the selection', async ({ + page, +}) => { + const control = await openControl(page); + await watchClicks(control, 'table', {veto: true}); + const selections = await recordSelections(control.group); + await control.driver.play( + touchTap(await clientCenter(control, 'table'), {holdMs: 80}), + ); + await page.waitForTimeout(400); + expect(await selections()).toEqual([]); + await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true'); + // The lens settles back on Grid and hands its surface back. + await expectLensHidden(control); + expect( + await control.group.evaluate(group => + [...group.querySelectorAll('[role="radio"]')] + .map(segment => segment.style.cssText) + .join(''), + ), + ).toBe(''); +}); + +test('a parent that adopts the value 200 ms later gets no bounce: the lens keeps going and lands there', async ({ + page, +}) => { + const control = await openControl(page); + // The story's parent adopts a value at once; this one adopts it 200 ms + // after the click: the commit's own click goes unheard (nobody vetoes it), + // and a later programmatic click delivers the value. + await control.segment('table').evaluate(segment => { + const lens: number[] = []; + (window as unknown as {__lens: number[]}).__lens = lens; + const group = segment.closest('[role="radiogroup"]') as HTMLElement; + const sample = () => { + const style = getComputedStyle(group, '::before'); + if (style.visibility === 'visible') { + const translate = + style.translate === 'none' ? 0 : parseFloat(style.translate); + lens.push( + parseFloat(style.left) + parseFloat(style.width) / 2 + translate, + ); + } + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + const hold = (event: Event) => { + if ((event as MouseEvent).detail === 0) { + return; + } + event.stopImmediatePropagation(); + segment.removeEventListener('click', hold, true); + setTimeout(() => { + (segment as HTMLElement).click(); + }, 200); + }; + segment.addEventListener('click', hold, true); + }); + await control.tapSegment('table'); + await expect(control.segment('table')).toHaveAttribute( + 'aria-checked', + 'true', + ); + await expectLensHidden(control); + const centers = await page.evaluate( + () => (window as unknown as {__lens: number[]}).__lens, + ); + expect(centers.length).toBeGreaterThan(10); + // Every presented frame heads for Table: never back toward Grid (beyond + // the spring's own overshoot of about a pixel at the end). + let highest = -Infinity; + for (const center of centers) { + expect(center, JSON.stringify(centers)).toBeGreaterThan(highest - 2); + highest = Math.max(highest, center); + } +}); + +test('a drag commits through the destination item’s click too: its onClick runs once, and a veto keeps the selection', async ({ + page, +}) => { + const control = await openControl(page); + const clicks = await watchClicks(control, 'table'); + const selections = await recordSelections(control.group); + const from = await clientCenter(control, 'grid'); + const to = await clientCenter(control, 'table'); + await control.driver.play( + touchDrag(from, to, {durationMs: 400, restMs: 100}), + ); + await page.waitForTimeout(400); + expect(await clicks()).toBe(1); + expect((await selections()).map(change => change.value)).toEqual(['table']); + // Back to Grid, then a vetoed drag to List. + await control.driver.play( + touchTap(await clientCenter(control, 'grid'), {holdMs: 80}), + ); + await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true'); + await expectLensHidden(control); + await watchClicks(control, 'list', {veto: true}); + const vetoed = await recordSelections(control.group); + await control.driver.play( + touchDrag( + await clientCenter(control, 'grid'), + await clientCenter(control, 'list'), + {durationMs: 300, restMs: 100}, + ), + ); + await page.waitForTimeout(400); + expect(await vetoed()).toEqual([]); + await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true'); + await expectLensHidden(control); +}); + +/** A desktop context: a mouse, no touch, a fine primary pointer. */ +async function openWithMouse(browser: Browser): Promise<{ + context: BrowserContext; + page: Page; + group: Locator; + centerOf: (value: string) => Promise<{x: number; y: number}>; + lensShown: () => Promise; +}> { + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 1024, height: 768}, + }); + const page = await context.newPage(); + await openStory(page, storybook(), 'core-segmentedcontrol--default'); + // This context's pointer is fine (a context without touch can still match + // a coarse one). + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const group = page.getByRole('radiogroup', {name: 'View mode', exact: true}); + await expect(group).toBeVisible(); + const centerOf = async (value: string) => { + const rect = await group.locator(`[data-value="${value}"]`).boundingBox(); + if (rect == null) { + throw new Error(`no segment ${value}`); + } + return {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2}; + }; + // The motion shows the lens through the radiogroup's own custom property. + const lensShown = async () => + group.evaluate( + element => + element.style.getPropertyValue('--_segmented-lens-visibility') === + 'visible', + ); + return {context, page, group, centerOf, lensShown}; +} + +test('with a mouse a drag from the selected segment carries the selection and commits where it lifts, as every pointer does (spec:AST-094 FR43)', async ({ + browser, +}) => { + const {context, page, group, centerOf, lensShown} = + await openWithMouse(browser); + try { + const selections = await recordSelections(group); + const from = await centerOf('grid'); + const to = await centerOf('table'); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, {steps: 12}); + // Held: the lens is on the pointer, and nothing is committed before the + // lift. + expect(await lensShown()).toBe(true); + await expect(group.locator('[data-value="grid"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + await page.mouse.up(); + await expect(group.locator('[data-value="table"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + expect((await selections()).map(change => change.value)).toEqual(['table']); + // The drag selected no text, and the lens hands back once it settles. + expect(await page.evaluate(() => getSelection()?.toString() ?? '')).toBe( + '', + ); + await expect.poll(lensShown, {timeout: 3000}).toBe(false); + await expect(group.locator('[data-value="list"]')).toHaveCSS( + 'transition-property', + 'color, background-color, box-shadow', + ); + // A click still selects. + await group.locator('[data-value="list"]').click(); + await expect(group.locator('[data-value="list"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + } finally { + await context.close(); + } +}); + +test('with a mouse a drag that starts on another segment commits only where it lifts, focus already in the group or not, and carries no lens', async ({ + browser, +}) => { + const {context, page, group, centerOf, lensShown} = + await openWithMouse(browser); + try { + // A click on the selected segment first: focus is in the group, so the + // press below moves focus within it, which must select nothing. + await group.locator('[data-value="grid"]').click(); + const selections = await recordSelections(group); + const from = await centerOf('list'); + const to = await centerOf('table'); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, {steps: 12}); + expect(await lensShown()).toBe(false); + // Nothing is committed before the lift. + await expect(group.locator('[data-value="grid"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + await page.mouse.up(); + await expect(group.locator('[data-value="table"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + expect((await selections()).map(change => change.value)).toEqual(['table']); + expect(await lensShown()).toBe(false); + } finally { + await context.close(); + } +}); + +test('with a pen a drag from the selected segment carries the selection and commits where it lifts (spec:AST-094 FR43)', async ({ + browser, +}) => { + const {context, page, group, centerOf} = await openWithMouse(browser); + try { + const driver = await webInputDriver(page); + test.skip(!driver.pens, PEN_SKIP); + const selections = await recordSelections(group); + const from = await centerOf('grid'); + const to = await centerOf('table'); + const points = Array.from({length: 13}, (_, i) => ({ + x: from.x + ((to.x - from.x) * i) / 12, + y: from.y, + t: i * 25, + })); + await driver.pen(points); + await expect(group.locator('[data-value="table"]')).toHaveAttribute( + 'aria-checked', + 'true', + ); + expect((await selections()).map(change => change.value)).toEqual(['table']); + } finally { + await context.close(); + } +}); + +test('the track keeps vertical scrolling and takes horizontal drags', async ({ + page, +}) => { + const control = await openControl(page); + await expect(control.group).toHaveCSS('touch-action', 'pan-y pinch-zoom'); +}); + +test('a held finger selects no text on the control; letting go gives selection back', async ({ + page, +}) => { + const control = await openControl(page); + const userSelect = async () => + control.group.evaluate(element => { + const style = getComputedStyle(element) as CSSStyleDeclaration & { + webkitUserSelect?: string; + }; + return style.userSelect || style.webkitUserSelect; + }); + // Whether a selection starting on the held segment is refused now. Where + // iOS WebKit does not run, the gesture host's lock cancels `selectstart` + // and writes no style, so nothing repaints at the touch-down or the lift + // (`spec:AST-094` FR41); in iOS WebKit, which fires no `selectstart` for a + // long press, the lock is `user-select` and the callout, which the + // simulator recordings cover. + const refusesSelection = async () => + control.segment('list').evaluate(element => { + const event = new Event('selectstart', {bubbles: true, cancelable: true}); + element.dispatchEvent(event); + return event.defaultPrevented; + }); + // At rest the titles are as selectable as anywhere else on the page. + const atRest = await userSelect(); + expect(atRest).not.toBe('none'); + expect(await refusesSelection()).toBe(false); + const playing = control.driver.play( + touchTap(await clientCenter(control, 'list'), {holdMs: 600}), + ); + await expect.poll(refusesSelection).toBe(true); + expect(await userSelect()).toBe(atRest); + await playing; + await expect.poll(refusesSelection).toBe(false); + expect(await userSelect()).toBe(atRest); +}); + +/** Makes the story page scroll: the control sits in a scroller. */ +async function makePageScroll(page: Page): Promise { + await page.evaluate(() => { + const spacer = document.createElement('div'); + spacer.style.height = '2000px'; + document.body.append(spacer); + }); +} + +/** Records whether each `touchmove` was cancelled (read after every listener). */ +async function recordTouchMoves(page: Page): Promise<() => Promise> { + await page.evaluate(() => { + const moves: boolean[] = []; + (window as unknown as {__moves: boolean[]}).__moves = moves; + window.addEventListener( + 'touchmove', + event => { + moves.push(event.defaultPrevented); + }, + {passive: true}, + ); + }); + return async () => + page.evaluate(() => (window as unknown as {__moves: boolean[]}).__moves); +} + +/** Records, on the page's clock, each time the lens is shown or hidden. */ +async function recordProxyVisibility( + control: Control, +): Promise<() => Promise<{visible: boolean; at: number}[]>> { + await control.group.evaluate(element => { + const changes: {visible: boolean; at: number}[] = []; + (window as unknown as {__lens: typeof changes}).__lens = changes; + // The radiogroup's style also carries the gesture host's text-selection + // lock and the animator's promotion: only a change of the lens counts. + const shown = () => + getComputedStyle(element, '::before').visibility === 'visible'; + let visible = shown(); + new MutationObserver(() => { + const now = shown(); + if (now !== visible) { + visible = now; + changes.push({visible, at: performance.timeOrigin + performance.now()}); + } + }).observe(element, {attributes: true, attributeFilter: ['style']}); + }); + return async () => + control.group.evaluate( + () => + (window as unknown as {__lens: {visible: boolean; at: number}[]}) + .__lens, + ); +} + +test('a vertical drag that starts on the control scrolls the page and lifts nothing', async ({ + page, +}) => { + const control = await openControl(page); + await makePageScroll(page); + const selections = await recordSelections(control.group); + const moves = await recordTouchMoves(page); + const shown = await recordProxyVisibility(control); + const start = await clientCenter(control, 'grid'); + await control.driver.play( + touchDrag(start, {x: start.x + 4, y: start.y - 140}, {durationMs: 300}), + ); + // The page kept every move: nothing cancelled them... + const cancelled = await moves(); + expect(cancelled.length).toBeGreaterThan(0); + expect(cancelled.some(Boolean)).toBe(false); + if (control.driver.engine === 'chromium') { + // ...and Chromium scrolled it natively. + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(60); + } + // A flick inside a scroller presses nothing: no lift, no change. + await page.waitForTimeout(300); + expect(await shown()).toEqual([]); + expect(await selections()).toEqual([]); +}); + +test('RTL: a drag carries the lens toward the finger and commits once, at the lift', async ({ + page, +}) => { + const control = await openControl( + page, + 'core-segmentedcontrol--default', + 'View mode', + {direction: 'rtl'}, + ); + const boxes = await control.boxes(); + // The first segment is on the right in RTL. + expect(boxOf(boxes, 'grid').x).toBeGreaterThan(boxOf(boxes, 'table').x); + const selections = await recordSelections(control.group); + const from = await clientCenter(control, 'grid'); + const to = await clientCenter(control, 'table'); + const midDrag: {finger: number; lens: number; width: number; at: number}[] = + []; + const played = await control.driver.play( + touchDrag(from, to, {durationMs: 600, restMs: 200}), + { + onEvent: async (step, index) => { + if (step.type === 'touchMove' && index % 6 === 0) { + const now = await presentedNow(control); + midDrag.push({ + finger: step.changed[0].x, + lens: now.center, + width: now.width, + at: Date.now(), + }); + } + }, + }, + ); + const lift = played.find(event => event.type === 'touchEnd'); + const changes = await selections(); + expect(changes.map(change => change.value)).toEqual(['table']); + expect(changes[0].at).toBeGreaterThanOrEqual((lift?.dispatchedAt ?? 0) - 5); + // Trailing the finger from the right as it moves left, at its resting + // size. + const trackLeft = (await control.group.boundingBox())?.x ?? 0; + expect(midDrag.length).toBeGreaterThan(3); + for (const sample of midDrag.slice(2)) { + // Nothing lifts it: its width stays a segment's. + expect(sample.width).toBeLessThan(boxOf(boxes, 'grid').width + 12); + const lag = sample.lens - (sample.finger - trackLeft); + expect(lag).toBeGreaterThan(-2); + expect(lag).toBeLessThan(40); + } + await expectLensHidden(control); +}); + +test( + 'storyboard: hold the selected segment, drag it, let go', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const control = await openControl(page); + const box = await control.group.boundingBox(); + if (box == null) { + throw new Error('no control'); + } + const from = await clientCenter(control, 'grid'); + const to = await clientCenter(control, 'table'); + const board = await touchStoryboard( + page, + control.driver, + touchDrag(from, to, {durationMs: 600, holdMs: 350, restMs: 250, hz: 20}), + { + name: 'segmented-hold-drag-release', + clip: { + x: box.x - 12, + y: box.y - 14, + width: box.width + 24, + height: box.height + 28, + }, + measure: async () => presentedNow(control), + columns: 4, + cellScale: 1, + }, + ); + await board.write(testInfo); + // Nothing lifts while the finger holds the selected segment: the lens + // appears only once the drag moves it, at the resting size. + const rest = boxOf(await control.boxes(), 'grid').width; + const held = board.frames.filter(frame => + frame.label.startsWith('touchStart'), + ); + for (const frame of held) { + const data = frame.data as {width: number; visible: boolean}; + expect(data.visible, frame.label).toBe(false); + } + // Carried the whole way: the selected face moving to the title under the + // finger reflows the titles, and the lens stays with the finger. + const dragged = board.frames.filter( + frame => frame.label.startsWith('touchMove') && frame.t >= 450, + ); + expect(dragged.length).toBeGreaterThan(5); + for (const frame of dragged) { + const data = frame.data as {width: number; visible: boolean}; + expect(data.visible, frame.label).toBe(true); + expect(data.width, frame.label).toBeLessThan(rest + 12); + } + }, +); diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts new file mode 100644 index 0000000000000..64d2962a173b3 --- /dev/null +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts @@ -0,0 +1,1261 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useSegmentedSelectionMotion.test.ts + * @input vitest, jsdom, SegmentedSelectionMotion with an animator on a + * scripted clock, stubbed segment geometry and a recording `animate` + * @output The touch layer's selection motion as a state machine: the lens + * (the radiogroup's ::before) is painted from the selected surface and + * springs from the old segment's box to the new one's on the UIKit spring, + * the segment's own surface hidden meanwhile and handed back on landing; a + * change mid-flight keeps the presented position and velocity; resize, a + * cleared selection and Reduced Motion (the ::after fading out where it + * is); under a finger no lift and no dim (a press shows the shared overlay), + * the chase at the lens's resting size, the commit at the lift and what + * happens when the value does not come back, and the face that follows a + * dragging finger. + * @position Unit tests for useSegmentedSelectionMotion.ts. The browser proofs + * (real touch, seeked curves, busy main thread, Layout / Paint, pixels) are + * __tests__/SegmentedControl.interaction.browser.spec.ts. + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {motionRoleOf} from '../motion/roles'; +import {createAnimator, type Animator} from '../motion/animator'; +import {solveSpring, toSpring} from '../motion/spring'; +import {segmentedControl, springs} from '../motion/uikit'; +import {measureSegments, segmentTargetAt} from './useSegmentedTouchTracking'; +import { + SegmentedSelectionMotion, + TITLE_SELECTOR, + layerVariable, + type Layer, +} from './useSegmentedSelectionMotion'; + +interface Geometry { + left: number; + width: number; +} + +// The track sits at (10, 20) in the viewport; segments are 27 px tall, 2 px +// below its padding edge. Unequal widths, like a hug layout. +const TRACK = {left: 10, top: 20, width: 306, height: 31}; +const SEGMENTS: Record = { + grid: {left: 12, width: 96}, + list: {left: 108, width: 100}, + table: {left: 208, width: 106}, +}; + +function rect(left: number, top: number, width: number, height: number) { + return { + left, + top, + width, + height, + right: left + width, + bottom: top + height, + x: left, + y: top, + toJSON: () => ({}), + } as DOMRect; +} + +let clock = 0; +let reduceMotion = false; + +/** + * The person's settings, through `matchMedia` as the animator reads them (no + * option overrides them): Reduce Motion as `reduceMotion` says at each read, + * and a coarse primary pointer or not. + */ +function stubMedia(coarse: boolean): void { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query.includes('prefers-reduced-motion') + ? reduceMotion + : query.includes('pointer: coarse') + ? coarse + : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })); +} + +function setup(selected: string, {coarse = true}: {coarse?: boolean} = {}) { + stubMedia(coarse); + const track = document.createElement('div'); + track.getBoundingClientRect = () => + rect(TRACK.left, TRACK.top, TRACK.width, TRACK.height); + Object.defineProperty(track, 'offsetWidth', { + value: TRACK.width, + configurable: true, + }); + const segments: Record = {}; + for (const [value, geometry] of Object.entries(SEGMENTS)) { + const segment = document.createElement('button'); + segment.setAttribute('role', 'radio'); + segment.dataset.value = value; + segment.getBoundingClientRect = () => + rect(geometry.left, TRACK.top + 2, geometry.width, 27); + const title = document.createElement('span'); + title.dataset.segmentTitle = ''; + title.textContent = value; + segment.append(title); + track.append(segment); + segments[value] = segment; + } + const style = document.createElement('style'); + style.textContent = STYLES; + document.head.append(style); + document.body.append(track); + // A finger by default: Reduced Motion fades (design:reduced-motion DR2). + const animator: Animator = createAnimator(null, { + now: () => clock, + pseudoElement: '::before', + }); + // The ::after: the lifted lens's shadow, or the surface fading out. + const afterAnimator: Animator = createAnimator(null, { + now: () => clock, + pseudoElement: '::after', + initial: {opacity: 0}, + }); + const motion = new SegmentedSelectionMotion(animator, { + now: () => clock, + afterAnimator, + }); + motion.attachTrack(track); + paint(segments, selected); + /** A custom property of one of the radiogroup's pseudo-element layers. */ + const layer = (name: Layer, property: string) => + track.style.getPropertyValue(layerVariable(name, property)); + return { + track, + segments, + animator, + leavingAnimator: afterAnimator, + motion, + layer, + }; +} + +type Ctx = ReturnType; + +/** The segment the touch tracking resolves for a finger at `clientX`. */ +function targetAt(ctx: Ctx, clientX: number): HTMLElement | null { + return segmentTargetAt(clientX, measureSegments(ctx.track)); +} + +/** A finger lands at `clientX` (the tracker's begin, then the motion's). */ +function begin(ctx: Ctx, clientX: number): void { + ctx.motion.begin(ctx.track, targetAt(ctx, clientX)); +} + +/** A finger lands at `clientX`. */ +function press(ctx: Ctx, clientX: number): void { + begin(ctx, clientX); +} + +/** The finger moves to `clientX`: a lens it holds chases it. */ +function drag(ctx: Ctx, clientX: number): void { + ctx.motion.drag(clientX); +} + +/** The finger lets go at `clientX`, on the segment the tracker resolves. */ +function release(ctx: Ctx, clientX: number): string | null { + return ctx.motion.release(targetAt(ctx, clientX)); +} + +/** + * The component's styles, as a stylesheet: the selected segment paints the + * raised surface, and each title's rendering follows its segment's state. + * (A stylesheet and not inline styles: the controller hides and restores the + * surface inline, exactly as it does over the real component's classes.) + */ +const STYLES = ` + [role="radio"] { border-top-left-radius: 6px; } + [role="radio"][aria-checked="true"] { + background-color: rgb(255, 255, 255); + box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px; + } + [role="radio"][aria-checked="false"] [data-segment-title] { + color: rgb(110, 110, 110); + font-weight: 500; + } + [role="radio"][aria-checked="true"] [data-segment-title] { + color: rgb(10, 10, 10); + font-weight: 600; + } + [role="radio"][aria-disabled="true"] [data-segment-title] { + color: rgb(200, 200, 200); + } +`; + +/** What a selection does to the DOM: the checked state moves. */ +function paint(segments: Record, selected: string) { + for (const [value, segment] of Object.entries(segments)) { + segment.setAttribute('aria-checked', String(value === selected)); + } +} + +function select(ctx: ReturnType, from: string, to: string): void { + paint(ctx.segments, to); + ctx.motion.select(ctx.track, from, to); +} + +/** A segment's center in the track's padding-box coordinates. */ +const centerOf = (value: string) => + SEGMENTS[value].left - TRACK.left + SEGMENTS[value].width / 2; + +/** The lens carries this segment's surface: hidden on the segment, inline. */ +function expectHidden(segment: HTMLElement): void { + expect(segment.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); +} + +/** The segment paints its own surface again: nothing inline, the stylesheet's paint. */ +/** No inline surface override is left on the segment. */ +function expectNoOverride(segment: HTMLElement): void { + expect(segment.style.getPropertyValue('background-color')).toBe(''); + expect(segment.style.getPropertyValue('background-image')).toBe(''); + expect(segment.style.getPropertyValue('box-shadow')).toBe(''); +} + +function expectOwnSurface(segment: HTMLElement): void { + expect(segment.style.getPropertyValue('background-color')).toBe(''); + expect(segment.style.getPropertyValue('box-shadow')).toBe(''); + expect(getComputedStyle(segment).backgroundColor).toBe('rgb(255, 255, 255)'); +} + +beforeEach(() => { + clock = 1000; + reduceMotion = false; + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); + document.body.innerHTML = ''; + document.head.innerHTML = ''; +}); + +async function advance(ms: number): Promise { + clock += ms; + await vi.advanceTimersByTimeAsync(ms); +} + +describe('the motion roles (spec:AST-094 FR4)', () => { + it('plays the slide through its internal segmented role', () => { + setup('grid'); + expect(motionRoleOf(segmentedControl.selectionSpring)?.id).toBe( + 'segmented.selectionSpring', + ); + }); +}); + +describe('the selection slide', () => { + it('paints the lens (the radiogroup’s ::before) with the selected surface and hides it on the segment: no element is added', () => { + const ctx = setup('grid'); + const elements = ctx.track.querySelectorAll('*').length; + select(ctx, 'grid', 'table'); + const {layer, segments} = ctx; + expect(ctx.track.querySelectorAll('*').length).toBe(elements); + expect(layer('lens', 'visibility')).toBe('visible'); + expect(layer('lens', 'background-color')).toBe('rgb(255, 255, 255)'); + expect(layer('lens', 'box-shadow')).toBe('rgba(0, 0, 0, 0.1) 0px 1px 2px'); + expect(layer('lens', 'border-top-left-radius')).toBe('6px'); + // Inline and with priority, so a theme's rule cannot paint a second one. + expect(segments.table.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); + expect(segments.table.style.getPropertyPriority('background-color')).toBe( + 'important', + ); + expect(segments.table.style.getPropertyValue('box-shadow')).toBe('none'); + // The lens is laid out on the destination's box. + expect(layer('lens', 'left')).toBe('198px'); + expect(layer('lens', 'width')).toBe('106px'); + expect(layer('lens', 'height')).toBe('27px'); + expect(layer('lens', 'top')).toBe('2px'); + }); + + it('hands the surface back to the segment when it lands', async () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(true); + await advance(400); + expect(ctx.motion.isSliding).toBe(true); + await advance(2000); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expectOwnSurface(ctx.segments.table); + }); + + it('the hand-back restores a segment’s own inline surface (its `style`)', async () => { + const ctx = setup('grid'); + const {table, list} = ctx.segments; + table.style.setProperty('background-color', 'gold', 'important'); + table.style.setProperty('border-top-color', 'red'); + select(ctx, 'grid', 'table'); + // Hidden while the lens carries the surface... + expect(table.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); + await advance(2400); + expect(ctx.motion.isSliding).toBe(false); + // ...then the segment's own declarations come back, priority included, + // and nothing it did not have is left behind. + expect(table.style.getPropertyValue('background-color')).toBe('gold'); + expect(table.style.getPropertyPriority('background-color')).toBe( + 'important', + ); + expect(table.style.getPropertyValue('border-top-color')).toBe('red'); + expect(table.style.getPropertyPriority('border-top-color')).toBe(''); + expect(table.style.getPropertyValue('background-image')).toBe(''); + expect(table.style.getPropertyValue('box-shadow')).toBe(''); + // A segment the slide never hid keeps its inline surface too. + list.style.setProperty('background-color', 'teal'); + select(ctx, 'table', 'grid'); + ctx.motion.settle(); + expect(list.style.getPropertyValue('background-color')).toBe('teal'); + }); + + it('a change mid-flight starts from what is on screen and keeps its velocity', async () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + await advance(80); + // The lens scales around its center: x is the center's offset from the + // destination's center. + const centerBefore = centerOf('table') + ctx.animator.get('x'); + const vBefore = ctx.animator.getVelocity('x'); + const widthBefore = ctx.animator.get('scaleX') * 106; + expect(vBefore).toBeGreaterThan(500); + select(ctx, 'table', 'list'); + // No jump and no lost velocity at the retarget. + expect(centerOf('list') + ctx.animator.get('x')).toBeCloseTo( + centerBefore, + 6, + ); + expect(ctx.animator.getVelocity('x')).toBeCloseTo(vBefore, 3); + expect(ctx.animator.get('scaleX') * 100).toBeCloseTo(widthBefore, 6); + // The lens now carries the new destination's surface and size. The + // abandoned destination paints nothing of its own until the lens lands: + // its tap may still be fading, and that paint would cover the lens. + expect(ctx.layer('lens', 'width')).toBe('100px'); + expect(ctx.segments.table.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); + expect(ctx.segments.table.style.getPropertyValue('background-image')).toBe( + 'none', + ); + expect(ctx.segments.list.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); + await advance(3000); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.list); + expectNoOverride(ctx.segments.table); + }); + + it('a change back to the abandoned segment takes it as the destination again', async () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + await advance(80); + select(ctx, 'table', 'list'); + await advance(40); + select(ctx, 'list', 'table'); + expect(ctx.segments.table.style.getPropertyValue('background-color')).toBe( + 'transparent', + ); + await advance(3000); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + expectNoOverride(ctx.segments.list); + }); + + it('settle() hands the surface back at once (resize, unmount, presentation change)', () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'list'); + ctx.motion.settle(); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expectOwnSurface(ctx.segments.list); + }); + + it('stop() ends a slide and leaves the controller usable (StrictMode remounts)', () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + ctx.motion.stop(); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + // The next change still slides, on the same lens. + select(ctx, 'table', 'list'); + expect(ctx.motion.isSliding).toBe(true); + expect(ctx.layer('lens', 'visibility')).toBe('visible'); + expect(ctx.animator.get('x', clock)).toBeCloseTo( + centerOf('table') - centerOf('list'), + 6, + ); + }); + + it('does not slide when nothing was selected, and settles when the selection clears', () => { + const ctx = setup('none'); + select(ctx, 'none', 'list'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + select(ctx, 'list', 'grid'); + expect(ctx.motion.isSliding).toBe(true); + select(ctx, 'grid', 'none'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.segments.grid.style.getPropertyValue('background-color')).toBe( + '', + ); + }); + + it('does not slide a control that is not laid out', () => { + const ctx = setup('grid'); + ctx.segments.table.getBoundingClientRect = () => rect(0, 0, 0, 0); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + }); + + it('undoes an ancestor scale: boxes are measured in the track’s own pixels', () => { + const ctx = setup('grid'); + // Rendered at 2x by a transformed ancestor: client rects double. + ctx.track.getBoundingClientRect = () => + rect(TRACK.left, TRACK.top, TRACK.width * 2, TRACK.height * 2); + for (const [value, geometry] of Object.entries(SEGMENTS)) { + ctx.segments[value].getBoundingClientRect = () => + rect( + TRACK.left + (geometry.left - TRACK.left) * 2, + TRACK.top + 4, + geometry.width * 2, + 54, + ); + } + select(ctx, 'grid', 'table'); + expect(ctx.layer('lens', 'width')).toBe('106px'); + expect(ctx.animator.get('x', 5000)).toBeCloseTo(0, 6); + }); + + it('Reduced Motion (design:reduced-motion): no travel, no scale; the old surface fades out where it is as the new one fades in, in 200 ms or less', async () => { + reduceMotion = true; + const ctx = setup('grid'); + const start = clock; + select(ctx, 'grid', 'table'); + expect(ctx.layer('lens', 'width')).toBe('106px'); + expectHidden(ctx.segments.table); + expectReducedMotionCrossFade(ctx, start, 'grid'); + await advance(1000); + expect(isLeaving(ctx)).toBe(false); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expectOwnSurface(ctx.segments.table); + }); + + it('Reduced Motion with any other pointer: a change completes at once, with no fade and no leaving surface (DR3)', () => { + reduceMotion = true; + const ctx = setup('grid', {coarse: false}); + select(ctx, 'grid', 'table'); + expect(isLeaving(ctx)).toBe(false); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.animator.get('opacity')).toBe(1); + expect(ctx.animator.get('scaleX')).toBe(1); + }); + + it('Reduced Motion off again: the next change slides at full size and opacity', async () => { + reduceMotion = true; + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + await advance(50); + // Turned off mid-fade: the next change travels, opaque and unscaled. + reduceMotion = false; + ctx.motion.settle(); + select(ctx, 'table', 'list'); + expect(ctx.animator.get('opacity')).toBe(1); + expect(ctx.animator.get('scaleY')).toBe(1); + await advance(3000); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.motion.isSliding).toBe(false); + }); +}); + +/** + * Under Reduced Motion the ::after shows the surface that fades out where it + * is: painted with a surface (the lifted lens's shadow has no fill). + */ +const isLeaving = (ctx: ReturnType) => + ctx.layer('after', 'visibility') === 'visible' && + ctx.layer('after', 'background-color') !== ''; + +/** When `get` stops changing: the end of the fade, in ms after `start`. */ +function endOf(get: (t: number) => number, start: number): number { + const last = get(start + 5000); + for (let t = 0; t <= 5000; t += 1) { + if (Math.abs(get(start + t) - last) < 1e-6) { + return t; + } + } + return Infinity; +} + +/** + * The Reduce Motion cross-fade from `start` (design:reduced-motion DR1, + * DR2): the lens fades in on its new segment, full size, never moving; a copy + * of the surface fades out where `leavingFrom` rests, on the same clock; over + * in 200 ms or less. + */ +function expectReducedMotionCrossFade( + ctx: ReturnType, + start: number, + leavingFrom: string, +): void { + const entering = (t: number) => ctx.animator.get('opacity', t); + const fadeIn = endOf(entering, start); + expect(fadeIn).toBeGreaterThan(0); + expect(fadeIn).toBeLessThanOrEqual(200); + expect(entering(start)).toBeCloseTo(0, 6); + expect(entering(start + fadeIn)).toBeCloseTo(1, 6); + for (let t = 0; t <= fadeIn; t += 10) { + expect(ctx.animator.get('x', start + t)).toBe(0); + expect(ctx.animator.get('scaleX', start + t)).toBe(1); + expect(ctx.animator.get('scaleY', start + t)).toBe(1); + } + // The ::after, painted with the selected surface where it rested; no + // element is added for it. + expect(isLeaving(ctx)).toBe(true); + expect(ctx.layer('after', 'background-color')).toBe('rgb(255, 255, 255)'); + expect(ctx.layer('after', 'left')).toBe( + `${SEGMENTS[leavingFrom].left - TRACK.left}px`, + ); + expect(ctx.layer('after', 'width')).toBe(`${SEGMENTS[leavingFrom].width}px`); + expect(ctx.track.querySelectorAll('*').length).toBe(6); + const leavingOpacity = (t: number) => ctx.leavingAnimator.get('opacity', t); + expect(leavingOpacity(start)).toBeCloseTo(1, 6); + expect(endOf(leavingOpacity, start)).toBe(fadeIn); + for (let t = 0; t < fadeIn; t += 10) { + expect(ctx.leavingAnimator.get('x', start + t)).toBe(0); + expect(entering(start + t) + leavingOpacity(start + t)).toBeCloseTo(1, 6); + } +} + +/** Client x of a segment's center (the track starts at client x 10). */ +const clientCenterOf = (value: string) => + SEGMENTS[value].left + SEGMENTS[value].width / 2; + +/** One step of the style traffic `recordStyleTraffic` records. */ +type StyleEvent = + | {kind: 'take'; style: CSSStyleDeclaration} + | {kind: 'read'; style: CSSStyleDeclaration} + | {kind: 'write'}; + +describe('style reads at a change', () => { + /** + * Records, in order, each computed-style declaration taken, every value + * read from one, and every write to the track's inline style. A read from + * a declaration after a write to the track since it was taken makes the + * browser recompute style for it (a forced restyle). + */ + function recordStyleTraffic(track: HTMLElement) { + const events: StyleEvent[] = []; + const realGetComputedStyle = window.getComputedStyle.bind(window); + vi.stubGlobal( + 'getComputedStyle', + ( + element: Element, + pseudoElement?: string | null, + ): CSSStyleDeclaration => { + const style = realGetComputedStyle(element, pseudoElement); + events.push({kind: 'take', style}); + const readValue = (name: string): string => { + events.push({kind: 'read', style}); + return style.getPropertyValue(name); + }; + return new Proxy(style, { + // `getPropertyValue` and a property (`style.opacity`) both read. + get(target, key): string | ((name: string) => string) | undefined { + if (key === 'getPropertyValue') { + return readValue; + } + if (typeof key !== 'string') { + return undefined; + } + events.push({kind: 'read', style: target}); + const value = Reflect.get(target, key, target) as unknown; + return typeof value === 'string' ? value : undefined; + }, + }); + }, + ); + const setProperty = track.style.setProperty.bind(track.style); + track.style.setProperty = ( + name: string, + value: string | null, + priority?: string, + ) => { + events.push({kind: 'write'}); + setProperty(name, value, priority); + }; + /** Reads that follow a track write made after their declaration was taken. */ + return () => { + const takenAt = new Map(); + let reads = 0; + let forced = 0; + events.forEach((event, index) => { + if (event.kind === 'take') { + takenAt.set(event.style, index); + } else if (event.kind === 'read') { + reads += 1; + const from = takenAt.get(event.style) ?? 0; + if (events.slice(from, index).some(e => e.kind === 'write')) { + forced += 1; + } + } + }); + return {reads, forced}; + }; + } + + it('reads a segment’s whole surface before writing any of it to the track: no read follows a write, so a change restyles once, not once per property', () => { + reduceMotion = true; + const ctx = setup('grid'); + const traffic = recordStyleTraffic(ctx.track); + // Under Reduce Motion a change paints both layers: the lens and the + // surface leaving. + select(ctx, 'grid', 'table'); + const {reads, forced} = traffic(); + expect(reads).toBeGreaterThan(0); + expect(forced).toBe(0); + expect(ctx.layer('lens', 'background-color')).toBe('rgb(255, 255, 255)'); + expect(ctx.layer('after', 'background-color')).toBe('rgb(255, 255, 255)'); + }); + + it('a finger’s drag and its lift read before they write: no read follows a write, with or without Reduce Motion', () => { + for (const reduced of [false, true]) { + reduceMotion = reduced; + const ctx = setup('grid'); + const traffic = recordStyleTraffic(ctx.track); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + drag(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + select(ctx, 'grid', 'table'); + const {reads, forced} = traffic(); + expect(reads).toBeGreaterThan(0); + expect({reduced, forced}).toEqual({reduced, forced: 0}); + vi.unstubAllGlobals(); + document.body.innerHTML = ''; + document.head.innerHTML = ''; + } + }); +}); + +describe('under a finger', () => { + it('landing on the selected segment lifts nothing by default (the pressed-thumb lift is a theme’s): the lens and the ::after stay hidden', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + await advance(600); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expect(ctx.layer('after', 'visibility')).toBe(''); + expectOwnSurface(ctx.segments.grid); + }); + + it('a drag holds the lens at its resting size until the finger lets go, then it settles back and hands back', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('grid') + 10); + await advance(2000); + expect(ctx.motion.isSliding).toBe(true); + expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6); + expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6); + expect(release(ctx, clientCenterOf('grid'))).toBeNull(); + await advance(2000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + }); + + it('landing on another segment leaves the lens alone', () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + drag(ctx, clientCenterOf('list')); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + }); + + it('a commit that is not adopted (vetoed, or kept by the parent) sends the lens back, and the next change to that value still slides', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + // The commit's click ran (nobody vetoed it); the value has not come back. + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + await advance(60); + expect(ctx.motion.isSliding).toBe(true); + // Grid stays selected. + ctx.motion.decline(ctx.track, 'table'); + await advance(3000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + // A later change to Table slides from Grid: the declined commit is gone. + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(true); + expect(ctx.layer('lens', 'visibility')).toBe('visible'); + expect(ctx.animator.get('x', clock)).toBeCloseTo( + centerOf('grid') - centerOf('table'), + 6, + ); + }); + + it('a click the item vetoes sends the lens back at once', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + await advance(60); + ctx.motion.clicked(ctx.track, 'table', true); + // Bound for Grid again, from where it is. + await advance(3000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + expectNoOverride(ctx.segments.table); + }); + + it('a parent that adopts the value 200 ms later: no bounce, the lens keeps going and lands there', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + // The click was not vetoed; the value has not come back yet (the lens + // sets off once the click's event is over). + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + // Every frame until the parent adopts it heads for Table, never back. + let center = centerOf('table') + ctx.animator.get('x'); + for (let t = 0; t < 200; t += 16) { + await advance(16); + const next = centerOf('table') + ctx.animator.get('x'); + expect(next).toBeGreaterThanOrEqual(center - 1e-6); + center = next; + } + select(ctx, 'grid', 'table'); + await advance(3000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + expectNoOverride(ctx.segments.grid); + }); + + it('a value that never comes back: the lens goes back once its slide settles, the bound being the slide itself', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + release(ctx, clientCenterOf('table')); + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + // Mid-slide it still waits. + await advance(300); + expect(centerOf('table') + ctx.animator.get('x')).toBeGreaterThan( + centerOf('list'), + ); + await advance(6000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + expectNoOverride(ctx.segments.table); + }); + + it('the commit re-aims the lens at the destination’s box as it is once the new value shows (the titles’ weights move the segments)', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + // The commit's titles take their new weights: Table grows 4 px. + ctx.segments.table.getBoundingClientRect = () => + rect(206, TRACK.top + 2, 110, 27); + select(ctx, 'grid', 'table'); + expect(ctx.layer('lens', 'width')).toBe('110px'); + expect(ctx.layer('lens', 'left')).toBe('196px'); + await advance(3000); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.animator.get('scaleX')).toBe(1); + expect(ctx.motion.isSliding).toBe(false); + }); + + it('a resize while a finger holds the lens (the selected face reflows the titles) keeps it held', async () => { + const ctx = setup('grid'); + let width = TRACK.width; + Object.defineProperty(ctx.track, 'offsetWidth', {get: () => width}); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + width += 3; + ctx.motion.resized(ctx.track); + expect(ctx.motion.isSliding).toBe(true); + await advance(1000); + expect(ctx.motion.isSliding).toBe(true); + }); + + it('a drag carries the lens on the shared finger-tracking role, no further than 11 pt past the end segments', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + const chase = solveSpring(toSpring(springs.fingerTracking), { + from: 0, + to: centerOf('list') - centerOf('grid'), + velocity: 0, + }); + expect(ctx.animator.get('x', 1050)).toBeCloseTo(chase.value(0.05), 6); + await advance(1000); + expect(ctx.animator.get('x')).toBeCloseTo( + centerOf('list') - centerOf('grid'), + 6, + ); + // Far past the last segment: clamped. + drag(ctx, 500); + await advance(1000); + expect(ctx.animator.get('x')).toBeCloseTo( + centerOf('table') + segmentedControl.dragOvershoot - centerOf('grid'), + 6, + ); + // At its resting size throughout: nothing lifts it. + expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6); + expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6); + }); + + it('letting go commits the segment nearest the finger: 40 % of the way stays, 60 % moves', async () => { + const forty = setup('grid'); + const at = (p: number) => + clientCenterOf('grid') + + (clientCenterOf('list') - clientCenterOf('grid')) * p; + press(forty, clientCenterOf('grid')); + drag(forty, at(0.4)); + await advance(500); + expect(release(forty, at(0.4))).toBeNull(); + await advance(3000); + expect(forty.animator.get('x')).toBe(0); + expect(forty.motion.isSliding).toBe(false); + expectOwnSurface(forty.segments.grid); + document.body.innerHTML = ''; + document.head.innerHTML = ''; + + const sixty = setup('grid'); + press(sixty, clientCenterOf('grid')); + drag(sixty, at(0.6)); + await advance(500); + const centerAtLift = centerOf('grid') + sixty.animator.get('x'); + expect(release(sixty, at(0.6))).toBe('list'); + // Until the new value comes back, the old selection's paint is carried. + expectHidden(sixty.segments.grid); + // The commit (synchronous, through the segment's click) shows List: the + // lens re-bases onto it without a jump, then springs there on the slide + // spring while it comes down on the lift spring, painted by List. + select(sixty, 'grid', 'list'); + expect(centerOf('list') + sixty.animator.get('x')).toBeCloseTo( + centerAtLift, + 6, + ); + expect(sixty.layer('lens', 'width')).toBe('100px'); + expectHidden(sixty.segments.list); + expect(sixty.segments.grid.style.getPropertyValue('background-color')).toBe( + '', + ); + await advance(3000); + expect(sixty.animator.get('x')).toBe(0); + expect(sixty.animator.get('scaleX')).toBe(1); + expect(sixty.motion.isSliding).toBe(false); + expectOwnSurface(sixty.segments.list); + }); + + it('a tap on another segment slides there on the slide spring, at its resting size', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + select(ctx, 'grid', 'table'); + const travel = solveSpring(toSpring(segmentedControl.selectionSpring), { + from: centerOf('grid') - centerOf('table'), + to: 0, + velocity: 0, + }); + expect(ctx.animator.get('x', 1100)).toBeCloseTo(travel.value(0.1), 6); + // Nothing lifts it on the way: Grid's width grows to Table's on the + // same spring, and no further. + for (let t = 0; t <= 800; t += 20) { + expect(ctx.animator.get('scaleY', 1000 + t)).toBeCloseTo(1, 6); + expect(ctx.animator.get('scaleX', 1000 + t)).toBeLessThan(1.02); + } + await advance(2000); + expect(ctx.animator.get('scaleX')).toBe(1); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + }); + + it('a cancelled touch puts the lens back', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('table')); + await advance(200); + ctx.motion.cancel(); + await advance(3000); + expect(ctx.animator.get('x')).toBe(0); + expect(ctx.animator.get('scaleX')).toBe(1); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + }); + + it('the lens is bound only once a drag from the selected segment moves it', async () => { + const ctx = setup('grid'); + begin(ctx, clientCenterOf('grid')); + expect(ctx.motion.isSliding).toBe(false); + drag(ctx, clientCenterOf('list')); + expect(ctx.motion.isSliding).toBe(true); + await advance(1000); + expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6); + expect(ctx.layer('after', 'visibility')).toBe(''); + expect(release(ctx, clientCenterOf('list'))).toBe('list'); + }); + + it('a press cancelled before it drags leaves everything as it was', () => { + const ctx = setup('grid'); + begin(ctx, clientCenterOf('grid')); + ctx.motion.cancel(); + expect(ctx.motion.isSliding).toBe(false); + drag(ctx, clientCenterOf('list')); + expect(ctx.motion.isSliding).toBe(false); + }); + + it('never commits a disabled segment', () => { + const ctx = setup('grid'); + ctx.segments.table.setAttribute('aria-disabled', 'true'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBeNull(); + }); + + it('Reduced Motion: no lift, no chase; the drag commits at the lift and the selection cross-fades there, on any pointer (a touch release, DR2)', async () => { + reduceMotion = true; + // A fine primary pointer: the touch release still fades. + const ctx = setup('grid', {coarse: false}); + press(ctx, clientCenterOf('grid')); + expect(ctx.motion.isSliding).toBe(false); + // The lens stays parked on the selected segment while the finger moves. + drag(ctx, clientCenterOf('list')); + drag(ctx, clientCenterOf('table')); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + // The segment under the finger at the lift is committed... + const start = clock; + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + select(ctx, 'grid', 'table'); + // ...and the selection cross-fades there. + expect(ctx.layer('lens', 'width')).toBe('106px'); + expectReducedMotionCrossFade(ctx, start, 'grid'); + expectHidden(ctx.segments.table); + await advance(1000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + }); + + it('Reduced Motion: a hold and a lift on the selected segment change nothing', () => { + reduceMotion = true; + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + expect(release(ctx, clientCenterOf('grid'))).toBeNull(); + expect(ctx.motion.isSliding).toBe(false); + }); +}); + +describe('under a mouse or a pen (spec:AST-094 FR43)', () => { + /** + * A fine primary pointer: the touch presentation is off (a change keeps the + * theme's transition), and press tracking is on, as for every pointer. + */ + function setupFine(selected: string) { + const ctx = setup(selected, {coarse: false}); + ctx.motion.present(false); + return ctx; + } + + it('a change from a click, a key or a new value moves no lens: the theme’s transition shows it', () => { + const ctx = setupFine('grid'); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expectNoOverride(ctx.segments.grid); + expectNoOverride(ctx.segments.table); + }); + + it('a press that lifts on another segment with no drag moves no lens: its click selects through the theme’s transition', async () => { + const ctx = setupFine('grid'); + press(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expectNoOverride(ctx.segments.table); + }); + + it('a drag from the selected segment carries the lens on the pointer itself, written at each move, at its resting size and no further than 11 pt past the end segments', () => { + const ctx = setupFine('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + expect(ctx.motion.isSliding).toBe(true); + // Where the pointer is, at once: a pointer that holds the lens times it. + expect(ctx.animator.get('x')).toBeCloseTo( + centerOf('list') - centerOf('grid'), + 6, + ); + expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6); + expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6); + drag(ctx, 500); + expect(ctx.animator.get('x')).toBeCloseTo( + centerOf('table') + segmentedControl.dragOvershoot - centerOf('grid'), + 6, + ); + }); + + it('the lift commits the segment nearest the pointer; the lens settles there on the theme’s state-change spring and hands back', async () => { + const ctx = setupFine('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('table') - 5); + expect(release(ctx, clientCenterOf('table') - 5)).toBe('table'); + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + select(ctx, 'grid', 'table'); + const settle = solveSpring(toSpring(springs.stateChange), { + from: -5, + to: 0, + velocity: 0, + }); + expect(ctx.animator.get('x', 1100)).toBeCloseTo(settle.value(0.1), 4); + await advance(3000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.table); + }); + + it('a drag that starts on another segment carries nothing; the lift commits there through the theme’s transition', async () => { + const ctx = setupFine('grid'); + press(ctx, clientCenterOf('list')); + drag(ctx, clientCenterOf('table')); + expect(ctx.motion.isSliding).toBe(false); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + }); + + it('while the lens is carried the segments’ own transitions are off, so the surface it borrows neither fades out nor back in; they come back once it has handed back', async () => { + const ctx = setupFine('grid'); + ctx.segments.list.style.setProperty('transition-property', 'color'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + for (const segment of Object.values(ctx.segments)) { + expect(segment.style.getPropertyValue('transition-property')).toBe( + 'none', + ); + } + expect(release(ctx, clientCenterOf('grid'))).toBeNull(); + await advance(3000); + expect(ctx.motion.isSliding).toBe(false); + expectOwnSurface(ctx.segments.grid); + // Each segment's own inline value is back. + expect( + ctx.segments.grid.style.getPropertyValue('transition-property'), + ).toBe(''); + expect( + ctx.segments.list.style.getPropertyValue('transition-property'), + ).toBe('color'); + }); + + it('Reduced Motion: a drag holds nothing; the lift commits through the theme’s transition', async () => { + reduceMotion = true; + const ctx = setupFine('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('table')); + expect(ctx.motion.isSliding).toBe(false); + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + ctx.motion.clicked(ctx.track, 'table', false); + await Promise.resolve(); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(false); + expect(ctx.layer('lens', 'visibility')).toBe(''); + expect(ctx.layer('after', 'visibility')).toBe(''); + }); + + it('back under a finger (a touchscreen laptop flips its primary pointer), changes slide again', () => { + const ctx = setupFine('grid'); + ctx.motion.present(true); + select(ctx, 'grid', 'table'); + expect(ctx.motion.isSliding).toBe(true); + }); +}); + +describe('the titles under a finger', () => { + interface Recorded { + element: HTMLElement; + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + cancel: ReturnType; + } + let recorded: Recorded[] = []; + const realAnimate = HTMLElement.prototype.animate; + + beforeEach(() => { + recorded = []; + HTMLElement.prototype.animate = function ( + this: HTMLElement, + keyframes: Keyframe[] | PropertyIndexedKeyframes | null, + options?: number | KeyframeAnimationOptions, + ) { + const finished = new Promise(() => {}); + const cancel = vi.fn(); + if (this.getAttribute('role') !== 'radio') { + return {finished, cancel, startTime: null} as unknown as Animation; + } + recorded.push({ + element: this, + keyframes: keyframes as Keyframe[], + options: options as KeyframeAnimationOptions, + cancel, + }); + return {finished, cancel} as unknown as Animation; + }; + }); + + afterEach(() => { + HTMLElement.prototype.animate = realAnimate; + }); + + const titleOf = (segment: HTMLElement): HTMLElement => { + const title = segment.querySelector(TITLE_SELECTOR); + if (title == null) { + throw new Error('no title'); + } + return title; + }; + // Any fade the controller plays on a segment (none: a press shows the + // shared overlay, and nothing dims). + const fadesOf = (segment: HTMLElement) => + recorded.filter(r => r.element === segment); + const faceOf = (segment: HTMLElement) => ({ + weight: titleOf(segment).style.fontWeight, + color: titleOf(segment).style.color, + }); + const NO_FACE = {weight: '', color: ''}; + + it('a finger on an unselected segment dims nothing: no pressed state and no fade on it; the lens stays', () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('list')); + drag(ctx, clientCenterOf('table')); + for (const segment of Object.values(ctx.segments)) { + expect(segment.hasAttribute('data-pressed')).toBe(false); + expect(fadesOf(segment)).toEqual([]); + } + expect(ctx.motion.isSliding).toBe(false); + }); + + it('a tap on the selected segment dims nothing', () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + expect(release(ctx, clientCenterOf('grid'))).toBeNull(); + expect(recorded).toHaveLength(0); + }); + + it('during a lifted drag the selected face follows the lens, as a colour only (no weight swap mid-drag)', async () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('list')); + // The lens lags the finger: the face waits for it. + expect(faceOf(ctx.segments.list)).toEqual(NO_FACE); + await advance(400); + expect(faceOf(ctx.segments.list)).toEqual({ + weight: '', + color: 'rgb(10, 10, 10)', + }); + expect(faceOf(ctx.segments.grid)).toEqual({ + weight: '', + color: 'rgb(110, 110, 110)', + }); + expect(faceOf(ctx.segments.table)).toEqual(NO_FACE); + expect(recorded).toHaveLength(0); + drag(ctx, clientCenterOf('table')); + await advance(400); + expect(faceOf(ctx.segments.table).color).toBe('rgb(10, 10, 10)'); + expect(faceOf(ctx.segments.list)).toEqual(NO_FACE); + // The lift commits; the selection's own styles take over in its commit. + expect(release(ctx, clientCenterOf('table'))).toBe('table'); + select(ctx, 'grid', 'table'); + for (const segment of Object.values(ctx.segments)) { + expect(faceOf(segment)).toEqual(NO_FACE); + } + expect(recorded).toHaveLength(0); + }); + + it('the segment a lifted drag leaves wears an enabled segment’s unselected face, never a disabled one’s', async () => { + const ctx = setup('list'); + // The first segment in DOM order is disabled: its title has its own colour. + ctx.segments.grid.setAttribute('aria-disabled', 'true'); + press(ctx, clientCenterOf('list')); + drag(ctx, clientCenterOf('table')); + await advance(400); + expect(faceOf(ctx.segments.table).color).toBe('rgb(10, 10, 10)'); + expect(faceOf(ctx.segments.list)).toEqual({ + weight: '', + color: 'rgb(110, 110, 110)', + }); + }); + + it('the face crosses a boundary only once the lens is a quarter segment past it, so a ±3 px dither changes it at most once', async () => { + const ctx = setup('grid'); + const faced = () => + Object.entries(ctx.segments).find( + ([, segment]) => faceOf(segment).color === 'rgb(10, 10, 10)', + )?.[0] ?? 'grid'; + press(ctx, clientCenterOf('grid')); + // Grid | List boundary at x 108; List is 100 px wide: 25 px of hysteresis. + drag(ctx, 108 + 20); + await advance(400); + expect(faced()).toBe('grid'); + drag(ctx, 108 + 30); + await advance(400); + expect(faced()).toBe('list'); + // A slow dither of ±3 px around the boundary, the lens following it. + const seen = [faced()]; + for (let i = 0; i < 24; i++) { + drag(ctx, 108 + (i % 2 === 0 ? 3 : -3)); + await advance(50); + if (faced() !== seen.at(-1)) { + seen.push(faced()); + } + } + expect(seen.length - 1).toBeLessThanOrEqual(1); + }); + + it('a lifted drag back onto the selected segment, or a cancel, puts the faces back', () => { + const ctx = setup('grid'); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('table')); + drag(ctx, clientCenterOf('grid')); + expect(faceOf(ctx.segments.table)).toEqual(NO_FACE); + expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE); + drag(ctx, clientCenterOf('list')); + ctx.motion.cancel(); + expect(faceOf(ctx.segments.list)).toEqual(NO_FACE); + expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE); + press(ctx, clientCenterOf('grid')); + drag(ctx, clientCenterOf('table')); + expect(release(ctx, clientCenterOf('grid'))).toBeNull(); + expect(faceOf(ctx.segments.table)).toEqual(NO_FACE); + expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE); + }); + + it('a programmatic or keyboard change animates no title: the titles switch at once', () => { + const ctx = setup('grid'); + select(ctx, 'grid', 'table'); + expect(recorded).toHaveLength(0); + }); +}); diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts new file mode 100644 index 0000000000000..82e73d432080a --- /dev/null +++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts @@ -0,0 +1,1569 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useSegmentedSelectionMotion.ts + * @input The radiogroup element, the selected value, whether the touch + * presentation applies and whether a press is tracked (every pointer's, + * `spec:AST-094` FR43); the motion animator (motion/animator.ts), the + * UIKit constants table (motion/uikit, `segmentedControl`) and the touch + * tracking (useSegmentedTouchTracking.ts) + * @output Exports `useSegmentedSelectionMotion` (the React wiring, the touch + * tracking included), `SegmentedSelectionMotion` (the controller), + * `SURFACE_PROPERTIES` and `layerVariable` (the custom properties that paint + * the radiogroup's two pseudo-element layers) and the selectors that find a + * segment and its title: SegmentedControl's touch layer, the + * selection slide and the lens a finger drags and lets go of + * @position SegmentedControl's touch layer. Its one import site is + * SegmentedControl.tsx, which styles the radiogroup's ::before and ::after + * from these custom properties. + * + * WHAT MOVES, AND ON WHICH THREAD + * + * UISegmentedControl slides one selection indicator from the old segment to + * the new one on a spring (`segmentedControl.selectionSpring`), after a tap and + * after a programmatic change alike: UIKit's measured spring, played through + * its internal motion role (`segmented.selectionSpring`, `spec:AST-094` FR4), + * which no theme retunes while it stays internal (DEC-11). + * + * The selected segment paints its own raised surface at rest, so themes keep + * styling it as they always have. For the slide the lens takes over: the + * radiogroup's ::before pseudo-element, decoration with no element of its own + * (`architecture:component-style-authoring` INV7), painted from custom + * properties copied from the segment's computed surface. The segment hides its + * own surface (inline, so a theme rule cannot keep painting it) and the lens + * springs from the old segment's box to the new one's through the compositor + * animator: `translate` for the position and `scale` for the size, so nothing + * lays out or paints per frame and the slide keeps moving while JavaScript is + * busy. The lens is laid out on the destination's box, so it lands at + * translate 0 and scale 1 and hands the surface back to the segment pixel for + * pixel. It scales around its center, so its position (the center) and its + * size run on separate springs, as UIKit's lens position and bounds do. A + * change mid-flight starts from the presented geometry with its velocities + * (the animator evaluates its curves; the DOM is never read for it). The + * titles change with the selection, at once. + * + * UNDER A FINGER (useSegmentedTouchTracking.ts reports the touch) + * + * - Landing on the selected segment lifts nothing: a pressed thumb's lift is + * a theme's (a shared pressed-thumb lift role for draggable thumbs, none by + * default; the record owner's decision), not this table's. + * - Dragging from there carries the lens at its resting size: its center + * chases the finger on + * `springs.fingerTracking` (the shared `spec:AST-094` FR4 role, which + * UISegmentedControl's tracking values match), no further than + * `dragOvershoot` past the end segments. + * The selected title's colour follows the lens's presented center, moving + * to a neighbour only once the center is a quarter of that segment (at + * least 8 px) past the boundary (inline, until the commit's own styles take + * over); every title keeps its weight until the lift. + * - Letting go commits the segment nearest the finger: the lens springs + * there on `selectionSpring`. + * - A touch that lands on another segment leaves the lens alone until the + * finger lifts; then it slides there like any change. Meanwhile that + * segment shows the system's pressed overlay, as every pressable surface + * does under a finger (SegmentedControlItem.tsx keeps the shared press + * paint); nothing dims. + * - The value a finger lets go on is committed through that segment's click. + * The commit's titles take their new weights at once, so the lens aims at + * the destination's box as it is once the new value shows. A click the + * item vetoes sends the lens back at once; otherwise the lens waits for the + * value to come back (a parent may adopt it later, after renders that still + * show the old one), and goes back only if the slide settles without it. + * - At the lift the selected colour snaps to the segment nearest the finger, + * the one the lift commits, even where the hysteresis had kept it on a + * neighbour just past a boundary. + * - A cancelled touch (the page took it to scroll) puts the lens back. + * + * UNDER A MOUSE OR A PEN (a fine primary pointer, `spec:AST-094` FR43) + * + * Press tracking is every pointer's, so the same press commits the same + * segment; only the timing is the theme's (FR43's non-goals: a pointer + * presentation keeps the theme's timing). A click, a key or a new value + * keeps the theme's colour transition, with no lens. A drag from the + * selected segment carries the lens on the pointer itself, written at each + * move, and the lift's lens settles on the theme's state-change spring + * (`springs.stateChange`); the segments' own transitions are off while it is + * on screen, so the surface it borrows neither fades out nor back in. A drag + * that starts on another segment carries nothing: its lift commits there + * through the theme's transition. + * + * Reduced Motion (`design:reduced-motion`): nothing chases, travels or + * scales. Every change hands the animator an entrance at the new segment, so + * its Reduce Motion cross-fade lands the lens there and fades it in (a touch + * release fades on any pointer), while the radiogroup's ::after, painted + * with the surface that was on screen, fades out where it is on the same + * clock. + * + * SYNC: When modified, update: + * - /packages/core/src/SegmentedControl/SegmentedControl.tsx (the pseudo-elements) + * - /packages/core/src/SegmentedControl/SegmentedControlItem.tsx (the title marker) + * - /packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts + * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts + * - /packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts + */ + +import {useEffect, useRef, useState, type RefObject} from 'react'; +import { + createAnimator, + type AnimateOptions, + type Animator, + type MotionHandle, + type MotionValues, + type SpringTransition, +} from '../motion/animator'; +import { + registerSegmentedTable, + segmentedControl, +} from '../motion/uikit/segmented'; +import {registerSpringsTable, springs} from '../motion/uikit/springs'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import {observeResize} from '../utils/sharedResizeObserver'; +import {useSegmentedTouchTracking} from './useSegmentedTouchTracking'; + +/** The segments, in DOM order. */ +export const SEGMENT_SELECTOR = '[role="radio"][data-value]'; +/** + * The selected face moves to another segment only once the lens's center is + * this far past the boundary: a quarter of that segment's width, at least + * 8 px. + */ +const FACE_HYSTERESIS_RATIO = 0.25; +const FACE_HYSTERESIS_MIN_PX = 8; + +/** A segment's title: the text assistive technology reads. */ +export const TITLE_SELECTOR = '[data-segment-title]'; + +/** The selected surface's paint, copied into a layer's custom properties. */ +export const SURFACE_PROPERTIES: ReadonlyArray = [ + 'background-color', + 'background-image', + 'background-position', + 'background-size', + 'background-repeat', + 'background-origin', + 'background-clip', + 'box-shadow', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-right-radius', + 'border-bottom-left-radius', + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width', + 'border-top-style', + 'border-right-style', + 'border-bottom-style', + 'border-left-style', + 'border-top-color', + 'border-right-color', + 'border-bottom-color', + 'border-left-color', + 'backdrop-filter', + '-webkit-backdrop-filter', +]; + +/** + * The radiogroup's two pseudo-element layers: the lens (::before) and the + * ::after, which under Reduced Motion shows the surface that fades out where + * it is. + */ +export type Layer = 'lens' | 'after'; + +/** Box and visibility of a layer, besides its paint. */ +export const LAYER_GEOMETRY: ReadonlyArray = [ + 'left', + 'top', + 'width', + 'height', + 'visibility', +]; + +/** The custom property on the radiogroup that sets `property` of `layer`. */ +export function layerVariable(layer: Layer, property: string): string { + return `--_segmented-${layer}-${property.replace(/^-+/, '')}`; +} + +/** + * What the destination segment shows while the lens carries its surface. + * Written inline with priority so a theme's rule for the selected segment + * cannot paint a second surface; borders keep their width so nothing moves. + */ +const HIDDEN_SURFACE: ReadonlyArray = [ + ['background-color', 'transparent'], + ['background-image', 'none'], + ['box-shadow', 'none'], + ['border-top-color', 'transparent'], + ['border-right-color', 'transparent'], + ['border-bottom-color', 'transparent'], + ['border-left-color', 'transparent'], + ['backdrop-filter', 'none'], + ['-webkit-backdrop-filter', 'none'], +]; + +/** A title's face: what a dragging finger moves between titles. */ +interface TitleFace { + readonly color: string; + readonly fontWeight: string; +} + +/** A box in the track's padding-box coordinates, in CSS px. */ +interface Box { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +interface Carried { + /** The segment the lens is bound for: it lands there at rest. */ + readonly segment: HTMLElement; + /** + * The lens's layout box: the segment's, so it lands at translate 0 from + * the segment and scale 1, the segment's own size. + */ + readonly box: Box; + /** + * The segment whose surface the lens shows, hidden there meanwhile: the + * selected one. A touch moves the lens before the new value comes back, + * so until then this is still the old selection. + */ + hidden: HTMLElement; + /** The track's layout size when the box was measured. */ + readonly trackSize: {readonly width: number; readonly height: number}; +} + +/** A finger's touch, from landing to letting go. */ +interface Touch { + /** The track's geometry when the finger landed (read once). */ + readonly toTrackX: (clientX: number) => number; + readonly boxes: ReadonlyMap; + /** The segment the finger landed on, if any (the tracker's begin target). */ + readonly origin: HTMLElement | null; + /** Whether it landed on the selected segment (a drag carries the lens). */ + readonly carriesLens: boolean; + /** The selected title's face and an unselected one, read at landing. */ + readonly faces: { + readonly selected: TitleFace; + readonly unselected: TitleFace; + } | null; +} + +/** + * The motion a release starts once its commit's click has run: on the + * destination's box as it is when the new value shows (the titles' new + * weights move the segments), or on the box measured at landing while the + * value has not come back. + */ +interface Pending { + readonly destination: HTMLElement; + /** The destination's box when the finger landed. */ + readonly box: Box; + /** The held lens settles there; otherwise it slides from `from`. */ + readonly isHeld: boolean; + /** The selected segment's box: where a tap's slide starts. */ + readonly from: Box | null; +} + +function faceOf(element: HTMLElement): TitleFace { + const style = getComputedStyle(element); + return {color: style.color, fontWeight: style.fontWeight}; +} + +/** + * A hidden segment's own inline declarations (its `style`) for the properties + * `hideSurface` overrides: value and priority, restored by `showSurface`. + */ +const ownSurface = new WeakMap< + HTMLElement, + ReadonlyArray +>(); + +function hideSurface(segment: HTMLElement): void { + if (!ownSurface.has(segment)) { + ownSurface.set( + segment, + HIDDEN_SURFACE.map(([property]) => [ + property, + segment.style.getPropertyValue(property), + segment.style.getPropertyPriority(property), + ]), + ); + } + for (const [property, value] of HIDDEN_SURFACE) { + segment.style.setProperty(property, value, 'important'); + } +} + +/** Gives a hidden segment its surface back, its own inline values included. */ +function showSurface(segment: HTMLElement): void { + const own = ownSurface.get(segment); + if (own == null) { + return; + } + ownSurface.delete(segment); + for (const [property, value, priority] of own) { + if (value === '') { + segment.style.removeProperty(property); + } else { + segment.style.setProperty(property, value, priority); + } + } +} + +/** + * Paints `layer` with `segment`'s computed surface. Every value is read + * before any is written: a write to the track's style makes the next read + * from a computed style recompute it, so interleaving them restyled the + * control once per property. + */ +function paintLayer( + track: HTMLElement, + layer: Layer, + segment: HTMLElement, +): void { + const style = getComputedStyle(segment); + const values = SURFACE_PROPERTIES.map(property => + style.getPropertyValue(property), + ); + SURFACE_PROPERTIES.forEach((property, index) => { + track.style.setProperty(layerVariable(layer, property), values[index]); + }); +} + +/** Copies the lens's paint onto the ::after. */ +function copyLensPaint(track: HTMLElement): void { + for (const property of SURFACE_PROPERTIES) { + track.style.setProperty( + layerVariable('after', property), + track.style.getPropertyValue(layerVariable('lens', property)), + ); + } +} + +/** Lays `layer` out on `box` and shows it. */ +function placeLayer(track: HTMLElement, layer: Layer, box: Box): void { + track.style.setProperty(layerVariable(layer, 'left'), `${box.x}px`); + track.style.setProperty(layerVariable(layer, 'top'), `${box.y}px`); + track.style.setProperty(layerVariable(layer, 'width'), `${box.width}px`); + track.style.setProperty(layerVariable(layer, 'height'), `${box.height}px`); + track.style.setProperty(layerVariable(layer, 'visibility'), 'visible'); +} + +/** Hides `layer` and drops its custom properties. */ +function clearLayer(track: HTMLElement, layer: Layer): void { + for (const property of [...LAYER_GEOMETRY, ...SURFACE_PROPERTIES]) { + track.style.removeProperty(layerVariable(layer, property)); + } +} + +/** + * The scale an ancestor transform applies to the track's client rects. The + * lens lays out untransformed. `offsetWidth` is rounded to whole pixels, so a + * fractional track width reads as a scale a little off 1 with no transform at + * all; only a real transform moves it further than that rounding can. + */ +function scaleOf(track: HTMLElement, rect: DOMRect): number { + if (track.offsetWidth <= 0 || rect.width <= 0) { + return 1; + } + return Math.abs(rect.width - track.offsetWidth) <= 1 + ? 1 + : rect.width / track.offsetWidth; +} + +/** Boxes relative to the track's padding box. */ +function boxesIn(track: HTMLElement): (element: HTMLElement) => Box { + const trackRect = track.getBoundingClientRect(); + const scale = scaleOf(track, trackRect); + return element => { + const rect = element.getBoundingClientRect(); + return { + x: (rect.left - trackRect.left) / scale - track.clientLeft, + y: (rect.top - trackRect.top) / scale - track.clientTop, + width: rect.width / scale, + height: rect.height / scale, + }; + }; +} + +/** Maps a client x to the track's padding-box x, read once per touch. */ +function trackXIn(track: HTMLElement): (clientX: number) => number { + const rect = track.getBoundingClientRect(); + const scale = scaleOf(track, rect); + return clientX => (clientX - rect.left) / scale - track.clientLeft; +} + +function segmentsOf(track: HTMLElement): HTMLElement[] { + return Array.from(track.querySelectorAll(SEGMENT_SELECTOR)); +} + +function isLaidOut(box: Box): boolean { + return box.width > 0 && box.height > 0; +} + +function center(box: Box): number { + return box.x + box.width / 2; +} + +/** Whether two boxes are the same to a quarter of a pixel. */ +function isSameBox(a: Box, b: Box): boolean { + return ( + Math.abs(a.x - b.x) < 0.25 && + Math.abs(a.y - b.y) < 0.25 && + Math.abs(a.width - b.width) < 0.25 && + Math.abs(a.height - b.height) < 0.25 + ); +} + +function isEnabledSegment(segment: HTMLElement): boolean { + return ( + !segment.hasAttribute('disabled') && + segment.getAttribute('aria-disabled') !== 'true' + ); +} + +function titleOf(segment: HTMLElement): HTMLElement | null { + return segment.querySelector(TITLE_SELECTOR); +} + +/** What the control reads of its selection motion. */ +export interface SegmentedSelection { + /** + * A press is down on the control (any pointer's): the segment it lifts on + * is what commits, so a focus move it causes selects nothing. + */ + readonly isPressing: () => boolean; +} + +export interface SegmentedSelectionMotionOptions { + /** The animator's clock (ms, document timeline); `performance.now()` by default. */ + readonly now?: () => number; + /** + * The animator for the radiogroup's ::after (the surface that fades out + * under Reduced Motion); one of its own by default. + */ + readonly afterAnimator?: Animator; +} + +function defaultNow(): number { + return typeof performance === 'undefined' ? Date.now() : performance.now(); +} + +/** + * The selection motion of one SegmentedControl. Lives outside React's render + * cycle: nothing here sets state, so a slide never re-renders anything. + */ +export class SegmentedSelectionMotion { + private track: HTMLElement | null = null; + private carried: Carried | null = null; + /** + * Segments whose surface the lens carried until a change turned it + * elsewhere. They stay surface-hidden until it lands: a tap's press is + * still fading on such a segment, and its paint would cover the lens (which + * sits under the segments' backgrounds) while the lens is still crossing it. + */ + private readonly abandoned = new Set(); + /** The segment showing the selected face under a dragging finger. */ + private facedSegment: HTMLElement | null = null; + /** The frame request that keeps the face on the lens while it is carried. */ + private lensFrame: number | null = null; + /** Titles wearing another face for the drag (inline weight and color). */ + private readonly faceOverrides = new Set(); + /** The motions the hand-back waits for. */ + private readonly running = new Set(); + /** A finger holds the lens: a drag from the selected segment carries it. */ + private isHeld = false; + /** + * The touch presentation applies (a coarse primary pointer): every change + * slides on UIKit's springs. Off, under a fine primary pointer + * (`spec:AST-094` FR43), a change keeps the theme's transition and only a + * drag from the selected segment carries the lens, on the pointer itself; + * what the pointer does not hold settles on the theme's state-change + * spring (`springs.stateChange`, the role that follows the theme). + */ + private isPresenting = true; + /** + * Segments whose own transitions are off while a fine pointer's carry is + * on screen, with their own inline values to give back. + */ + private readonly stilled = new Map(); + /** The frame request that gives the stilled segments their transitions back. */ + private thawFrame: number | null = null; + private touch: Touch | null = null; + /** + * The value a touch already moved the lens to: the selection change that + * follows (the controlled value coming back) re-aims the lens. + */ + private committed: string | null = null; + /** + * The commit's click ran without a veto: the lens waits for the value + * until the slide settles. + */ + private isAwaitingValue = false; + /** The motion a release starts once its commit's click has run. */ + private pending: Pending | null = null; + /** The ::after shows the leaving surface (Reduced Motion). */ + private isLeavingShown = false; + /** Bumped by every leaving fade; a finished fade clears only its own. */ + private leaving = 0; + + private readonly now: () => number; + /** The ::after: the surface fading out under Reduced Motion. */ + private readonly after: Animator; + + constructor( + private readonly animator: Animator = createAnimator(null, { + pseudoElement: '::before', + }), + options: SegmentedSelectionMotionOptions = {}, + ) { + // The chase plays the shared role `springs.fingerTracking`, and the + // slide the segmented role (`spec:AST-094` FR4): registered before the + // first animation (idempotent; nothing registers on import). + registerSpringsTable(); + registerSegmentedTable(); + this.now = options.now ?? defaultNow; + this.after = + options.afterAnimator ?? + createAnimator(null, {pseudoElement: '::after', initial: {opacity: 0}}); + } + + /** Attaches the radiogroup whose pseudo-elements are the lens (null detaches). */ + attachTrack(element: HTMLElement | null): void { + if (element !== this.track) { + this.settle(); + } + this.track = element; + this.animator.attach(element); + this.after.attach(element); + } + + /** True while the lens carries the selected surface. */ + get isSliding(): boolean { + return this.carried != null; + } + + /** A press (any pointer's) is down on the control, from landing to letting go. */ + get isPressed(): boolean { + return this.touch != null; + } + + /** + * Whether the touch presentation applies. Off (a fine primary pointer, + * `spec:AST-094` FR43), a change keeps the theme's transition, and a drag + * from the selected segment still carries the lens. A change of + * presentation hands anything in flight back. + */ + present(isPresenting: boolean): void { + if (this.isPresenting === isPresenting) { + return; + } + this.isPresenting = isPresenting; + this.settle(); + } + + /** The segment that commits `value`, if the track has one. */ + segmentFor(track: HTMLElement, value: string): HTMLElement | null { + return ( + segmentsOf(track).find(segment => segment.dataset.value === value) ?? null + ); + } + + /** The selection moved from `from` to `to`; the DOM already shows `to`. */ + select(track: HTMLElement, from: string, to: string): void { + if (this.track !== track) { + return; + } + const origin = this.segmentFor(track, from); + const destination = this.segmentFor(track, to); + const isTouchCommit = this.committed === to; + // The commit's own styles take over from a drag's borrowed faces. + this.clearFaces(); + this.committed = null; + this.isAwaitingValue = false; + if (isTouchCommit) { + if (this.pending?.destination === destination && destination != null) { + // Adopted during the click: the lens moves now, on the box the + // destination has with the new value shown. + this.startPending(destination, boxesIn(track)(destination)); + } + // The new selection now paints the surface the lens carries, and its + // titles' weights may have moved the segments since the lens set off. + const carried = this.carried; + if (carried != null && carried.segment === destination) { + if (carried.hidden !== destination) { + showSurface(carried.hidden); + paintLayer(track, 'lens', destination); + hideSurface(destination); + carried.hidden = destination; + } + this.reaim(track, destination); + } + return; + } + if (!this.isPresenting) { + // A click, a key or a new value under a fine pointer: the theme's + // transition shows the change. + this.settle(); + return; + } + if (destination == null) { + // Nothing is selected any more: no surface to carry. + this.settle(); + return; + } + if (this.carried == null && origin == null) { + // Nothing was selected: there is no surface to slide from. + return; + } + const boxOf = boxesIn(track); + const to_ = boxOf(destination); + if (!isLaidOut(to_)) { + this.settle(); + return; + } + const from_ = this.carried == null ? boxOf(origin as HTMLElement) : null; + if (this.animator.reducedMotion() !== 'off') { + this.crossFadeTo(destination, to_, from_, destination, false); + return; + } + const at = this.carry(destination, to_, from_, destination); + // A programmatic or keyboard change: the whole box on the slide spring. + this.springLens( + {x: 0, scaleX: 1, scaleY: 1}, + this.springFrom({x: 0, scaleX: 1, scaleY: 1}, 'selection'), + {at}, + ); + } + + /** + * A finger landed on `origin`, the segment the action-group tracker + * resolved for it (null: none): the track's geometry and title faces, read + * once. + */ + begin(track: HTMLElement, origin: HTMLElement | null): void { + const segments = segmentsOf(track); + const boxOf = boxesIn(track); + const boxes = new Map(segments.map(segment => [segment, boxOf(segment)])); + const toTrackX = trackXIn(track); + const selected = + segments.find( + segment => segment.getAttribute('aria-checked') === 'true', + ) ?? null; + const carriesLens = origin != null && origin === selected; + const selectedTitle = selected != null ? titleOf(selected) : null; + // An enabled segment's unselected face: a disabled title has its own. + const other = segments.find( + segment => segment !== selected && isEnabledSegment(segment), + ); + const otherTitle = other != null ? titleOf(other) : null; + const faces = + selectedTitle != null && otherTitle != null + ? {selected: faceOf(selectedTitle), unselected: faceOf(otherTitle)} + : null; + this.touch = { + toTrackX, + boxes, + origin, + carriesLens, + faces, + }; + } + + /** + * The finger moved to `clientX`. A drag from the selected segment carries + * the lens at its resting size; a touch elsewhere leaves it alone (that + * segment shows the system's pressed overlay). + */ + drag(clientX: number): void { + const touch = this.touch; + if (touch == null || !touch.carriesLens) { + return; + } + this.hold(); + if (!this.isHeld) { + return; + } + this.chase(clientX); + this.followLens(); + } + + /** + * The first move of a drag from the selected segment binds the lens there, + * at its resting size. Reduced Motion: nothing chases, so nothing is held + * (the lens stays parked until the release cross-fades). + */ + private hold(): void { + const touch = this.touch; + if ( + touch == null || + touch.origin == null || + this.isHeld || + this.animator.reducedMotion() !== 'off' + ) { + return; + } + const box = touch.boxes.get(touch.origin) as Box; + if (!isLaidOut(box)) { + return; + } + if (!this.isPresenting) { + // Before the surface is borrowed: it must not fade out. + this.stillTransitions(); + } + this.carry(touch.origin, box, null, touch.origin); + this.isHeld = true; + } + + /** + * The selected face follows the held lens: the segment the lens's + * presented center is over, with hysteresis around each boundary (a + * quarter of the segment's width, at least 8 px), so a finger resting on a + * boundary never flips it back and forth. It runs every frame while the + * lens is held, so the face keeps up as the lens settles under a still + * finger. + */ + private followLens(): void { + const touch = this.touch; + const carried = this.carried; + if ( + touch == null || + !touch.carriesLens || + !this.isHeld || + carried == null || + touch.origin == null + ) { + this.lensFrame = null; + return; + } + const lensCenter = this.presented(carried.box, this.now()).center; + const spans = [...touch.boxes.entries()] + .filter(([segment]) => isEnabledSegment(segment)) + .sort((a, b) => a[1].x - b[1].x); + const current = this.facedSegment ?? touch.origin; + const at = spans.findIndex(([segment]) => segment === current); + if (at >= 0) { + const edge = (i: number) => + (spans[i][1].x + spans[i][1].width + spans[i + 1][1].x) / 2; + let next = at; + while (next + 1 < spans.length && lensCenter > edge(next)) { + next += 1; + } + while (next > 0 && lensCenter < edge(next - 1)) { + next -= 1; + } + if (next !== at) { + const boundary = next > at ? edge(at) : edge(at - 1); + const hysteresis = Math.max( + FACE_HYSTERESIS_MIN_PX, + FACE_HYSTERESIS_RATIO * spans[next][1].width, + ); + if (Math.abs(lensCenter - boundary) >= hysteresis) { + const segment = spans[next][0]; + this.showFaceAt(segment === touch.origin ? null : segment); + } + } + } + const view = this.track?.ownerDocument.defaultView; + if (this.lensFrame == null && view != null) { + this.lensFrame = view.requestAnimationFrame(() => { + this.lensFrame = null; + this.followLens(); + }); + } + } + + /** The held lens's center chases the finger at `clientX`. */ + private chase(clientX: number): void { + const touch = this.touch; + const carried = this.carried; + if (touch == null || carried == null) { + return; + } + const centers = [...touch.boxes.values()].map(center); + const reach = segmentedControl.dragOvershoot; + const target = Math.min( + Math.max(touch.toTrackX(clientX), Math.min(...centers) - reach), + Math.max(...centers) + reach, + ); + if (!this.isPresenting) { + // A mouse or a pen holds the lens itself: it is where the pointer is, + // written at each move (the theme times only what it does not hold). + this.animator.set({x: target - center(carried.box)}); + return; + } + // The center chases the finger; the size stays at rest. Each chase starts + // at the call (an explicit start): a call from rest waits for the + // browser to start it, and on Android Chrome, whose touch moves arrive + // once a frame, the next move came before that start was known, so every + // move started the chase from rest again and the lens stuck to its + // segment until the finger stopped (or followed it, when the start came + // in time). + const at = this.now(); + this.springLens( + {x: target - center(carried.box)}, + this.springFrom({x: target - center(carried.box)}, 'tracking'), + {at}, + ); + } + + /** + * The finger let go on `target`, the segment the tracker resolved for it + * (null: none, or a disabled one). Moves the lens there and returns its + * value when it is not the selected one (the tracker's lift commits it + * through its click), else null. + */ + release(target: HTMLElement | null): string | null { + const touch = this.touch; + this.touch = null; + if (touch == null) { + return null; + } + const selected = + [...touch.boxes.keys()].find( + segment => segment.getAttribute('aria-checked') === 'true', + ) ?? null; + // A disabled segment never commits: the lens settles back on the + // selection. + const destination = + (target != null && isEnabledSegment(target) ? target : null) ?? selected; + if (destination == null) { + this.clearFaces(); + if (this.isHeld) { + this.isHeld = false; + this.settle(); + } + return null; + } + const box = touch.boxes.get(destination) as Box; + const value = + destination !== selected ? (destination.dataset.value ?? null) : null; + // A drag's borrowed face stays only if the lift commits (the commit + // takes it over). + if (value == null) { + this.clearFaces(); + } + const isHeld = touch.carriesLens && this.isHeld; + this.committed = value; + this.isAwaitingValue = false; + if (value == null) { + if (isHeld) { + // The held lens settles back on the selection. + this.moveLensTo(destination, box, selected ?? destination); + } + return null; + } + // The commit follows at once, through the segment's click; the lens + // moves once it has run, on the box the destination has then. A held + // lens settles there; a tap (or a drag that started elsewhere) slides + // there from the selected segment. + // Under a fine pointer only a held lens moves: a click's change, or a + // drag's from elsewhere, shows through the theme's transition. + if (isHeld || (selected != null && this.isPresenting)) { + this.pending = { + destination, + box, + isHeld, + from: + !isHeld && selected != null + ? (touch.boxes.get(selected) as Box) + : null, + }; + } + return value; + } + + /** + * The commit's click for `value` has run. A cancelled click (the item's + * `onClick` vetoed it) sends the lens back at once; otherwise the lens + * waits for the value, which a parent may adopt later. + */ + clicked(track: HTMLElement, value: string, isCancelled: boolean): void { + if (this.committed !== value) { + // Adopted during the click, or superseded. + return; + } + if (isCancelled) { + this.pending = null; + this.decline(track, value); + return; + } + this.isAwaitingValue = true; + // React may render the click's change only once the event that + // dispatched it is over (a click inside a touch handler is batched with + // it): give it that turn. Adopted then, the lens has already moved on + // the new box; otherwise it heads for the box measured at landing and + // re-aims when the value comes back. + queueMicrotask(() => { + if (this.committed === value && this.pending != null) { + this.startPending(this.selectedIn(track)); + } + }); + } + + /** + * The value the finger let go on was not adopted (the item's `onClick` + * vetoed it, or a controlled parent kept its value): the lens goes back to + * the selected segment, and the next change to that value slides as any + * change does. + */ + decline(track: HTMLElement, value: string): void { + if (this.committed !== value) { + return; + } + this.committed = null; + this.isAwaitingValue = false; + this.pending = null; + this.clearFaces(); + const selected = + segmentsOf(track).find( + segment => segment.getAttribute('aria-checked') === 'true', + ) ?? null; + if (selected == null || this.carried == null) { + this.settle(); + return; + } + const box = boxesIn(track)(selected); + if (!isLaidOut(box)) { + this.settle(); + return; + } + this.moveLensTo(selected, box, selected); + } + + /** The touch was taken away (the page scrolled): the lens goes back. */ + cancel(): void { + const touch = this.touch; + this.touch = null; + this.clearFaces(); + if ( + touch == null || + !touch.carriesLens || + touch.origin == null || + !this.isHeld + ) { + // Nothing was held: nothing to put back. + return; + } + const box = touch.boxes.get(touch.origin) as Box; + this.moveLensTo(touch.origin, box, touch.origin); + } + + /** Hands the surface back to its segment now and hides the lens. */ + settle(): void { + this.endLeaving(); + this.isHeld = false; + this.pending = null; + const carried = this.carried; + if (carried != null) { + this.carried = null; + this.running.clear(); + this.animator.stop(); + this.after.stop(); + showSurface(carried.hidden); + for (const segment of this.abandoned) { + showSurface(segment); + } + this.abandoned.clear(); + if (this.track != null) { + clearLayer(this.track, 'lens'); + clearLayer(this.track, 'after'); + } + this.isLeavingShown = false; + } + // Once the surfaces are back on screen, so nothing fades in. + this.thawTransitions(); + } + + /** + * The control resized. The lens aims at boxes measured when its motion + * began, so it hands the surface back rather than land somewhere stale, + * unless the track still has the size it had then (the change itself + * resized it: a title takes its new weight, and a content-sized control + * follows, and the box was measured after that) or a finger holds it. + */ + resized(track: HTMLElement): void { + const carried = this.carried; + // A finger holding the lens reflows the titles itself (the selected face + // moves to the title under it): the lens follows the finger, and the + // commit measures the destination again. + if (carried == null || this.touch != null) { + return; + } + if ( + Math.abs(track.offsetWidth - carried.trackSize.width) < 0.5 && + Math.abs(track.offsetHeight - carried.trackSize.height) < 0.5 + ) { + return; + } + this.settle(); + } + + /** + * Ends everything in flight (unmount). The controller stays usable, so an + * effect cleanup followed by a setup (StrictMode's extra mount) loses + * nothing. + */ + stop(): void { + this.touch = null; + if (this.lensFrame != null) { + this.track?.ownerDocument.defaultView?.cancelAnimationFrame( + this.lensFrame, + ); + this.lensFrame = null; + } + this.committed = null; + this.isAwaitingValue = false; + this.clearFaces(); + this.settle(); + this.cancelThaw(); + this.restoreTransitions(); + } + + /** + * A fine pointer's carry: the segments' own transitions go off while the + * lens is on screen, so the surface it borrows neither fades out nor back + * in (under a finger the touch presentation already turns them off). + */ + private stillTransitions(): void { + const track = this.track; + if (track == null) { + return; + } + this.cancelThaw(); + for (const segment of segmentsOf(track)) { + if (!this.stilled.has(segment)) { + this.stilled.set(segment, [ + segment.style.getPropertyValue('transition-property'), + segment.style.getPropertyPriority('transition-property'), + ]); + } + segment.style.setProperty('transition-property', 'none', 'important'); + } + } + + /** + * Gives the stilled segments their transitions back two frames after the + * hand-back, once the surfaces it gave back have been on screen. + */ + private thawTransitions(): void { + if (this.stilled.size === 0 || this.thawFrame != null) { + return; + } + const view = this.track?.ownerDocument.defaultView; + if (view == null) { + this.restoreTransitions(); + return; + } + this.thawFrame = view.requestAnimationFrame(() => { + this.thawFrame = view.requestAnimationFrame(() => { + this.thawFrame = null; + this.restoreTransitions(); + }); + }); + } + + private cancelThaw(): void { + if (this.thawFrame != null) { + this.track?.ownerDocument.defaultView?.cancelAnimationFrame( + this.thawFrame, + ); + this.thawFrame = null; + } + } + + private restoreTransitions(): void { + for (const [segment, [value, priority]] of this.stilled) { + if (value === '') { + segment.style.removeProperty('transition-property'); + } else { + segment.style.setProperty('transition-property', value, priority); + } + } + this.stilled.clear(); + } + + /** The selected segment, as the DOM shows it now. */ + private selectedIn(track: HTMLElement): HTMLElement | null { + return ( + segmentsOf(track).find( + segment => segment.getAttribute('aria-checked') === 'true', + ) ?? null + ); + } + + /** + * Starts the motion the release left pending: on `box` (the destination's + * box now) or the box measured at landing, showing `paint`'s surface (the + * selected segment's). + */ + private startPending(paint: HTMLElement | null, box?: Box): void { + const pending = this.pending; + this.pending = null; + if (pending == null) { + return; + } + const to = box ?? pending.box; + const surface = this.carried?.hidden ?? paint ?? pending.destination; + if (pending.isHeld) { + this.moveLensTo(pending.destination, to, surface); + } else if (pending.from != null) { + this.slideTo(pending.destination, to, pending.from, surface); + } + } + + /** + * Aims the lens at `destination`'s box as it is now: a value adopted + * after its click (mid-flight) moves the segments with its titles' new + * weights. + */ + private reaim(track: HTMLElement, destination: HTMLElement): void { + const carried = this.carried; + if (carried == null) { + return; + } + const box = boxesIn(track)(destination); + if (!isLaidOut(box) || isSameBox(box, carried.box)) { + return; + } + this.moveLensTo(destination, box, carried.hidden); + } + + /** + * Binds the lens for `segment` with `box` as its layout box, showing + * `paint`'s surface (the selected segment's), keeping what is on screen: + * from `from` (a segment's resting box) when nothing was carried, else + * from the presented geometry, re-based onto the new box with the + * velocities it had. + */ + private carry( + segment: HTMLElement, + box: Box, + from: Box | null, + paint: HTMLElement, + ): number | undefined { + const track = this.track; + if (track == null) { + return undefined; + } + const previous = this.carried; + let start: MotionValues; + // Motion already on screen continues from this instant; a start from + // rest waits for the browser to commit it (the animator's rule). + let at: number | undefined; + this.velocity = {}; + if (previous != null) { + at = this.now(); + const presented = this.presented(previous.box, at); + start = { + x: presented.center - center(box), + scaleX: presented.width / box.width, + scaleY: presented.height / box.height, + }; + this.velocity = { + x: this.animator.getVelocity('x', at), + scaleX: + (this.animator.getVelocity('scaleX', at) * previous.box.width) / + box.width, + scaleY: + (this.animator.getVelocity('scaleY', at) * previous.box.height) / + box.height, + }; + } else { + const origin = from ?? box; + start = { + x: center(origin) - center(box), + scaleX: origin.width / box.width, + scaleY: origin.height / box.height, + }; + } + if (previous?.hidden !== paint) { + if (previous != null) { + this.abandoned.add(previous.hidden); + } + // A segment abandoned mid-flight still has its surface hidden: read + // its paint with it shown. + if (this.abandoned.has(paint)) { + showSurface(paint); + } + paintLayer(track, 'lens', paint); + hideSurface(paint); + this.abandoned.delete(paint); + } + placeLayer(track, 'lens', box); + this.carried = { + segment, + box, + hidden: paint, + trackSize: {width: track.offsetWidth, height: track.offsetHeight}, + }; + // Opaque, whatever a Reduce Motion fade left. + this.animator.set({...start, opacity: 1}); + return at; + } + + /** Velocities captured by the last `carry`, in the new box's units. */ + private velocity: Partial> = {}; + + /** A spring transition that keeps the captured velocities of `values`. */ + private springFrom( + values: MotionValues, + kind: 'selection' | 'tracking', + ): SpringTransition { + // Under a fine pointer the theme times the motion: the state-change role + // (`spec:AST-094` FR43, FR4), not UIKit's measured springs. + const spring = !this.isPresenting + ? springs.stateChange + : kind === 'selection' + ? segmentedControl.selectionSpring + : springs.fingerTracking; + const velocity: Record = {}; + for (const key of Object.keys(values) as (keyof typeof this.velocity)[]) { + const v = this.velocity[key]; + if (v != null && v !== 0) { + velocity[key] = v; + } + } + // A captured velocity is spent by the first call that drives its channel. + this.velocity = Object.fromEntries( + Object.entries(this.velocity).filter(([key]) => !(key in values)), + ); + return Object.keys(velocity).length > 0 ? {spring, velocity} : {spring}; + } + + /** Springs the lens toward `values`. */ + private springLens( + values: MotionValues, + transition: SpringTransition, + options?: AnimateOptions, + ): void { + this.trackHandle(this.animator.animate(values, transition, options)); + } + + /** The lens's presented center and size, from the animator. */ + private presented( + box: Box, + at: number, + ): {center: number; width: number; height: number} { + return { + center: center(box) + this.animator.get('x', at), + width: box.width * this.animator.get('scaleX', at), + height: box.height * this.animator.get('scaleY', at), + }; + } + + /** The lens settles on `segment`, at its resting size. */ + private moveLensTo(segment: HTMLElement, box: Box, paint: HTMLElement): void { + this.isHeld = false; + if (!isLaidOut(box)) { + this.settle(); + return; + } + if (this.animator.reducedMotion({touchRelease: true}) !== 'off') { + // A touch released it (or declined its commit): it fades on any + // pointer. + this.crossFadeTo(segment, box, null, this.carried?.hidden ?? paint, true); + return; + } + const at = this.carry(segment, box, null, this.carried?.hidden ?? paint); + this.springLens( + {x: 0, scaleX: 1, scaleY: 1}, + this.springFrom({x: 0, scaleX: 1, scaleY: 1}, 'selection'), + {at}, + ); + } + + /** A tap's slide: from `from` to `segment` on the slide spring. */ + private slideTo( + segment: HTMLElement, + box: Box, + from: Box, + paint: HTMLElement, + ): void { + if (!isLaidOut(box)) { + this.settle(); + return; + } + if (this.animator.reducedMotion({touchRelease: true}) !== 'off') { + // A tap's release: no travel; it fades on any pointer. + this.crossFadeTo( + segment, + box, + this.carried == null ? from : null, + this.carried?.hidden ?? paint, + true, + ); + return; + } + const at = this.carry( + segment, + box, + this.carried == null ? from : null, + this.carried?.hidden ?? paint, + ); + this.springLens( + {x: 0, scaleX: 1, scaleY: 1}, + this.springFrom({x: 0, scaleX: 1, scaleY: 1}, 'selection'), + {at}, + ); + } + + /** + * Reduced Motion (design:reduced-motion): the lens lands on `segment` and + * fades in there (handed to the animator as an entrance), while the surface + * on screen (the lens when it was carried, else `from`'s resting surface) + * fades out where it is on the same clock. Whether anything fades is the + * animator's call: on a fine pointer both change at once, unless a touch + * released the change (`touchRelease`). + */ + private crossFadeTo( + segment: HTMLElement, + box: Box, + from: Box | null, + paint: HTMLElement, + touchRelease: boolean, + ): void { + const track = this.track; + if (track == null) { + return; + } + // What is on screen before the lens is rebound. + let leaving: Box | null = null; + let opacity = 1; + const previous = this.carried; + if (previous != null) { + const now = this.now(); + const presented = this.presented(previous.box, now); + leaving = { + x: presented.center - presented.width / 2, + y: previous.box.y, + width: presented.width, + height: previous.box.height, + }; + opacity = this.animator.get('opacity', now); + } else if (from != null) { + leaving = from; + } + this.isHeld = false; + this.endLeaving(); + this.after.stop(); + clearLayer(track, 'after'); + this.isLeavingShown = false; + const fades = + leaving != null && + opacity > 0 && + this.animator.reducedMotion({touchRelease}) === 'crossfade'; + if (fades) { + this.leave(track, previous != null, paint, leaving as Box, opacity, box); + } + const at = this.carry(segment, box, from, paint); + this.velocity = {}; + this.trackHandle( + this.animator.animate( + {x: 0, scaleX: 1, scaleY: 1}, + {spring: segmentedControl.selectionSpring}, + {at, crossfadeAs: 'entrance', touchRelease}, + ), + ); + if (fades) { + this.fadeLeaving(box, leaving as Box, at, touchRelease); + } + } + + /** + * Paints the ::after with the surface on screen (the lens's paint, or + * `paint`'s resting surface) where it is (`from`, at `opacity`). + */ + private leave( + track: HTMLElement, + fromLens: boolean, + paint: HTMLElement, + from: Box, + opacity: number, + box: Box, + ): void { + if (fromLens) { + copyLensPaint(track); + } else { + paintLayer(track, 'after', paint); + } + placeLayer(track, 'after', {...from, y: box.y, height: box.height}); + this.isLeavingShown = true; + this.after.set({x: 0, scaleX: 1, scaleY: 1, opacity}); + } + + /** + * The ::after fades out where it is while the lens fades in on `box`: + * handed to the animator as a leaving travel, it fades on the same Reduce + * Motion clock and lands only once it is invisible. + */ + private fadeLeaving( + box: Box, + from: Box, + at: number | undefined, + touchRelease: boolean, + ): void { + const id = ++this.leaving; + const handle = this.after.animate( + {x: center(box) - center(from), opacity: 0}, + {spring: segmentedControl.selectionSpring}, + {at, touchRelease}, + ); + void handle.finished.then(() => { + if (this.leaving === id) { + this.endLeaving(); + } + }); + } + + private endLeaving(): void { + if (!this.isLeavingShown) { + return; + } + this.isLeavingShown = false; + this.leaving++; + this.after.stop(); + if (this.track != null) { + clearLayer(this.track, 'after'); + } + } + + /** + * Waits for `handle`; the surface goes back when nothing is left. A + * touch's value still waiting to come back when the motion settles goes + * back instead: the settled slide bounds the wait. + */ + private trackHandle(handle: MotionHandle): void { + this.running.add(handle); + void handle.finished.then(() => { + this.running.delete(handle); + if (this.running.size > 0 || this.isHeld || this.touch != null) { + return; + } + const committed = this.committed; + if (this.isAwaitingValue && committed != null && this.track != null) { + this.decline(this.track, committed); + return; + } + if (this.committed == null) { + this.settle(); + } + }); + } + + /** + * Gives `segment`'s title the selected face and the selected segment's + * title an unselected one (none for null or the selected segment), at once. + */ + private showFaceAt(segment: HTMLElement | null): void { + const touch = this.touch; + const selected = touch?.origin ?? null; + if (segment === this.facedSegment) { + return; + } + this.clearFaces(); + if ( + touch?.faces == null || + selected == null || + segment == null || + segment === selected + ) { + return; + } + const title = titleOf(segment); + const selectedTitle = titleOf(selected); + if (title == null || selectedTitle == null) { + return; + } + this.wearFace(title, touch.faces.selected); + this.wearFace(selectedTitle, touch.faces.unselected); + this.facedSegment = segment; + } + + /** + * Mid-drag the face is the colour alone: a weight swap would change the + * titles' widths, move the segments under the finger and the lens, and + * shake the boundary. The commit's own styles give the new weight at the + * lift. + */ + private wearFace(title: HTMLElement, face: TitleFace): void { + title.style.color = face.color; + this.faceOverrides.add(title); + } + + /** Every title back to its own face. */ + private clearFaces(): void { + for (const title of this.faceOverrides) { + title.style.removeProperty('color'); + } + this.faceOverrides.clear(); + this.facedSegment = null; + } +} + +/** + * Wires `SegmentedSelectionMotion` to a SegmentedControl: every change of + * `value` while `isEnabled` slides the selection, in the commit that shows the + * new value (no frame shows it unanimated), and a finger's touch drives the + * lens while `isTracking`. + */ +export function useSegmentedSelectionMotion( + trackRef: RefObject, + value: string, + isPresenting: boolean, + isTracking: boolean, +): SegmentedSelection { + const [motion] = useState(() => new SegmentedSelectionMotion()); + const previousValueRef = useRef(value); + // The lens is the radiogroup's own pseudo-elements: the animators attach to + // it while the touch presentation applies (every change slides) or while a + // press can drag it, which is every pointer's (`spec:AST-094` FR43). + const isEnabled = isPresenting || isTracking; + + useIsomorphicLayoutEffect(() => { + motion.present(isPresenting); + }, [isPresenting, motion]); + + useIsomorphicLayoutEffect(() => { + if (!isEnabled) { + return undefined; + } + motion.attachTrack(trackRef.current); + return () => motion.attachTrack(null); + }, [isEnabled, motion, trackRef]); + + useIsomorphicLayoutEffect(() => { + const from = previousValueRef.current; + previousValueRef.current = value; + const track = trackRef.current; + if (!isEnabled || track == null || from === value) { + return; + } + motion.select(track, from, value); + }, [isEnabled, motion, trackRef, value]); + + // The lens aims at boxes measured when its motion began: if the control + // resizes under it, hand the surface back rather than land somewhere stale. + useEffect(() => { + const track = trackRef.current; + if (!isEnabled || track == null) { + motion.settle(); + return; + } + return observeResize(track, () => motion.resized(track)); + }, [isEnabled, motion, trackRef]); + + useEffect(() => () => motion.stop(), [motion]); + + // Every pointer's press is tracked (`spec:AST-094` FR43): the lift + // commits the segment nearest the pointer, through that segment's click. + useSegmentedTouchTracking(trackRef, motion, isTracking); + + const [selection] = useState(() => ({ + isPressing: () => motion.isPressed, + })); + return selection; +} diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts new file mode 100644 index 0000000000000..1886eff56f04c --- /dev/null +++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts @@ -0,0 +1,101 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useSegmentedTouchTracking.test.ts + * @input useSegmentedTouchTracking.ts's segment resolution + * @output Proof of which segment a finger counts for, the rule the + * action-group tracker resolves the highlight and the commit with; and of + * which click the late-click guard swallows + * @position Testing for /packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts + */ + +import {describe, expect, it} from 'vitest'; +import { + isLateClick, + segmentTargetAt, + type SegmentSpan, +} from './useSegmentedTouchTracking'; + +function spans( + layout: ReadonlyArray<[string, number, number]>, + disabled: ReadonlyArray = [], +): SegmentSpan[] { + return layout.map(([value, left, right]) => { + const element = document.createElement('button'); + element.dataset.value = value; + if (disabled.includes(value)) { + element.setAttribute('aria-disabled', 'true'); + } + return {element, left, right}; + }); +} + +const valueAt = (x: number, segments: SegmentSpan[]) => + segmentTargetAt(x, segments)?.dataset.value ?? null; + +describe('segmentTargetAt', () => { + // Gaps of 4 px, and a narrow segment beside a wide one. + const layout: ReadonlyArray<[string, number, number]> = [ + ['grid', 12, 108], + ['list', 112, 152], + ['table', 156, 314], + ]; + + it('counts a finger over a segment for that segment, however near a narrower neighbour’s center', () => { + const segments = spans(layout); + // Inside Table, nearer List's center (132) than Table's own (235). + expect(valueAt(160, segments)).toBe('table'); + expect(valueAt(60, segments)).toBe('grid'); + }); + + it('splits a gap at its middle', () => { + const segments = spans(layout); + expect(valueAt(109, segments)).toBe('grid'); + expect(valueAt(111, segments)).toBe('list'); + expect(valueAt(153, segments)).toBe('list'); + expect(valueAt(155, segments)).toBe('table'); + }); + + it('counts a finger past either end for the end segment', () => { + const segments = spans(layout); + expect(valueAt(-40, segments)).toBe('grid'); + expect(valueAt(400, segments)).toBe('table'); + }); + + it('counts a finger over a disabled segment for nothing', () => { + const segments = spans(layout, ['list']); + expect(valueAt(130, segments)).toBeNull(); + expect(valueAt(111, segments)).toBeNull(); + expect(valueAt(109, segments)).toBe('grid'); + }); +}); + +describe('isLateClick', () => { + const segment = document.createElement('button'); + const label = document.createElement('span'); + segment.append(label); + + it('swallows the browser\u2019s own trusted click on the segment', () => { + expect( + isLateClick({isTrusted: true, detail: 1, target: label}, segment), + ).toBe(true); + }); + + it('lets a keyboard\u2019s or assistive technology\u2019s activation (detail 0) through (AST-094 FR21)', () => { + expect( + isLateClick({isTrusted: true, detail: 0, target: label}, segment), + ).toBe(false); + }); + + it('lets a script\u2019s click and a click elsewhere through', () => { + expect( + isLateClick({isTrusted: false, detail: 1, target: label}, segment), + ).toBe(false); + expect( + isLateClick( + {isTrusted: true, detail: 1, target: document.createElement('div')}, + segment, + ), + ).toBe(false); + }); +}); diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts new file mode 100644 index 0000000000000..f156155779c87 --- /dev/null +++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts @@ -0,0 +1,382 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useSegmentedTouchTracking.ts + * @input The radiogroup element, the selection motion controller and + * whether a press is tracked (every pointer's, `spec:AST-094` FR43) + * @output Exports `useSegmentedTouchTracking`: a press on a + * SegmentedControl (a finger, a mouse or a pen), from landing to letting + * go, reported to the selection + * motion (begin, drag, release, cancel); and + * `segmentTargetAt` / `measureSegments`, the segment a finger at x counts + * for. The segment the finger lets go on is committed through its own + * click, by the action-group tracker + * @position Internal to SegmentedControl's press tracking; the motion it + * drives is useSegmentedSelectionMotion.ts + * + * UISegmentedControl tracks a touch itself, the way a UIControl does: it + * reacts on touch-down, follows the finger and acts at the lift, where the + * segment nearest the finger wins, wherever the finger landed. Inside a + * scroll view the touch reaches it only after UIScrollView's content-touch + * delay, and a scroll that takes the touch cancels it. + * + * The gesture system's press tracker is that UIControl tracking: `touchDown` + * when the finger lands, `touchUpInside` / + * `touchUpOutside` at the lift, `touchCancel` when the browser takes the + * touch to scroll. It never claims the finger, so a vertical drag still + * scrolls the page. + * + * A horizontal pan carries the lens. It claims the finger only once the + * finger has travelled sideways past the pan's slop (the track gets + * `touch-action: pan-y` from it), and it does not cancel the press tracker: + * the lift still ends the press. + * + * Which segment the finger counts for, and the commit, are the action-group + * tracker's (hooks/actionGroupTracker.ts), the one tracker of a held finger + * across a group of targets: the segment under the finger, else the nearest + * (a gap splits at its middle; past the ends, the end one; nothing over a + * disabled segment), resolved from rects read once when the finger lands. The + * press itself paints as every pressable surface does under a finger: the + * segment keeps the shared press paint (SegmentedControlItem.tsx), so the + * tracker paints nothing of its own. A tap (the finger lifts on the segment it landed on, + * with no drag) is committed by the browser's own click (`spec:AST-094` + * FR11); the control waits for it and clicks the segment itself only if no + * click comes. A drag, or a lift on another segment, gets no click from the + * browser: the tracker clicks that segment at the lift and swallows any + * click the browser sends after. Either way an item's consumer `onClick` + * runs and can veto the selection with `preventDefault()`, exactly as under + * a mouse, and the click path never runs twice. A vetoed click sends the + * lens back at once; otherwise the motion waits for the value to come back + * (a controlled parent may adopt it later) and sends the lens back only if + * the slide settles without it. + * A mouse and a pen are tracked the same way (`spec:AST-094` FR43): a click + * is the browser's click, and a drag commits where it lifts. Keyboard and + * assistive technology keep the click. + * + * While a finger is down, text selection and the touch callout are off on + * the track: the drag recognizer brings the selection lock (`lockSelection`, + * `spec:AST-094` FR41), so a held finger drags the lens and never starts a + * selection; the gesture host brings the same lock for a mouse or a pen + * that drags (FR43). + * + * SYNC: When modified, update: + * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts + * - /packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts + */ + +import {useRef, type RefObject} from 'react'; +import { + PanGestureRecognizer, + useGestureRecognizer, + usePressTracker, +} from '../gestures'; +import { + createActionGroupTracker, + type ActionGroupTarget, + type ActionGroupTracker, +} from '../hooks/actionGroupTracker'; +import {lockSelection} from '../gestures/selectionLock'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + SEGMENT_SELECTOR, + type SegmentedSelectionMotion, +} from './useSegmentedSelectionMotion'; + +/** + * How long a tap's lift waits for the browser's own click before the segment + * is clicked directly, ms: the browser sends it with the lift's `touchend` + * (the track has no double-tap delay), so this only runs out for a lift the + * browser does not count as a click. + */ +const BROWSER_CLICK_WAIT_MS = 300; + +/** + * Waits for the browser's own click on `segment` after a tap and reports + * whether a handler cancelled it; with no click in time, clicks the segment + * itself (its activation and every handler run) and reports that. Either way + * the tap activates once: the browser's click stops the wait as it arrives, + * and one that comes after the segment was clicked (a busy main thread held + * it past the wait) is swallowed. + */ +function awaitBrowserClick( + segment: HTMLElement, + onClicked: (isCancelled: boolean) => void, +): void { + const view = segment.ownerDocument.defaultView; + if (view == null) { + return; + } + let isDone = false; + const finish = (isCancelled: boolean) => { + if (isDone) { + return; + } + isDone = true; + view.removeEventListener('click', grab, true); + view.clearTimeout(timer); + onClicked(isCancelled); + }; + const grab = (event: MouseEvent) => { + if (!event.isTrusted || !segment.contains(event.target as Node | null)) { + return; + } + // The browser's click is the activation: the segment is not clicked + // again, even by a wait that ran out while the main thread was busy. + view.clearTimeout(timer); + // After every handler has run: was it cancelled? + view.setTimeout(() => finish(event.defaultPrevented), 0); + }; + const timer = view.setTimeout(() => { + if (isDone) { + return; + } + view.removeEventListener('click', grab, true); + finish(clickAndReport(segment)); + swallowLateClick(segment); + }, BROWSER_CLICK_WAIT_MS); + view.addEventListener('click', grab, true); +} + +/** + * After a tap's segment was clicked directly, the browser's own click for that + * tap may still come (a busy main thread holds it past the wait): it is the + * same activation, so it is swallowed before any handler sees it. Only until + * the next press or key: any later click belongs to them. + */ +/** + * Whether `event` is the browser's own late click on `segment` for the + * activation the tracker already ran. A keyboard's or assistive + * technology's activation (`detail === 0`) is never one: it always passes + * (`spec:AST-094` FR21), as the shared tracker's swallower lets it. + */ +export function isLateClick( + event: Pick, + segment: HTMLElement, +): boolean { + return ( + event.isTrusted && + event.detail !== 0 && + segment.contains(event.target as Node | null) + ); +} + +function swallowLateClick(segment: HTMLElement): void { + const view = segment.ownerDocument.defaultView; + if (view == null) { + return; + } + const stop = () => { + view.removeEventListener('click', swallow, true); + view.removeEventListener('pointerdown', stop, true); + view.removeEventListener('touchstart', stop, true); + view.removeEventListener('keydown', stop, true); + }; + const swallow = (event: MouseEvent) => { + if (!isLateClick(event, segment)) { + return; + } + event.preventDefault(); + event.stopImmediatePropagation(); + stop(); + }; + view.addEventListener('click', swallow, true); + view.addEventListener('pointerdown', stop, {capture: true, passive: true}); + view.addEventListener('touchstart', stop, {capture: true, passive: true}); + view.addEventListener('keydown', stop, true); +} + +/** + * Clicks `segment` (its activation and every handler run) and reports + * whether a handler cancelled the click. + */ +function clickAndReport(segment: HTMLElement): boolean { + const view = segment.ownerDocument.defaultView; + let clicked: Event | null = null; + const grab = (event: Event) => { + if (clicked == null && event.target === segment) { + clicked = event; + } + }; + view?.addEventListener('click', grab, true); + try { + segment.click(); + } finally { + view?.removeEventListener('click', grab, true); + } + return (clicked as Event | null)?.defaultPrevented === true; +} + +/** A ref to nothing: hooks given it attach nothing. */ +const DETACHED: RefObject = {current: null}; + +/** A segment as measured when the finger landed: its viewport span, px. */ +export interface SegmentSpan { + readonly element: HTMLElement; + readonly left: number; + readonly right: number; +} + +/** Every segment of `track`, disabled ones included, measured once. */ +export function measureSegments(track: HTMLElement): SegmentSpan[] { + return Array.from( + track.querySelectorAll(SEGMENT_SELECTOR), + element => { + const rect = element.getBoundingClientRect(); + return {element, left: rect.left, right: rect.right}; + }, + ); +} + +function isDisabled(element: HTMLElement): boolean { + return ( + element.hasAttribute('disabled') || + element.getAttribute('aria-disabled') === 'true' + ); +} + +/** + * The segment a finger at viewport `x` counts for: the one under it, else + * the nearest (a gap between two segments splits at its middle, as UIKit's + * segments share an edge; past the ends, the end segment), or null when + * that one is disabled. + */ +export function segmentTargetAt( + x: number, + segments: ReadonlyArray, +): HTMLElement | null { + let best: SegmentSpan | null = null; + let distance = Infinity; + for (const segment of segments) { + const d = Math.max(segment.left - x, 0, x - segment.right); + if (d < distance) { + distance = d; + best = segment; + } + } + return best != null && !isDisabled(best.element) ? best.element : null; +} + +export function useSegmentedTouchTracking( + trackRef: RefObject, + motion: SegmentedSelectionMotion, + isEnabled: boolean, +): void { + const isEnabledRef = useRef(isEnabled); + useIsomorphicLayoutEffect(() => { + isEnabledRef.current = isEnabled; + }); + /** The horizontal pan began for this touch: it is a drag, not a tap. */ + const isDraggingRef = useRef(false); + /** The segments as the finger found them (disabled ones too). */ + const segmentsRef = useRef([]); + const trackerRef = useRef(null); + const tracker = (trackerRef.current ??= createActionGroupTracker(() => ({ + roots: () => [trackRef.current], + itemSelector: SEGMENT_SELECTOR, + highlightExpansion: 0, + // The segments keep the shared press paint, which the press controller + // writes for the touched segment, as everywhere else under a finger: the + // tracker paints nothing of its own (a held lens shows the selected face). + paintsHighlight: false, + resolveTarget: ( + x: number, + _y: number, + _targets: ReadonlyArray, + ) => segmentTargetAt(x, segmentsRef.current), + onActivated: (item, cancelled) => { + const track = trackRef.current; + const value = item.dataset.value; + if (track != null && value != null) { + motion.clicked(track, value, cancelled); + } + }, + swallowsNativeClick: true, + }))); + useIsomorphicLayoutEffect(() => () => tracker.dispose(), [tracker]); + + // Every pointer's press is tracked while the control is enabled + // (`spec:AST-094` FR43); a disabled control attaches nothing. + const attachRef = isEnabled ? trackRef : DETACHED; + usePressTracker(attachRef, { + isEnabled: () => isEnabledRef.current, + onControlEvent: (event, touch) => { + const track = trackRef.current; + if (track == null) { + return; + } + switch (event) { + case 'touchDown': + isDraggingRef.current = false; + segmentsRef.current = measureSegments(track); + tracker.begin(touch.x, touch.y); + motion.begin(track, tracker.beganOn); + break; + case 'touchUpInside': + case 'touchUpOutside': { + // Where the finger lifts decides, wherever it landed. + tracker.move(touch.x, touch.y); + const lifted = tracker.highlighted; + const isTap = + event === 'touchUpInside' && + !isDraggingRef.current && + lifted != null && + lifted === tracker.beganOn; + const value = motion.release(lifted); + if (value != null && isTap && lifted != null) { + // A tap: the browser's own click commits it (spec:AST-094 FR11). + tracker.cancel(); + awaitBrowserClick(lifted, isCancelled => + motion.clicked(track, value, isCancelled), + ); + } else if (value != null) { + // No click comes from the browser for a drag: the segment's own + // click, inside the lift's event; its onClick may veto it. + tracker.end(); + } else { + tracker.cancel(); + } + break; + } + case 'touchCancel': + tracker.cancel(); + motion.cancel(); + break; + case 'touchDragInside': + case 'touchDragOutside': + case 'touchDragEnter': + case 'touchDragExit': + // The horizontal pan carries the lens. + break; + } + }, + }); + useGestureRecognizer( + attachRef, + () => + new PanGestureRecognizer({ + name: 'segmented-control-drag', + direction: 'horizontal', + cancelsTouchesInView: false, + // No title is selectable under a held finger, as in UIKit: a hold on + // the track does something (a drag carries the lens and commits where + // it lifts), so this recognizer brings the lock, and the host turns + // text selection and the callout off on the track while a finger is + // down. + selectionLock: lockSelection, + }), + recognizer => { + if (recognizer.state === 'began') { + isDraggingRef.current = true; + } + if (recognizer.state === 'began' || recognizer.state === 'changed') { + const {x, y} = recognizer.location(); + // The lens chases the finger, then the tracker moves the highlight. + motion.drag(x); + tracker.move(x, y); + } + }, + {isEnabled}, + ); +} diff --git a/packages/core/src/SelectableCard/SelectableCard.test.tsx b/packages/core/src/SelectableCard/SelectableCard.test.tsx index 6279ef0c28002..648be63404329 100644 --- a/packages/core/src/SelectableCard/SelectableCard.test.tsx +++ b/packages/core/src/SelectableCard/SelectableCard.test.tsx @@ -14,9 +14,12 @@ import {SelectableCard} from './SelectableCard'; import { afterPaintsPress, hasReleaseFade, + keepsPressOutsideCoarse, pressArmsShadowedByDefault, readsPressStrength, + releasesOnLayer, } from '../__tests__/pressState'; +import {button as uikitButton} from '../motion/uikit/button'; describe('SelectableCard', () => { it('renders children', () => { @@ -205,6 +208,13 @@ describe('SelectableCard pressed state (touch)', () => { throw new Error('the card carries no pressable marker'); } expect(hasReleaseFade(card)).toBe(true); + // Under a coarse primary pointer the `::after`'s opacity releases the + // press on a control's clock (the compositor); under any other the + // card keeps the strength's release it always had (the desktop rule). + expect( + releasesOnLayer(card, '::after', uikitButton.highlight.releaseMs), + ).toBe(true); + expect(keepsPressOutsideCoarse(card, '::after')).toBe(true); expect(readsPressStrength(card, '[data-astryx-press="on"]')).toBe(true); expect(readsPressStrength(card)).toBe(true); expect(afterPaintsPress(card, '[data-astryx-press="on"]')).toBe(true); diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsx index 1d6dce18eec76..cc6187ce1252c 100644 --- a/packages/core/src/SelectableCard/SelectableCard.tsx +++ b/packages/core/src/SelectableCard/SelectableCard.tsx @@ -48,6 +48,7 @@ import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; +import {controlPressLayerStyles} from '../utils/controlPressLayer'; import {usePressFeedback} from '../hooks/usePressFeedback'; import {useMergedRefs} from '../hooks/useMergedRefs'; @@ -449,6 +450,10 @@ export function SelectableCard({ // The touch press's strength and release, on the element the // controller writes to; the `::after` above paints off it. !isDisabled && interactionOverlayStyles.pressedAlpha, + // Under a coarse primary pointer, the press's release runs on the + // `::after`'s opacity, on the compositor; any other pointer keeps + // the strength's release. + !isDisabled && controlPressLayerStyles.controlOver, isDisabled && styles.disabled, xstyleProp, ] as unknown as StyleXStyles diff --git a/packages/core/src/Thumbnail/Thumbnail.test.tsx b/packages/core/src/Thumbnail/Thumbnail.test.tsx index 5b9215b4388c5..71aaa7d578b27 100644 --- a/packages/core/src/Thumbnail/Thumbnail.test.tsx +++ b/packages/core/src/Thumbnail/Thumbnail.test.tsx @@ -7,9 +7,12 @@ import {Thumbnail} from './Thumbnail'; import { afterPaintsPress, hasReleaseFade, + keepsPressOutsideCoarse, pressArmsShadowedByDefault, readsPressStrength, + releasesOnLayer, } from '../__tests__/pressState'; +import {button as uikitButton} from '../motion/uikit/button'; describe('Thumbnail', () => { it('renders an image when src is provided', () => { @@ -368,6 +371,13 @@ describe('Thumbnail pressed state (touch)', () => { throw new Error('the interactive thumbnail carries no pressable marker'); } expect(hasReleaseFade(surface)).toBe(true); + // Under a coarse primary pointer the `::after`'s opacity releases the + // press on a control's clock (the compositor); under any other the + // card keeps the strength's release it always had (the desktop rule). + expect( + releasesOnLayer(surface, '::after', uikitButton.highlight.releaseMs), + ).toBe(true); + expect(keepsPressOutsideCoarse(surface, '::after')).toBe(true); expect(readsPressStrength(surface, '[data-astryx-press="on"]')).toBe(true); expect(readsPressStrength(surface)).toBe(true); expect(afterPaintsPress(surface, '[data-astryx-press="on"]')).toBe(true); diff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsx index 441db9c6cad13..9c4e8b83ce6ac 100644 --- a/packages/core/src/Thumbnail/Thumbnail.tsx +++ b/packages/core/src/Thumbnail/Thumbnail.tsx @@ -47,6 +47,7 @@ import {mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; +import {controlPressLayerStyles} from '../utils/controlPressLayer'; import {usePressFeedback} from '../hooks/usePressFeedback'; import {useTranslator} from '../i18n'; @@ -488,6 +489,10 @@ export function Thumbnail({ // The touch press's strength and release, on the element the // controller writes to; the `::after` above paints off it. isInteractive && interactionOverlayStyles.pressedAlpha, + // Under a coarse primary pointer, the press's release runs on the + // `::after`'s opacity, on the compositor; any other pointer keeps + // the strength's release. + isInteractive && controlPressLayerStyles.controlOver, ), isHoverReveal ? getContainerProps() : {}, )}> diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx index 97edf6064d6d6..16371c2bd6dbb 100644 --- a/packages/core/src/TreeList/TreeListItem.tsx +++ b/packages/core/src/TreeList/TreeListItem.tsx @@ -4,7 +4,8 @@ /** * @file TreeListItem.tsx - * @input Uses React, StyleX, theme tokens, TreeListBranches + * @input Uses React, StyleX, theme tokens, TreeListBranches, the shared press + * overlays and the compositor press layer * @output Exports TreeListItem component (internal, not publicly exported) * @position Internal implementation; consumed by TreeList.tsx * @@ -26,7 +27,10 @@ import { } from '../theme/tokens.stylex'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; +import {cellPressableProps} from '../utils/pressFeedback'; +import {rowPressLayerStyles} from '../utils/rowPressLayer'; import {usePressFeedback} from '../hooks/usePressFeedback'; +import {useInteractionModalityTracking} from '../utils/interactionModality'; import { hasInteractiveAncestor, useClickableContainer, @@ -405,7 +409,15 @@ export function TreeListItem({ setSize, isTabbable, }: TreeListItemInternalProps) { - const pressable = usePressFeedback(); + // A row's press is a cell's: it waits UIScrollView's content-touch delay + // only inside a scroll view (FR11), yields to the pan, and releases on the + // deselect clock. + usePressFeedback(); + // The cell profile (utils/pressFeedback.ts), internal to core. + const pressable = cellPressableProps; + // A selection hold returns focus to this row after a pop; its ring follows + // how the user last interacted (List/selectionHold.ts). + useInteractionModalityTracking(); const t = useTranslator(); const labelId = useId(); const descriptionId = useId(); @@ -679,6 +691,10 @@ export function TreeListItem({ densityStyles[density], styles.interactive, interactionOverlayStyles.backgroundImage, + // The touch press on a compositor layer (after the + // overlay, whose own touch paint it turns off). + rowPressLayerStyles.cell, + rowPressLayerStyles.cellOnImage, isDisabled && styles.disabled, isSelected && styles.selected, xstyle, diff --git a/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts b/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts index 34e60c41ea6d5..1ed850575168d 100644 --- a/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts +++ b/packages/core/src/__tests__/CardPress.a11y.chromium.spec.ts @@ -298,7 +298,7 @@ for (const surface of SURFACES) { } }); - test(`${surface.name}: a desktop mouse is unchanged: hover, \`:active\`, release, leave`, async ({ + test(`${surface.name}: a desktop mouse: hover, the press controller's press, its release, leave`, async ({ browser, }) => { const desktop = await open(browser, DESKTOP, surface); @@ -308,9 +308,13 @@ for (const surface of SURFACES) { const hover = await steadyPixel(desktop.page, desktop.sample); await desktop.page.mouse.down(); const pressed = await steadyPixel(desktop.page, desktop.sample); - // A fine pointer's press is `:active` alone: the controller writes nothing. - expect(await pressAttribute(desktop, surface)).toBeNull(); + // A fine pointer's press is the controller's, in place of `:active` + // (`spec:AST-094` FR11, DEC-21). + expect(await pressAttribute(desktop, surface)).toBe('on'); await desktop.page.mouse.up(); + await expect + .poll(async () => pressAttribute(desktop, surface)) + .toBeNull(); const released = await steadyPixel(desktop.page, desktop.sample); await desktop.page.mouse.move(1, 1); const left = await steadyPixel(desktop.page, desktop.sample); diff --git a/packages/core/src/__tests__/FinePointerPress.interaction.browser.spec.ts b/packages/core/src/__tests__/FinePointerPress.interaction.browser.spec.ts new file mode 100644 index 0000000000000..e695124668fdb --- /dev/null +++ b/packages/core/src/__tests__/FinePointerPress.interaction.browser.spec.ts @@ -0,0 +1,246 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file FinePointerPress.interaction.browser.spec.ts + * @input The built Button, List, SegmentedControl and RadioList stories, a + * real mouse (no touch) or a real finger, the interaction harness + * @output Interaction proofs for the fine-pointer press profile + * (`spec:AST-094` FR11, FR43, DEC-21): a mouse's press paints at + * `pointerdown` through the press controller, holds, and fades at the + * release, and its click runs once; a right click paints nothing; under + * reduced motion the release completes at once; a List row and an + * unselected SegmentedControl item paint at once, and the selected item + * paints nothing; and a press on a link inside a RadioList row paints + * nothing on the row, under a mouse or a finger + * @position Interaction evidence for utils/pressFeedback.ts's fine profile + * and its nested-control boundary + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + openStory, + tap, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +const PRESS = 'data-astryx-press'; + +interface Point { + readonly x: number; + readonly y: number; +} + +async function centerOf(locator: Locator): Promise { + const box = await locator.boundingBox(); + if (box == null) { + throw new Error('no box'); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; +} + +/** Records every value the element's press attribute takes from now on. */ +async function recordPress(locator: Locator): Promise { + await locator.evaluate(element => { + const values: (string | null)[] = []; + (element as unknown as {__press: (string | null)[]}).__press = values; + new MutationObserver(() => { + values.push(element.getAttribute('data-astryx-press')); + }).observe(element, { + attributes: true, + attributeFilter: ['data-astryx-press'], + }); + }); +} + +async function pressValues(locator: Locator): Promise<(string | null)[]> { + return locator.evaluate( + element => (element as unknown as {__press: (string | null)[]}).__press, + ); +} + +/** Counts the element's clicks from now on. */ +async function countClicks(locator: Locator): Promise<() => Promise> { + await locator.evaluate(element => { + (element as unknown as {__clicks: number}).__clicks = 0; + element.addEventListener('click', () => { + (element as unknown as {__clicks: number}).__clicks += 1; + }); + }); + return async () => + locator.evaluate( + element => (element as unknown as {__clicks: number}).__clicks, + ); +} + +/** + * The first RichContent row, with an unmarked native link added to its + * description: the story's own links are Astryx Links, pressable surfaces of + * their own, so a press on one never reached the row's surface anyway. + */ +async function rowWithNativeLink( + page: Page, +): Promise<{row: Locator; link: Locator; text: Locator}> { + await openStory(page, storybook(), 'core-radiolist--rich-content'); + const storyLink = page.getByRole('link', {name: 'Compare plans'}).first(); + await expect(storyLink).toBeVisible(); + const row = storyLink.locator('xpath=ancestor::*[@data-astryx-pressable][1]'); + await storyLink.evaluate(element => { + const native = document.createElement('a'); + native.href = '#terms'; + native.textContent = 'Terms'; + native.style.marginInlineStart = '8px'; + element.after(native); + }); + return { + row, + link: page.getByRole('link', {name: 'Terms'}), + text: row.getByText('Free forever.'), + }; +} + +async function mouseDownOn(page: Page, locator: Locator): Promise { + const center = await centerOf(locator); + await page.mouse.move(center.x, center.y); + await page.mouse.down(); +} + +test.describe('with a mouse', () => { + test.use({ + hasTouch: false, + isMobile: false, + viewport: {width: 1024, height: 768}, + }); + + test("a Button's press paints at pointerdown, holds, and fades at the release, and its click runs once", async ({ + page, + }) => { + await openStory(page, storybook(), 'core-button--primary'); + const button = page.getByRole('button', {name: 'Primary Button'}); + const clicks = await countClicks(button); + await mouseDownOn(page, button); + // A fine pointer has no scroll to wait out: painted at once. + await expect(button).toHaveAttribute(PRESS, 'on', {timeout: 100}); + await page.waitForTimeout(300); + await expect(button).toHaveAttribute(PRESS, 'on'); + await page.mouse.up(); + await expect(button).toHaveAttribute(PRESS, 'fading'); + await expect(button).not.toHaveAttribute(PRESS, /.+/); + expect(await clicks()).toBe(1); + }); + + test('a right click paints nothing', async ({page}) => { + await openStory(page, storybook(), 'core-button--primary'); + const button = page.getByRole('button', {name: 'Primary Button'}); + await recordPress(button); + const center = await centerOf(button); + await page.mouse.move(center.x, center.y); + await page.mouse.down({button: 'right'}); + await page.waitForTimeout(150); + await page.mouse.up({button: 'right'}); + await page.keyboard.press('Escape'); + expect(await pressValues(button)).toEqual([]); + }); + + test('a List row is pressed at once, and its release fades as under a finger', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-list--interactive'); + const row = page.locator('li[data-astryx-pressable]').first(); + await mouseDownOn(page, row); + await expect(row).toHaveAttribute(PRESS, 'on', {timeout: 100}); + await page.mouse.up(); + await expect(row).toHaveAttribute(PRESS, 'fading'); + await expect(row).not.toHaveAttribute(PRESS, /.+/); + }); + + test('an unselected SegmentedControl item paints the shared overlay at once, fades at the release, and the click selects it', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-segmentedcontrol--default'); + const group = page.getByRole('radiogroup', {name: 'View mode'}); + const list = group.locator('[data-value="list"]'); + await mouseDownOn(page, list); + await expect(list).toHaveAttribute(PRESS, 'on', {timeout: 100}); + const image = await list.evaluate( + element => getComputedStyle(element).backgroundImage, + ); + expect(image).toContain('gradient'); + await page.mouse.up(); + await expect(list).toHaveAttribute(PRESS, 'fading'); + await expect(list).not.toHaveAttribute(PRESS, /.+/); + await expect(list).toHaveAttribute('aria-checked', 'true'); + }); + + test('the selected SegmentedControl item paints nothing: it keeps its raised selected surface', async ({ + page, + }) => { + await openStory(page, storybook(), 'core-segmentedcontrol--default'); + const group = page.getByRole('radiogroup', {name: 'View mode'}); + const grid = group.locator('[data-value="grid"]'); + await expect(grid).toHaveAttribute('aria-checked', 'true'); + await recordPress(grid); + await mouseDownOn(page, grid); + await page.waitForTimeout(150); + await page.mouse.up(); + expect(await pressValues(grid)).toEqual([]); + }); + + test("a press on a native link inside a RadioList row paints nothing on the row, and on the row's own text it paints the row", async ({ + page, + }) => { + const {row, link, text} = await rowWithNativeLink(page); + await recordPress(row); + await mouseDownOn(page, link); + await page.waitForTimeout(150); + await page.mouse.up(); + expect(await pressValues(row)).toEqual([]); + const box = await text.boundingBox(); + if (box == null) { + throw new Error('no box'); + } + await page.mouse.move(box.x + 4, box.y + box.height / 2); + await page.mouse.down(); + await expect(row).toHaveAttribute(PRESS, 'on', {timeout: 100}); + await page.mouse.up(); + }); + + test.describe('under reduced motion', () => { + test("a mouse's release completes at once: no release animation runs", async ({ + page, + }) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), 'core-list--interactive'); + const row = page.locator('li[data-astryx-pressable]').first(); + await mouseDownOn(page, row); + await expect(row).toHaveAttribute(PRESS, 'on', {timeout: 100}); + await page.mouse.up(); + await expect(row).toHaveAttribute(PRESS, 'fading'); + expect( + await row.evaluate(element => getComputedStyle(element).animationName), + ).toBe('none'); + }); + }); +}); + +test.describe('with a finger', () => { + test.use({ + hasTouch: true, + isMobile: true, + viewport: {width: 390, height: 844}, + }); + + test('a press on a native link inside a RadioList row paints nothing on the row', async ({ + page, + }) => { + const {row, link} = await rowWithNativeLink(page); + await expect(link).toBeVisible(); + await recordPress(row); + const driver = await touchDriver(page); + await driver.play(tap(await centerOf(link), {holdMs: 400})); + await page.waitForTimeout(100); + expect(await pressValues(row)).toEqual([]); + }); +}); diff --git a/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts new file mode 100644 index 0000000000000..6defc72107e16 --- /dev/null +++ b/packages/core/src/__tests__/PressModality.a11y.chromium.spec.ts @@ -0,0 +1,399 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// @pr-a11y always + +/** + * @file PressModality.a11y.chromium.spec.ts + * @input The `Core/Button` Secondary story in a built Storybook, real mouse, + * keyboard and touch input in a phone context (primary pointer coarse) and + * a desktop context (primary pointer fine) + * @output Real-engine proof that on a touch-first device a held mouse press + * and a held Space press paint the pressed state with the same pixels and + * scale a desktop `:active` press paints, and fade at the release; that a + * desktop press is still `:active` alone; and that a finger's press on a + * control is highlighted as the finger lands + * @position Run with `pnpm test:a11y-contract`. Browser layer of the touch + * press model (utils/pressFeedback.ts); the jsdom layer is + * utils/pressFeedback.test.ts. + * + * The stylesheet drops every `:active` arm under `@media (pointer: coarse)`, + * which reads the PRIMARY pointer, so on such a device the press controller + * is the only thing that can paint a mouse or keyboard press. + */ + +import {expect, test, type Browser, type Page} from '@playwright/test'; +// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned. +import {PNG} from 'pngjs'; +import { + DEFAULT_STORYBOOK_DIR, + serveStorybook, + type StaticServer, +} from '@astryxdesign/a11y-spec/storybook'; + +let storybook: StaticServer; + +test.beforeAll(async () => { + storybook = await serveStorybook( + process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR, + ); +}); + +test.afterAll(async () => { + await storybook?.close(); +}); + +const STORY = 'core-button--secondary'; +const SURFACE = '#storybook-root [data-astryx-pressable]'; +/** A phone: touch screen, mobile viewport rules, primary pointer coarse. */ +const PHONE = { + viewport: {width: 402, height: 714}, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, +} as const; +/** A desktop: primary pointer fine, hover, no touch. */ +const DESKTOP = { + viewport: {width: 1024, height: 768}, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, +} as const; + +type RGB = [number, number, number]; + +interface Opened { + page: Page; + close: () => Promise; + center: {x: number; y: number}; + /** A point on the button's fill, clear of its label. */ + fill: {x: number; y: number}; +} + +async function open( + browser: Browser, + device: typeof PHONE | typeof DESKTOP, +): Promise { + const context = await browser.newContext(device); + const page = await context.newPage(); + await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`); + // Each case runs on the device it claims: a coarse primary pointer for the + // phone, a fine one for the desktop. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(device.hasTouch); + const box = await page.locator(SURFACE).first().boundingBox(); + if (box == null) { + throw new Error('the Button story rendered no pressable surface'); + } + await page.mouse.move(1, 1); + return { + page, + close: async () => context.close(), + center: {x: box.x + box.width / 2, y: box.y + box.height / 2}, + fill: {x: box.x + 6, y: box.y + box.height / 2}, + }; +} + +/** The mean colour of a 2 × 2 CSS px patch, as presented. */ +async function pixel(page: Page, at: {x: number; y: number}): Promise { + const png = PNG.sync.read( + await page.screenshot({ + clip: { + x: Math.round(at.x) - 1, + y: Math.round(at.y) - 1, + width: 2, + height: 2, + }, + animations: 'allow', + caret: 'hide', + }), + ); + const sum = [0, 0, 0]; + const count = png.width * png.height; + for (let i = 0; i < count; i++) { + sum[0] += png.data[i * 4]; + sum[1] += png.data[i * 4 + 1]; + sum[2] += png.data[i * 4 + 2]; + } + return sum.map(v => Math.round(v / count)) as RGB; +} + +/** Resolves once nothing on the surface animates and its transform is still. */ +async function settled(page: Page): Promise { + await page + .locator(SURFACE) + .first() + .evaluate( + async element => + new Promise(resolve => { + let last = ''; + let still = 0; + const tick = () => { + const transform = getComputedStyle(element).transform; + const running = element + .getAnimations() + .some(animation => animation.playState === 'running'); + still = !running && transform === last ? still + 1 : 0; + last = transform; + if (still >= 2) { + resolve(); + } else { + requestAnimationFrame(tick); + } + }; + requestAnimationFrame(tick); + }), + ); +} + +async function pressAttribute(page: Page): Promise { + return page.locator(SURFACE).first().getAttribute('data-astryx-press'); +} + +async function scale(page: Page): Promise { + return page + .locator(SURFACE) + .first() + .evaluate(element => { + const transform = getComputedStyle(element).transform; + return transform === 'none' ? 1 : new DOMMatrixReadOnly(transform).a; + }); +} + +async function coarse(page: Page): Promise { + return page.evaluate(() => matchMedia('(pointer: coarse)').matches); +} + +function expectSameColour(actual: RGB, expected: RGB): void { + for (let channel = 0; channel < 3; channel++) { + expect( + Math.abs(actual[channel] - expected[channel]), + `${JSON.stringify(actual)} vs ${JSON.stringify(expected)}`, + ).toBeLessThanOrEqual(2); + } +} + +type Press = 'mouse' | 'space'; + +async function holdPress(opened: Opened, press: Press): Promise { + if (press === 'mouse') { + await opened.page.mouse.move(opened.center.x, opened.center.y); + await opened.page.mouse.down(); + } else { + await opened.page.locator(SURFACE).first().focus(); + await opened.page.keyboard.down('Space'); + } +} + +async function releasePress(opened: Opened, press: Press): Promise { + if (press === 'mouse') { + await opened.page.mouse.up(); + } else { + await opened.page.keyboard.up('Space'); + } +} + +/** What a desktop paints for the press: the reference, and proof the controller stays out. */ +async function desktopReference( + browser: Browser, + press: Press, +): Promise<{rest: RGB; pressed: RGB; scale: number; attribute: string | null}> { + const desktop = await open(browser, DESKTOP); + try { + expect(await coarse(desktop.page)).toBe(false); + const rest = await pixel(desktop.page, desktop.fill); + await holdPress(desktop, press); + await settled(desktop.page); + return { + rest, + pressed: await pixel(desktop.page, desktop.fill), + scale: await scale(desktop.page), + attribute: await pressAttribute(desktop.page), + }; + } finally { + await desktop.close(); + } +} + +for (const press of ['mouse', 'space'] as const) { + test(`on a touch-first device a held ${press} press paints what a desktop press paints, then fades`, async ({ + browser, + }) => { + const reference = await desktopReference(browser, press); + expect(reference.pressed).not.toEqual(reference.rest); + + const phone = await open(browser, PHONE); + try { + expect(await coarse(phone.page)).toBe(true); + await phone.page.evaluate(() => { + const target = window as unknown as {__clicks: number}; + target.__clicks = 0; + document.addEventListener('click', () => { + target.__clicks += 1; + }); + }); + const rest = await pixel(phone.page, phone.fill); + expectSameColour(rest, reference.rest); + + await holdPress(phone, press); + await phone.page.waitForTimeout(250); + expect(await pressAttribute(phone.page)).toBe('on'); + await settled(phone.page); + expectSameColour(await pixel(phone.page, phone.fill), reference.pressed); + expect(await scale(phone.page)).toBeCloseTo(reference.scale, 3); + + await releasePress(phone, press); + expect(await pressAttribute(phone.page)).toBe('fading'); + expect( + await phone.page.evaluate( + () => (window as unknown as {__clicks: number}).__clicks, + ), + ).toBe(1); + await expect.poll(async () => pressAttribute(phone.page)).toBeNull(); + await settled(phone.page); + expectSameColour(await pixel(phone.page, phone.fill), rest); + } finally { + await phone.close(); + } + }); +} + +test("a desktop mouse press is the press controller's and paints what `:active` paints; a Space press stays `:active`'s", async ({ + browser, +}) => { + // `spec:AST-094` FR11, DEC-21: a fine pointer's press goes through the + // controller, in place of `:active`; a Space press keeps its path. + const mouse = await desktopReference(browser, 'mouse'); + expect(mouse.attribute).toBe('on'); + expect(mouse.pressed).not.toEqual(mouse.rest); + expect(mouse.scale).toBeCloseTo(0.98, 3); + const space = await desktopReference(browser, 'space'); + expect(space.attribute).toBeNull(); + expectSameColour(space.pressed, mouse.pressed); +}); + +test("a finger's press on a control highlights as the finger lands, then fades at the lift", async ({ + browser, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'touch input goes through CDP, which only Chromium has', + ); + const phone = await open(browser, PHONE); + try { + const cdp = await phone.page.context().newCDPSession(phone.page); + const touch = async (type: 'touchStart' | 'touchEnd') => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: + type === 'touchStart' + ? [{x: phone.center.x, y: phone.center.y, id: 1}] + : [], + }); + await touch('touchStart'); + // Outside a scroller a control highlights in the frame the finger lands + // (UIControl's touchDown); nothing waits for a scroll that cannot come. + await phone.page.evaluate( + async () => + new Promise(resolve => requestAnimationFrame(() => resolve(null))), + ); + const landed = await pressAttribute(phone.page); + await phone.page.waitForTimeout(250); + const held = await pressAttribute(phone.page); + await touch('touchEnd'); + const lifted = await pressAttribute(phone.page); + expect(landed).toBe('on'); + expect(held).toBe('on'); + expect(lifted).toBe('fading'); + } finally { + await phone.close(); + } +}); + +test('a mouse press dragged across menu rows lights only the row under the pointer', async ({ + browser, +}) => { + // useMenuPress FR6 and DEC-6: a menu's highlight is its only paint, so a + // row pressed and then left must not stay painted beside the highlight. + const context = await browser.newContext(PHONE); + const page = await context.newPage(); + try { + await page.goto( + `${storybook.origin}/iframe.html?id=core-dropdownmenu--mounted-open&viewMode=story`, + ); + // A mouse on a touch-first device: the primary pointer is coarse. + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); + const rows = page.getByRole('menuitem'); + await rows.first().waitFor(); + const menu = await page.locator('[data-astryx-menu-press]').boundingBox(); + const first = await rows.nth(0).boundingBox(); + const second = await rows.nth(1).boundingBox(); + if (menu == null || first == null || second == null) { + throw new Error('the menu story rendered no rows'); + } + // Sampled in a row's leading padding, clear of its label and its check + // mark; the menu's own surface above the first row is what an unlit row + // shows there. + const on = (box: { + x: number; + y: number; + width: number; + height: number; + }) => ({x: box.x + 4, y: box.y + box.height / 2}); + const unlit = await pixel(page, {x: first.x + 4, y: menu.y + 2}); + await page.mouse.move(on(first).x, on(first).y); + await page.mouse.down(); + await page.mouse.move(on(second).x, on(second).y, {steps: 6}); + await page.waitForTimeout(250); + const painted = await page + .locator('[data-astryx-menu-press] [data-astryx-press]') + .count(); + const left = await pixel(page, on(first)); + await page.mouse.up(); + expect(painted).toBe(0); + expectSameColour(left, unlit); + } finally { + await context.close(); + } +}); + +test('Space on a focused checkbox leaves its row at rest, as on a desktop', async ({ + browser, +}) => { + for (const device of [DESKTOP, PHONE]) { + const context = await browser.newContext(device); + const page = await context.newPage(); + try { + await page.goto( + `${storybook.origin}/iframe.html?id=core-press-feedback-touch--controls&viewMode=story`, + ); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(device.hasTouch); + const checkbox = page.getByRole('checkbox', {name: 'Accept terms'}); + await checkbox.waitFor({state: 'attached'}); + const box = await checkbox.evaluate(element => { + const visual = ( + element.parentElement ?? element + ).getBoundingClientRect(); + return { + x: visual.x + visual.width / 2, + y: visual.y + visual.height / 2, + }; + }); + await checkbox.focus(); + const rest = await pixel(page, box); + await page.keyboard.down(' '); + await page.waitForTimeout(150); + const held = await pixel(page, box); + const painted = await page.locator('[data-astryx-press]').count(); + await page.keyboard.up(' '); + expect(painted, device.isMobile ? 'phone' : 'desktop').toBe(0); + expectSameColour(held, rest); + } finally { + await context.close(); + } + } +}); diff --git a/packages/core/src/__tests__/internalModulesNotExperimental.test.ts b/packages/core/src/__tests__/internalModulesNotExperimental.test.ts new file mode 100644 index 0000000000000..85fe3a821d9f4 --- /dev/null +++ b/packages/core/src/__tests__/internalModulesNotExperimental.test.ts @@ -0,0 +1,88 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file internalModulesNotExperimental.test.ts + * @input vitest, the source of core's internal motion, gesture and keyboard + * modules, and of the package-private utility module (touchPresentation) + * @output Fails when one of them declares `@experimental`: those modules are + * internal and never exported (spec:AST-017 FR21, DEC-27), and the tag + * belongs only to a deliberately experimental public API + * @position Testing; a repository guard over src/motion, src/gestures, + * src/keyboard and src/utils/touchPresentation.ts. The rest of src/utils + * backs the public `@astryxdesign/core/utils` entry, where an experimental + * API may carry the tag + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import {describe, expect, it} from 'vitest'; + +const SRC = path.resolve(__dirname, '..'); +const INTERNAL_DIRS = ['motion', 'gestures', 'keyboard']; +/** Package-private files in a directory that also backs a public entry. */ +const INTERNAL_FILES = ['utils/touchPresentation.ts']; + +/** Every source file under `dir`, tests and declarations left out. */ +function sourcesUnder(dir: string): string[] { + const files: string[] = []; + for (const entry of fs.readdirSync(dir, {withFileTypes: true})) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (entry.name !== '__tests__') { + files.push(...sourcesUnder(full)); + } + } else if ( + /\.(ts|tsx|mjs|js)$/.test(entry.name) && + !/\.(test|spec)\.[cm]?[jt]sx?$/.test(entry.name) && + !entry.name.endsWith('.d.ts') + ) { + files.push(full); + } + } + return files; +} + +/** The internal files the guard reads, relative to src. */ +function checkedFiles(): string[] { + const files: string[] = []; + for (const dir of INTERNAL_DIRS) { + const root = path.join(SRC, dir); + if (fs.existsSync(root)) { + files.push(...sourcesUnder(root)); + } + } + files.push(...INTERNAL_FILES.map(file => path.join(SRC, file))); + return files.map(file => path.relative(SRC, file)); +} + +describe('internal modules', () => { + it('declare no @experimental: only an experimental public API carries it', () => { + const offenders: string[] = []; + for (const file of checkedFiles()) { + fs.readFileSync(path.join(SRC, file), 'utf8') + .split('\n') + .forEach((line, index) => { + if (/@experimental\b/.test(line)) { + offenders.push(`${file}:${index + 1}`); + } + }); + } + expect(offenders).toEqual([]); + }); + + it('checks the directories and files it names', () => { + expect(fs.existsSync(path.join(SRC, 'motion'))).toBe(true); + expect(fs.existsSync(path.join(SRC, 'gestures'))).toBe(true); + expect(sourcesUnder(path.join(SRC, 'motion')).length).toBeGreaterThan(5); + for (const file of INTERNAL_FILES) { + expect(fs.existsSync(path.join(SRC, file)), file).toBe(true); + } + }); + + it('leaves the public utils entry alone: of src/utils, only its package-private files are checked', () => { + const utils = checkedFiles().filter(file => + file.startsWith('utils' + path.sep), + ); + expect(utils).toEqual([path.join('utils', 'touchPresentation.ts')]); + }); +}); diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.ts index 352f450af397d..7f8ec17b9c6c1 100644 --- a/packages/core/src/__tests__/pressState.ts +++ b/packages/core/src/__tests__/pressState.ts @@ -6,7 +6,9 @@ * the press machine's release clock (utils/pressGesture.ts) * @output Exports rulesDeclaredFor, rulesWithSelector, hasPressedArm, * declaresPressedOverlay, readsPressStrength, afterPaintsPress, - * pressArmsShadowedByDefault and hasReleaseFade test helpers + * pressArmsShadowedByDefault, hasReleaseFade, showsLayerPress, + * layerOnlyWhilePressed, releasesOnLayer and keepsPressOutsideCoarse test + * helpers * @position Shared test helper for asserting a control paints a pressed state * * jsdom does not compute `:active` (there is no real pointer), so a component @@ -24,29 +26,76 @@ * SYNC: When modified, update this header. */ -import {PRESS_FADE_MS} from '../utils/pressGesture'; +import {button} from '../motion/uikit/button'; +import {list} from '../motion/uikit/list'; const PRESSED_TOKEN = '--color-overlay-pressed'; const PRESS_STRENGTH = '--astryx-press-alpha'; /** The press's paint at its strength, declared once by the shared styles. */ const PRESS_PAINT = '--_press-paint'; const FADING_ARM = '[data-astryx-press="fading"]'; +const ON_ARM = '[data-astryx-press="on"]'; +/** A selection hold's arm: the row it keeps selected through a push. */ +const HELD_ARM = '[data-astryx-press="held"]'; +/** The marker's value for a surface whose press is a cell's. */ +const CELL_ARM = '[data-astryx-pressable="cell"]'; +/** A mouse or Space press on a touch-first device: the fine pointer's clock. */ +const INPUT_ARM = '[data-astryx-press-input]'; +const isInputArm = (rule: string) => selectorOf(rule).includes(INPUT_ARM); -function walk(list: CSSRuleList, visit: (rule: CSSRule) => void): void { +const selectorOf = (rule: string) => rule.slice(0, rule.indexOf('{')); +const onPseudoElement = (rule: string) => selectorOf(rule).includes('::'); +const durationsOf = (rules: string[]) => + rules.flatMap(rule => { + const match = rule.match(/animation-duration:\s*([^;}]+)/); + return match == null ? [] : [durationToMs(match[1])]; + }); +const runsAnimation = (rule: string) => /animation-name:\s*(?!none)/.test(rule); +const stopsAnimation = (rule: string) => /animation-name:\s*none\b/.test(rule); + +function walk( + list: CSSRuleList, + visit: (rule: CSSRule, conditions: string) => void, + conditions = '', +): void { for (const rule of Array.from(list)) { - visit(rule); + visit(rule, conditions); const nested = (rule as CSSGroupingRule).cssRules; if (nested != null) { - walk(nested, visit); + const media = (rule as CSSMediaRule).media?.mediaText ?? ''; + walk(nested, visit, `${conditions} ${media}`); } } } +interface RuleFilter { + /** Skip rules inside an `@media` whose condition matches. */ + outsideMedia?: RegExp; + /** Keep only rules inside an `@media` whose condition matches. */ + insideMedia?: RegExp; +} + +/** A coarse primary pointer's `@media` condition. */ +const COARSE_MEDIA = /\(pointer: coarse\)/; +/** A Reduce Motion `@media` condition. */ +const REDUCED_MEDIA = /prefers-reduced-motion/; +/** + * Rules for a coarse primary pointer (inside its `@media`), or for any other + * (outside it), Reduce Motion's arms left out of both. + */ +const UNDER = { + coarse: {insideMedia: COARSE_MEDIA, outsideMedia: REDUCED_MEDIA}, + fine: {outsideMedia: /prefers-reduced-motion|\(pointer: coarse\)/}, +} as const satisfies Record; + /** * Every injected style rule (rules nested in `@media` included) whose selector * names one of the element's classes, as `selector {declarations}` text. */ -export function rulesDeclaredFor(el: Element): string[] { +export function rulesDeclaredFor( + el: Element, + filter: RuleFilter = {}, +): string[] { const classes = el.className .split(/\s+/) .filter(Boolean) @@ -59,10 +108,16 @@ export function rulesDeclaredFor(el: Element): string[] { } catch { continue; } - walk(rules, rule => { + walk(rules, (rule, conditions) => { if (!(rule instanceof CSSStyleRule)) { return; } + if (filter.outsideMedia?.test(conditions) === true) { + return; + } + if (filter.insideMedia != null && !filter.insideMedia.test(conditions)) { + return; + } const selector = rule.selectorText; if (classes.some(cls => selector.startsWith(cls))) { out.push(`${selector} {${rule.style.cssText}}`); @@ -73,8 +128,12 @@ export function rulesDeclaredFor(el: Element): string[] { } /** The rules on `el` whose selector matches `pseudo` (e.g. `:active`). */ -export function rulesWithSelector(el: Element, pseudo: string): string[] { - return rulesDeclaredFor(el).filter(rule => { +export function rulesWithSelector( + el: Element, + pseudo: string, + filter: RuleFilter = {}, +): string[] { + return rulesDeclaredFor(el, filter).filter(rule => { const selector = rule.slice(0, rule.indexOf('{')); return selector.includes(pseudo); }); @@ -133,11 +192,132 @@ export function afterPaintsPress(el: Element, arm = FADING_ARM): boolean { ); return ( rules.some(rule => - /background-image:\s*var\(--_press-paint-image\)/.test(rule), + /background-image:[^;}]*(--_press-paint-image|--color-overlay-pressed)/.test( + rule, + ), ) && rules.some(rule => /background-color:\s*transparent/.test(rule)) ); } +/** + * Does the element paint the press on its `::before` compositor layer: the + * pressed token, on a layer that exists only while a press does (see + * {@link layerOnlyWhilePressed}), shown at once (opacity 1, no animation) on + * the on arm? + */ +export function showsLayerPress(el: Element): boolean { + const layer = rulesDeclaredFor(el).filter(rule => + selectorOf(rule).includes('::before'), + ); + const on = layer.filter(rule => selectorOf(rule).includes(ON_ARM)); + return ( + layer.some(rule => + /background-color:[^;}]*--color-overlay-pressed/.test(rule), + ) && + layerOnlyWhilePressed(el, '::before') && + on.some(rule => /opacity:\s*1\b/.test(rule)) && + !on.some(runsAnimation) + ); +} + +/** + * Under a coarse primary pointer, does every declaration of the element's + * press layer on `pseudo`, and its `isolation`, apply only while a press is + * on, fading or held (a list row's selection hold)? At rest the element then + * has no layer and is no stacking context, and a caller's own `pseudo` keeps + * its styles. + */ +export function layerOnlyWhilePressed( + el: Element, + pseudo: '::before' | '::after', +): boolean { + const declarations = (rule: string) => rule.slice(rule.indexOf('{')); + const layer = rulesDeclaredFor(el, {insideMedia: COARSE_MEDIA}).filter( + rule => + selectorOf(rule).includes(pseudo) || + /(^|[{;\s])isolation:/.test(declarations(rule)), + ); + const onPressArm = (rule: string) => + [ON_ARM, FADING_ARM, HELD_ARM].some(arm => selectorOf(rule).includes(arm)); + return layer.length > 0 && layer.every(onPressArm); +} + +/** + * Does the element release the press on a compositor layer: an opacity + * keyframe animation on `pseudo`'s fading arm, for exactly `releaseMs` and + * filled both ways, with no release animation left on the element itself + * wherever the layer releases (the strength's own, a main-thread animation, + * is dropped)? A layer that exists only under a coarse primary pointer + * passes when the element's own release stops there too. + */ +export function releasesOnLayer( + el: Element, + pseudo: '::before' | '::after', + releaseMs: number, +): boolean { + const fading = rulesWithSelector(el, FADING_ARM, { + outsideMedia: REDUCED_MEDIA, + }); + const layer = fading.filter(rule => selectorOf(rule).includes(pseudo)); + const durations = durationsOf(layer.filter(rule => !isInputArm(rule))); + // A mouse or Space press on the same layer keeps the deselect clock. + const inputDurations = durationsOf(layer.filter(isInputArm)); + const layerReleases = + layer.some(runsAnimation) && + layer.some(rule => /animation-fill-mode:\s*both/.test(rule)) && + durations.length === 1 && + durations[0] === releaseMs && + inputDurations.every(ms => ms === list.highlight.releaseMs); + if (!layerReleases) { + return false; + } + const own = (rules: string[]) => rules.filter(rule => !onPseudoElement(rule)); + if (!own(fading).some(runsAnimation)) { + return true; + } + // The element keeps its own release for a fine pointer: the layer's + // release must run only under a coarse one, where the element's stops. + const animates = (rules: string[]) => + rules.filter(rule => rule.slice(rule.indexOf('{')).includes('animation-')); + const coarseLayer = rulesWithSelector(el, FADING_ARM, UNDER.coarse).filter( + rule => selectorOf(rule).includes(pseudo), + ); + return ( + animates(coarseLayer).length === animates(layer).length && + own(rulesWithSelector(el, FADING_ARM, UNDER.coarse)).some(stopsAnimation) + ); +} + +/** + * Does the element, under any pointer but a coarse primary one, keep the + * press it always had (the desktop rule): nothing animates `pseudo`, a + * `::before` (the press's own layer; a card's `::after` is the card's box) + * is not created at all, no `isolation`, and the strength's release runs on + * the element on the deselect clock? + */ +export function keepsPressOutsideCoarse( + el: Element, + pseudo: '::before' | '::after', +): boolean { + const fine = rulesDeclaredFor(el, UNDER.fine); + const layer = fine.filter(rule => selectorOf(rule).includes(pseudo)); + const fading = rulesWithSelector(el, FADING_ARM, UNDER.fine).filter( + rule => !onPseudoElement(rule), + ); + const clock = durationsOf(fading); + return ( + (pseudo === '::after' || + !layer.some(rule => + /(^|[{;\s])content:/.test(rule.slice(rule.indexOf('{'))), + )) && + !layer.some(rule => /animation-(name|duration):/.test(rule)) && + !fine.some(rule => /isolation:\s*isolate/.test(rule)) && + fading.some(runsAnimation) && + clock.length === 1 && + clock[0] === list.highlight.releaseMs + ); +} + /** * The custom properties the element sets on a `data-astryx-press` arm that it * also declares without that attribute (unconditionally, or on a pseudo-class @@ -179,7 +359,23 @@ export function declaresPressPaint(el: Element): boolean { /** `.2s`, `200ms`, `0.2s` → 200. */ export function durationToMs(value: string): number { - const match = value.trim().match(/^([\d.]+)(ms|s)$/); + const text = value.trim(); + // StyleX folds a constant cap into `calc(