diff --git a/.changeset/build-stylex-cross-file-consts.md b/.changeset/build-stylex-cross-file-consts.md new file mode 100644 index 0000000000000..736b20da4327d --- /dev/null +++ b/.changeset/build-stylex-cross-file-consts.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/build': patch +--- + +[fix] `astryxStylex` resolves `defineConsts` values read from another file. With the `{stylexOptions}` form (the one Storybook uses), a file that read only constants from a `.stylex.ts` module lost that import once StyleX compiled it, so the constants never reached the CSS: a constant used as a media-query key failed the build ("Invalid empty selector") and one used as a value shipped as a custom property nothing declares. In either form, a constant defined on the other side of the layer split, or in an Astryx package (compiled with the library class-name prefix) and read from an app file (compiled with its own), stayed unresolved. + +@vjeux diff --git a/.changeset/click-guard.md b/.changeset/click-guard.md new file mode 100644 index 0000000000000..7376b26fef796 --- /dev/null +++ b/.changeset/click-guard.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the gesture recognizers and the menu press model share one guard for the browser's click after a gesture that already acted, swallowing it for 400ms or until the next press. Keyboard and assistive-technology clicks (`detail` 0) always pass. + +@vjeux diff --git a/.changeset/gesture-arena-moving-cancel.md b/.changeset/gesture-arena-moving-cancel.md new file mode 100644 index 0000000000000..5b7e52cad131a --- /dev/null +++ b/.changeset/gesture-arena-moving-cancel.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: a gesture that cancels itself on a finger's move (a long press dragged past its tolerance) keeps that finger claimed until it lifts, so the page never takes the drag over midway; a resting finger is still given back when its gesture is cancelled. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-browser-negotiation.md b/.changeset/gesture-browser-negotiation.md new file mode 100644 index 0000000000000..1930e34496d7e --- /dev/null +++ b/.changeset/gesture-browser-negotiation.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: touch-action derivation, the native scroll probe and haptics for the gesture system. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-hook-fixes.md b/.changeset/gesture-hook-fixes.md new file mode 100644 index 0000000000000..87f08a0948e31 --- /dev/null +++ b/.changeset/gesture-hook-fixes.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the gesture hooks call nothing back after unmount; `usePressTracker` brakes with the host by default and keeps one tracker, so an option change or a new ref never drops a press in progress; the recognizer's arena plumbing is `protected`. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-host-fixes.md b/.changeset/gesture-host-fixes.md new file mode 100644 index 0000000000000..2fc0915c974a6 --- /dev/null +++ b/.changeset/gesture-host-fixes.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: gesture host fixes from review. A page scroll under a still finger keeps the press and its click; watchers and touches nothing can claim get passive listeners only; a claimed pen holds only its own stylus touches; an element's own `touch-action` is never widened; slotted content scrolls with its shadow-tree scroller. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-host-owner.md b/.changeset/gesture-host-owner.md new file mode 100644 index 0000000000000..9ff3bb2d7aded --- /dev/null +++ b/.changeset/gesture-host-owner.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the gesture host becomes the one document-level touch owner: the finger count, touch gates, and a kept press for continuous-tracking controls, whose element gets `touch-action: manipulation` where the pointer is coarse. A scroll lock's page hold and the finger-scroll watch keep their own listeners and ask the host only about the touches it owns. A second finger fails a one-finger pan that has not claimed, so the page can pinch. A scroll-edge pan holds a lone finger from the first move that pulls away from an edge every scroller under it is at, so those moves are cancelled before it begins; with a second finger anywhere on the screen the page keeps its pinch. Where the primary pointer is fine, the host attaches nothing and registers no listener, following the pointer when it changes; a recognizer that reads each event's pointer itself opts out with `perEventPointer`, and a press tracker with it paints a finger's press feedback only, with no control event and no mouse or pen press. A press tracker whose hold acts (a stepper's hold-repeat) can bring a selection lock for its presses, as a recognizer can. Internal, for the touch components that adopt them; not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-host.md b/.changeset/gesture-host.md new file mode 100644 index 0000000000000..eb9f2fec42db2 --- /dev/null +++ b/.changeset/gesture-host.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the gesture system's DOM host (claims, click suppression, the browser's takeover, the pointer behind a contact). Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-pan.md b/.changeset/gesture-pan.md index 12eb02fc42391..908da1b367575 100644 --- a/.changeset/gesture-pan.md +++ b/.changeset/gesture-pan.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: the pan gesture recognizer, with UIKit's measured hysteresis and velocity filter. Not exported from the package entry point; no component uses it yet. +[chore] Internal: the pan gesture recognizer, with UIKit's measured hysteresis and velocity filter. Not exported from the package entry point. @vjeux diff --git a/.changeset/gesture-press-tracking.md b/.changeset/gesture-press-tracking.md new file mode 100644 index 0000000000000..1c66836c74243 --- /dev/null +++ b/.changeset/gesture-press-tracking.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: UIControl press tracking with control and cell profiles and the gesture hooks, with every press painter writing `data-astryx-press` through one internal writer in `utils/pressFeedback.ts`. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-readme.md b/.changeset/gesture-readme.md new file mode 100644 index 0000000000000..9a6293b811b68 --- /dev/null +++ b/.changeset/gesture-readme.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the gesture system's README for component authors, with its browser proof in Chromium and WebKit. + +@vjeux diff --git a/.changeset/gesture-recognizer-core.md b/.changeset/gesture-recognizer-core.md index 0b0bfc389235f..28caef0d5579c 100644 --- a/.changeset/gesture-recognizer-core.md +++ b/.changeset/gesture-recognizer-core.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: the gesture recognizer core for touch presentations: UIKit's recognizer state machine and the arena that settles which recognizer owns a touch. Not exported from the package entry point; no component uses it yet. +[chore] Internal: the gesture recognizer core for touch presentations: UIKit's recognizer state machine and the arena that settles which recognizer owns a touch. Not exported from the package entry point. @vjeux diff --git a/.changeset/gesture-recognizer-fixes.md b/.changeset/gesture-recognizer-fixes.md new file mode 100644 index 0000000000000..9e6754a78d733 --- /dev/null +++ b/.changeset/gesture-recognizer-fixes.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: gesture recognizer and arena fixes from review; a pan claims nothing before it begins at 10 pt; one velocity tracker for every gesture (`spec:AST-100`: UIKit's measured blend, a scrolling surface's release through the pan's `scrollVelocity()`, and FR2's release rules). Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-swipe-pinch-rotation-edge-hover.md b/.changeset/gesture-swipe-pinch-rotation-edge-hover.md new file mode 100644 index 0000000000000..ffeadde679ef5 --- /dev/null +++ b/.changeset/gesture-swipe-pinch-rotation-edge-hover.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: swipe, pinch, rotation, screen-edge pan and hover gesture recognizers. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gesture-tap-long-press.md b/.changeset/gesture-tap-long-press.md index 9ef786da65842..f1efef8d29014 100644 --- a/.changeset/gesture-tap-long-press.md +++ b/.changeset/gesture-tap-long-press.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[chore] Internal: tap and long-press gesture recognizers with UIKit's measured thresholds. Not exported from the package entry point; no component uses them yet. +[chore] Internal: tap and long-press gesture recognizers with UIKit's measured thresholds. Not exported from the package entry point. @vjeux diff --git a/.changeset/gesture-watcher.md b/.changeset/gesture-watcher.md new file mode 100644 index 0000000000000..bec7cd286e49d --- /dev/null +++ b/.changeset/gesture-watcher.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: a recognizer created with `claimsTouches: false` is a watcher: passive listeners only, simultaneous with every recognizer, and it follows a touch the browser takes for a scroll to the lift. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/gestures-every-pointer.md b/.changeset/gestures-every-pointer.md new file mode 100644 index 0000000000000..87e2940ff80b7 --- /dev/null +++ b/.changeset/gestures-every-pointer.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: gestures attach for every pointer, a mouse, a pen and a finger alike (AST-094 FR43). Under a fine primary pointer an element that uses a gesture keeps one passive `pointerdown` listener (a recognizer that claims a moving finger also keeps its blocking `touchmove`), and the page's listeners last only a press. A right click or a ctrl-click on macOS starts no press. A mouse or pen drag that a recognizer claims takes no text selection from then on, anywhere on the page, and a finger is read once where the browser sends Touch Events without exposing `ontouchstart`. A press tracker takes a mouse press as a press, painting at once with no scroll brake. The screen-edge pan stays off under a mouse, a trackpad and a pen unless its caller allows one, and `perEventPointer` is accepted and does nothing. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/input-stream.md b/.changeset/input-stream.md new file mode 100644 index 0000000000000..61c8b2d52ed22 --- /dev/null +++ b/.changeset/input-stream.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] The touch press feedback and the gesture recognizers now listen on the window's capture phase through one shared input stream: one passive listener per event type for both. An app's own capture-phase `stopPropagation` at the document no longer starves them, and a page of pressables registers no listener that can hold a scroll. + +@vjeux diff --git a/.changeset/list-has-animated-changes.md b/.changeset/list-has-animated-changes.md new file mode 100644 index 0000000000000..1ca1bb48ed9e1 --- /dev/null +++ b/.changeset/list-has-animated-changes.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `List` gains `hasAnimatedChanges`. Under a finger (a coarse primary pointer, iOS and Android alike), when rows are inserted, removed or reordered, the rows that stay slide to their new places and new rows fade in once the rows sliding past have cleared them, on the spring an iOS table uses. A row that crosses rows moving the other way (a reorder) rides above them with the surface color behind it, as an iOS table's opaque cell does. A removed row collapses in place (a swiped one with its action showing) while the rows below slide up into its gap, as a deleted iOS table cell does. Page content after the list takes its new place by layout at once; nothing moves it. With reduced motion on, nothing travels: rows cross-fade into place. Off by default; with a mouse nothing moves. + +@vjeux diff --git a/.changeset/list-reorder-mode-hint.md b/.changeset/list-reorder-mode-hint.md new file mode 100644 index 0000000000000..a5dad52a05089 --- /dev/null +++ b/.changeset/list-reorder-mode-hint.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] While a reorderable `List` row is in reorder mode, a hint anchored to its handle, in the keyboard hint's layer and theme roles, shows the moves and Done. Each is a button that does what its key does and leaves the focus on the handle, so a row can be reordered by taps alone: the handle, the moves, then Done. + +@vjeux diff --git a/.changeset/list-reorderable.md b/.changeset/list-reorderable.md new file mode 100644 index 0000000000000..0f3ce5e5ece0c --- /dev/null +++ b/.changeset/list-reorderable.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `createReorderable({onReorder, isReorderable})` makes a collection's reorder behavior, and `List` takes it as `reorderable`: each `ListItem` with an `itemKey` gets a reorder handle at its end, and each committed move calls `onReorder({key, to})` once, with the row's key and its index after the move. On a touch screen a finger held still on a handle picks up its row the way an iOS table's reorder control does (a flick on it still scrolls): the row stays in its place, dimmed, while a copy of it follows the finger and an accent line marks where it would land; the other rows stay still, the page scrolls near the edges, and on release the rows rearrange, gliding to their new places. A mouse drags a handle at once with the same copy and line, and rows take their places without motion; a cancelled drag puts everything back at once. Without a drag, a click, Space or Enter on a handle turns on reorder mode for its row: each arrow key moves it a place at once, announced with its place and neighbours, and Escape or another activation ends the mode, keeping the moves. The object's `start(key)` enters the same mode from the app's own UI, such as a row's context menu. A List without `reorderable` loads none of the reorder code. + +@vjeux diff --git a/.changeset/list-row-press-compositor.md b/.changeset/list-row-press-compositor.md new file mode 100644 index 0000000000000..96014ef632b3e --- /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 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-touch-hit-area.md b/.changeset/list-touch-hit-area.md new file mode 100644 index 0000000000000..eee89371d2ed5 --- /dev/null +++ b/.changeset/list-touch-hit-area.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] Under a finger (a coarse primary pointer), an interactive `List` row's hit target grows toward 44px where its neighbors leave room: the shared touch hit area measures each row and stops at half the gap to the nearest neighboring row or control. Rows look and lay out exactly as before, and a mouse is unchanged. Under a finger a list row's `::after` is that invisible layer, so decorate a row with a child instead. + +@vjeux diff --git a/.changeset/long-press-one-source.md b/.changeset/long-press-one-source.md new file mode 100644 index 0000000000000..7ed429a480cb9 --- /dev/null +++ b/.changeset/long-press-one-source.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] `useLongPress` (ContextMenu's long press, and the held finger that opens a menu from its trigger) now cancels when the finger travels more than 10px from where it landed, measured as a distance, as UIKit's long press does. Before, it allowed 10px on each axis, so a diagonal drift of up to about 14px kept the press. Its duration and tolerance now come from the same source as the long-press gesture recognizer. + +@vjeux diff --git a/.changeset/presented-hit-testing.md b/.changeset/presented-hit-testing.md new file mode 100644 index 0000000000000..e27c857277aad --- /dev/null +++ b/.changeset/presented-hit-testing.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] On iOS, a touch on an element the compositor animator is moving reaches what is drawn: the animator reports each moving element's offset from its layout box, and the gesture host sends the touch, press bounds and the tap's click there instead of to the layout position iOS WebKit hit-tests. + +@vjeux diff --git a/.changeset/reduced-motion-record.md b/.changeset/reduced-motion-record.md new file mode 100644 index 0000000000000..2ec44f4c1f9c8 --- /dev/null +++ b/.changeset/reduced-motion-record.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Reduce Motion for the touch presentations follows design:reduced-motion beyond the animator too. `reducedMotionFade()` gives code beside the animator the animator's own fade (an opacity-only 200 ms cross-fade on a coarse pointer or after a touch release, at once on any other pointer), `animator.reducedMotion()` reports which form a change takes for feedback that plays no fade of its own, and `reducedMotion.stylex.ts` holds the fade's constants for StyleX transitions. The fade's length is not a theme motion role. Not exported from the package entry point. + +@vjeux diff --git a/.changeset/reorder-values.md b/.changeset/reorder-values.md new file mode 100644 index 0000000000000..6b953cbcdaa46 --- /dev/null +++ b/.changeset/reorder-values.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: a table's reorder values in the UIKit constants table (the reorder control's claim and the edge autoscroll steps, measured on iOS 26.2) and the reorder model that applies them (the drop position a drag proposes, the rows a drag can pass, the autoscroll step). Not exported from the package entry point; no component uses them yet. + +@vjeux diff --git a/.changeset/reorderable-attach.md b/.changeset/reorderable-attach.md new file mode 100644 index 0000000000000..593bc61a92603 --- /dev/null +++ b/.changeset/reorderable-attach.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `createReorderable` takes `positions()` for a layout such as a grid or a fanned hand: one slot centre per item, so a drag follows the pointer on both axes, drops the item on the slot nearest its centre, and settles it on that slot's centre, and reorder mode's arrow keys and hint follow the layout's rows and columns (Left and Right along a row, all four in a grid, a row and a column in the announcement). Its new `attach(container, {items})` reorders plain elements with no collection component: each item's handle becomes reorder mode's toggle, named after its item and in the Tab order (a rejected or keyless item's handle is hidden), the container gets the drag and reorder mode with their announcements through the shared announcement channel, following the primary pointer as it turns coarse or fine, and `detach()` removes everything it added. + +@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/tree-list-expand-motion.md b/.changeset/tree-list-expand-motion.md new file mode 100644 index 0000000000000..ac62d494f4e7f --- /dev/null +++ b/.changeset/tree-list-expand-motion.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[feat] Under a finger (a coarse primary pointer, iOS and Android alike), a `TreeList` row's children slide out from under it as it expands, with the rows below moving down alongside and the chevron turning, and slide back under it as it collapses, as in an iOS outline list. They used to appear and vanish in a single frame. The motion runs on the compositor and keeps going while the page runs script; with reduced motion on, it cross-fades instead of moving. Trees driven by a mouse are unchanged. + +@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..9927f1e4b89e2 100644 --- a/apps/storybook/stories/List.stories.tsx +++ b/apps/storybook/stories/List.stories.tsx @@ -7,10 +7,11 @@ * @position Storybook demonstrations for List consumers */ -import {useState} from 'react'; +import {useMemo, useState} from 'react'; import * as stylex from '@stylexjs/stylex'; import type {Meta, StoryObj} from '@storybook/react'; import {List, ListItem} from '@astryxdesign/core/List'; +import {createReorderable} from '@astryxdesign/core/reorderable'; import {Avatar} from '@astryxdesign/core/Avatar'; import {Badge} from '@astryxdesign/core/Badge'; import {Card} from '@astryxdesign/core/Card'; @@ -18,6 +19,8 @@ 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'; +import {ContextMenu} from '@astryxdesign/core/ContextMenu'; import { Cog6ToothIcon, BellIcon, @@ -408,3 +411,289 @@ export const HeaderInFlexParent: Story = { }, }, }; + +function AnimatedChangesDemo() { + const [rows, setRows] = useState([ + 'Inbox', + 'Sent', + 'Drafts', + 'Archive', + 'Spam', + ]); + const [next, setNext] = useState(1); + return ( + + + {rows.map(label => ( + {}} /> + ))} + + + + + + + + ); +} + +export const AttachedCardsInADialog: Story = { + render: () => , + parameters: { + docs: { + description: { + story: + 'The cards are attached while their modal dialog is closed; once ' + + 'it opens, a move is announced inside the dialog, where a screen ' + + 'reader still reads.', + }, + }, + }, +}; diff --git a/apps/storybook/stories/TreeList.stories.tsx b/apps/storybook/stories/TreeList.stories.tsx index 9d542ec7a5737..5ffbf2cee6dac 100644 --- a/apps/storybook/stories/TreeList.stories.tsx +++ b/apps/storybook/stories/TreeList.stories.tsx @@ -5,6 +5,8 @@ import {TreeList} from '@astryxdesign/core/TreeList'; import type {TreeListItemData} from '@astryxdesign/core/TreeList'; import {Icon} from '@astryxdesign/core/Icon'; import {Badge} from '@astryxdesign/core/Badge'; +import {Button} from '@astryxdesign/core/Button'; +import {VStack} from '@astryxdesign/core/Layout'; import {Theme, defineTheme} from '@astryxdesign/core/theme'; import { FolderIcon, @@ -73,6 +75,25 @@ export const Basic: Story = { }, }; +export const WithContentBelow: Story = { + render: () => ( + + +
`; + 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, @@ -961,6 +2082,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 +2231,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 +2304,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 +2409,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 +2713,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 +2926,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/scripts.test.ts b/internal/interaction-harness/src/scripts.test.ts index 321b76d1a49c5..f44e9fbf430c6 100644 --- a/internal/interaction-harness/src/scripts.test.ts +++ b/internal/interaction-harness/src/scripts.test.ts @@ -49,6 +49,22 @@ describe('touch scripts', () => { expect(releaseVelocity(script)).toEqual({x: 0, y: 0}); }); + it('a cancelled drag ends in a touchCancel, not a touchEnd', () => { + const events = toTouchEvents( + drag( + {x: 0, y: 0}, + {x: 0, y: 100}, + {durationMs: 100, hz: 60, holdMs: 500, cancel: true}, + ), + ); + expect(events.filter(e => e.type === 'touchEnd')).toHaveLength(0); + expect(events.at(-1)).toMatchObject({ + type: 'touchCancel', + fingers: [], + changed: [{id: 0, x: 0, y: 100}], + }); + }); + it('flick releases at exactly the scripted velocity', () => { const script = flick( {x: 10, y: 10}, diff --git a/internal/interaction-harness/src/scripts.ts b/internal/interaction-harness/src/scripts.ts index 91d52f9cacf7b..165bde3ec26fb 100644 --- a/internal/interaction-harness/src/scripts.ts +++ b/internal/interaction-harness/src/scripts.ts @@ -34,6 +34,11 @@ export interface TouchFrame { readonly t: number; /** Every finger that is down at `t`. Empty = all lifted. */ readonly fingers: readonly Finger[]; + /** + * The fingers this frame takes away are cancelled (a `touchCancel`, as + * when the browser takes the touch over), not lifted (a `touchEnd`). + */ + readonly cancel?: boolean; } export type TouchScript = readonly TouchFrame[]; @@ -86,6 +91,8 @@ export interface DragOptions { /** Progress easing over the move, default linear (constant velocity). */ readonly easing?: (progress: number) => number; readonly id?: number; + /** Ends in a `touchCancel` instead of a lift. */ + readonly cancel?: boolean; } /** Press at `from`, move to `to`, lift. Constant velocity unless `easing` says otherwise. */ @@ -101,6 +108,7 @@ export function drag( restMs = 0, easing = (p: number) => p, id = 0, + cancel = false, } = options; const frames: TouchFrame[] = [{t: 0, fingers: [{id, ...from}]}]; for (const t of frameTimes(durationMs, hz)) { @@ -111,7 +119,11 @@ export function drag( } // A real finger reports no move while it rests: the lift simply comes later. const last = frames[frames.length - 1].t; - frames.push({t: last + Math.max(restMs, 1000 / hz / 4), fingers: []}); + frames.push({ + t: last + Math.max(restMs, 1000 / hz / 4), + fingers: [], + ...(cancel ? {cancel} : null), + }); return frames; } @@ -305,7 +317,8 @@ export function merge(...scripts: TouchScript[]): TouchScript { /** * Turns frames into events: a finger that appears is a `touchStart`, one that - * disappears a `touchEnd`, one that moved a `touchMove`. A frame that both + * disappears a `touchEnd` (a `touchCancel` in a frame that cancels), one that + * moved a `touchMove`. A frame that both * moves some fingers and lifts others yields the move first, then the lift. * Unchanged frames yield nothing (a resting finger reports nothing). */ @@ -334,7 +347,7 @@ export function toTouchEvents(script: TouchScript): TouchEventStep[] { const remaining = [...down.values()].filter(f => next.has(f.id)); events.push({ t: frame.t, - type: 'touchEnd', + type: frame.cancel === true ? 'touchCancel' : 'touchEnd', fingers: remaining, changed: released.map(f => down.get(f.id) ?? f), }); 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..62603e78efc9f 100644 --- a/internal/interaction-harness/src/touch.ts +++ b/internal/interaction-harness/src/touch.ts @@ -159,15 +159,18 @@ async function chromiumDriver(page: Page): Promise { // A start or move lists every finger down (CDP presses the new ones). // An end lists the fingers that lift: that releases exactly those // while the rest stay down and keep moving; the last lift lists none. - // (A move that omits a finger does not release it.) + // (A move that omits a finger does not release it.) A cancel takes + // every finger and lists none. await cdp.send('Input.dispatchTouchEvent', { type: step.type, touchPoints: - step.type !== 'touchEnd' - ? touchPoints(step.fingers) - : step.fingers.length > 0 - ? touchPoints(step.changed) - : [], + step.type === 'touchCancel' + ? [] + : step.type !== 'touchEnd' + ? touchPoints(step.fingers) + : step.fingers.length > 0 + ? touchPoints(step.changed) + : [], timestamp: timestamp / 1000, }); }, @@ -265,6 +268,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 +286,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/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index 97b4458b92bda..0a06363f1bcd6 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -3744,6 +3744,11 @@ "path": "examples/visually-hidden/supplementary-context", "aliases": [] }, + { + "name": "hook-create-reorderable", + "path": "hooks/create-reorderable", + "aliases": [] + }, { "name": "hook-use-announce", "path": "hooks/use-announce", 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/foundation/discovery/hook-discovery.mjs b/packages/cli/foundation/discovery/hook-discovery.mjs index 93d8e29a2621f..a838276a8c951 100644 --- a/packages/cli/foundation/discovery/hook-discovery.mjs +++ b/packages/cli/foundation/discovery/hook-discovery.mjs @@ -12,6 +12,10 @@ import {levenshteinDistance} from '../text/string-utils.mjs'; const SKIP_DIRS = new Set(['utils', '__tests__', 'node_modules']); +// A hook's doc outside src/hooks/: a `use…` hook, or a `create…` factory +// documented as one (its doc typed `HookDoc`, such as createReorderable). +const HOOK_DOC_FILE_RE = /^(?:use|create)[A-Z]\w*\.doc\.mjs$/; + // Matches the top-level `category: 'categoryName'` field in a hook .doc.mjs file. const CATEGORY_RE = /(?:^|\n) {0,4}category:\s*['"]([^'"]+)['"]/; @@ -70,7 +74,8 @@ export function discoverHooks(coreDir) { } } - // 2. Scan ALL component directories for files matching use*.doc.mjs + // 2. Scan ALL component directories for hook docs: use*.doc.mjs, and + // create*.doc.mjs for a factory documented as a hook (createReorderable) if (pathExists(srcDir)) { const topEntries = listDirEntries(srcDir); for (const entry of topEntries) { @@ -120,11 +125,7 @@ function scanDirForHookDocs(dirPath, hookCategories) { for (const entry of entries) { if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) { scanDirForHookDocs(path.join(dirPath, entry.name), hookCategories); - } else if ( - entry.isFile() && - entry.name.startsWith('use') && - entry.name.endsWith('.doc.mjs') - ) { + } else if (entry.isFile() && HOOK_DOC_FILE_RE.test(entry.name)) { const hookName = hookNameFromFile(entry.name); if (!hookCategories.has(hookName)) { const docPath = path.join(dirPath, entry.name); diff --git a/packages/cli/foundation/discovery/hook-discovery.test.mjs b/packages/cli/foundation/discovery/hook-discovery.test.mjs index 711224ae1c17f..f383688a974a1 100644 --- a/packages/cli/foundation/discovery/hook-discovery.test.mjs +++ b/packages/cli/foundation/discovery/hook-discovery.test.mjs @@ -88,6 +88,26 @@ describe('discoverHooks (real core)', () => { expect(discoverHooks(core)).toEqual({Interaction: ['useResizable']}); }); + it('discovers a create*.doc.mjs factory documented as a hook, but no other file', () => { + const core = mkTmp('as-hd-factory-'); + const dir = path.join(core, 'src', 'reorderable'); + fs.mkdirSync(dir, {recursive: true}); + fs.writeFileSync( + path.join(dir, 'createReorderable.doc.mjs'), + "export default {\n category: 'interaction',\n};\n", + ); + // Neither a component doc nor a lowercase `create` prefix is a hook. + fs.writeFileSync(path.join(dir, 'Creator.doc.mjs'), 'export default {};\n'); + fs.writeFileSync( + path.join(dir, 'createdHelpers.doc.mjs'), + 'export default {};\n', + ); + expect(discoverHooks(core)).toEqual({Interaction: ['createReorderable']}); + expect(findHookDoc(core, 'createReorderable')).toBe( + path.join(dir, 'createReorderable.doc.mjs'), + ); + }); + it('returns {} when src/ is missing (guarded with existsSync)', () => { const core = mkTmp('as-hd-nosrc-'); expect(discoverHooks(core)).toEqual({}); diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json index a3aa68558d1d7..3023394f827ae 100644 --- a/packages/core/locales/en.json +++ b/packages/core/locales/en.json @@ -463,6 +463,86 @@ "defaultMessage": "{count, number} {count, plural, one {other} other {others}}", "description": "Overflow element for the chat typing status when three or more people type: the first name is shown and the rest collapse into this phrase, which is then joined to the name by Intl.ListFormat. Renders as the last list item, e.g. \"Ana and 2 others\"." }, + "@astryx.list.reorderHandle": { + "defaultMessage": "Reorder {label}", + "description": "Accessible label on the handle at the end of a List row that drags the row to a new place or moves it with the arrow keys. `{label}` is the row's text (e.g. \"Reorder Inbox\")." + }, + "@astryx.list.reorderHandleVerb": { + "defaultMessage": "Reorder", + "description": "The handle's own accessible label at the end of a List row named through the row's label element: read first, then the row's label (e.g. \"Reorder\" then \"Inbox\"), so a label of any shape completes it. The verb alone, without the row's label." + }, + "@astryx.list.reorderHandleAt": { + "defaultMessage": "Reorder item {position, number}", + "description": "Accessible label on a List row's reorder handle when the row has no text label to name it after. `{position}` is the row's 1-based place in the list (e.g. \"Reorder item 3\")." + }, + "@astryx.list.reorderHint": { + "defaultMessage": "Drag to move this item, or press Space or Enter, then the arrow keys to move it one place at a time. Press Escape when you are done.", + "description": "Description read after the label of every reorder handle in a List: how to move a row by dragging, or in reorder mode, which the handle's Space or Enter turns on and Escape ends." + }, + "@astryx.list.reorderPlace": { + "defaultMessage": "{label}, position {position, number} of {total, number}, after {previous}, before {next}", + "description": "Screen-reader announcement after each move of a List row in reorder mode. `{label}` is the row's text, `{position}` its new 1-based place, `{total}` the number of rows, and `{previous}` and `{next}` the texts of the rows now before and after it (e.g. \"Milk, position 3 of 5, after Eggs, before Bread\")." + }, + "@astryx.list.reorderPlaceTop": { + "defaultMessage": "{label}, position {position, number} of {total, number}, at the top, before {next}", + "description": "Screen-reader announcement after a List row in reorder mode moves to the first place. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows, and `{next}` the text of the row now after it (e.g. \"Milk, position 1 of 5, at the top, before Eggs\")." + }, + "@astryx.list.reorderPlaceEnd": { + "defaultMessage": "{label}, position {position, number} of {total, number}, after {previous}, at the end", + "description": "Screen-reader announcement after a List row in reorder mode moves to the last place. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows, and `{previous}` the text of the row now before it (e.g. \"Milk, position 5 of 5, after Bread, at the end\")." + }, + "@astryx.list.reorderPlaceGrid": { + "defaultMessage": "{label}, row {row, number}, column {column, number}, position {position, number} of {total, number}", + "description": "Screen-reader announcement after an item in a two-dimensional reorderable layout (a grid or a wrapping board) moves in reorder mode. `{label}` is the item's text, `{row}` and `{column}` its 1-based row and column in reading order, `{position}` its 1-based place in the whole order, and `{total}` the number of items (e.g. \"Milk, row 2, column 3, position 8 of 12\")." + }, + "@astryx.list.reorderNotMoved": { + "defaultMessage": "Can't move {label}", + "description": "Screen-reader announcement when an item in a reorderable container of plain elements was moved but the app did not apply the move, so the item keeps its place. `{label}` is the item's name (e.g. \"Can't move King of hearts\")." + }, + "@astryx.list.reorderRefused": { + "defaultMessage": "Can't move past {label}", + "description": "Screen-reader announcement when an arrow key in reorder mode would move a List row past a row that keeps its place. `{label}` is that row's text (e.g. \"Can't move past Pinned\")." + }, + "@astryx.list.reorderItemAt": { + "defaultMessage": "Item {position, number}", + "description": "What reorder announcements call a List row that shows no text, such as an icon-only row. `{position}` is its 1-based place (e.g. \"after Item 2\")." + }, + "@astryx.list.reorderMoveUp": { + "defaultMessage": "Move up", + "description": "Accessible label of the up-arrow button in the hint a List row's reorder mode shows: it moves the row one place up, as the Up arrow key does." + }, + "@astryx.list.reorderMoveDown": { + "defaultMessage": "Move down", + "description": "Accessible label of the down-arrow button in the hint a List row's reorder mode shows: it moves the row one place down, as the Down arrow key does." + }, + "@astryx.list.reorderMoveLeft": { + "defaultMessage": "Move left", + "description": "Label of the button in reorder mode's hint that moves an item one place left in a horizontal or two-dimensional reorderable layout, as the Left arrow key does." + }, + "@astryx.list.reorderMoveRight": { + "defaultMessage": "Move right", + "description": "Label of the button in reorder mode's hint that moves an item one place right in a horizontal or two-dimensional reorderable layout, as the Right arrow key does." + }, + "@astryx.list.reorderDone": { + "defaultMessage": "Done", + "description": "Button in the hint a List row's reorder mode shows: it ends the mode and keeps the moves, as Escape does." + }, + "@astryx.list.reorderModeDone": { + "defaultMessage": "Done, {label} at position {position, number} of {total, number}", + "description": "Screen-reader announcement when a List row's reorder mode ends (Escape, the handle again, or Done), keeping its moves. `{label}` is the row's text, `{position}` its 1-based place, `{total}` the number of rows (e.g. \"Done, Milk at position 3 of 5\")." + }, + "@astryx.list.reorderPickedUp": { + "defaultMessage": "Picked up, position {position, number} of {total, number}.", + "description": "Screen-reader announcement when a row of a List is picked up to be reordered, from its handle's keys or by a drag. `{position}` is the row's 1-based place, `{total}` the number of rows." + }, + "@astryx.list.reorderDropped": { + "defaultMessage": "Dropped, position {position, number} of {total, number}", + "description": "Screen-reader announcement when a row being reordered in a List is dropped. `{position}` is its new 1-based place, `{total}` the number of rows." + }, + "@astryx.list.reorderCancelled": { + "defaultMessage": "Reorder cancelled, back to position {position, number} of {total, number}", + "description": "Screen-reader announcement when a reorder in a List is cancelled and the row returns to where it was. `{position}` is that 1-based place, `{total}` the number of rows." + }, "@astryx.listInput.emptyTitle": { "defaultMessage": "No {itemName}s yet", "description": "EmptyState title shown inside a lab ListInput when its collection has no records. `{itemName}` is the consumer's singular noun for one record (e.g. \"guest\"); the source appends a literal \"s\" to pluralize it, which only works for regular English plurals. If your language cannot pluralize an interpolated noun this way, rephrase around `{itemName}` instead (e.g. \"No {itemName} added yet\")." diff --git a/packages/core/package.json b/packages/core/package.json index 8bd491e6273cb..7e32f9fc19f2f 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -709,6 +709,11 @@ "types": "./dist/i18n/index.d.ts", "default": "./dist/i18n/index.js" }, + "./reorderable": { + "source": "./src/reorderable/index.ts", + "types": "./dist/reorderable/index.d.ts", + "default": "./dist/reorderable/index.js" + }, "./theme": { "source": "./src/theme/index.ts", "types": "./dist/theme/index.d.ts", @@ -859,6 +864,7 @@ "devDependencies": { "@astryxdesign/a11y-spec": "workspace:*", "@astryxdesign/cli": "workspace:*", + "@astryxdesign/interaction-harness": "workspace:*", "@babel/cli": "catalog:", "@babel/core": "catalog:", "@babel/preset-react": "catalog:", diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsx index 8358b096fb9ef..c6df634a5fb1b 100644 --- a/packages/core/src/Item/Item.test.tsx +++ b/packages/core/src/Item/Item.test.tsx @@ -345,6 +345,36 @@ describe('Item', () => { expect(anchor?.textContent).toContain('Link'); }); + it('follows the link on a click in a link row’s own box, outside its anchor (its padding, or its touch hit area under a finger)', () => { + const {container} = render(); + const anchor = container.querySelector('a') as HTMLAnchorElement; + const followed = vi.fn((event: MouseEvent) => event.preventDefault()); + anchor.addEventListener('click', followed); + const row = container.firstElementChild as HTMLElement; + fireEvent.click(row); + expect(followed).toHaveBeenCalledTimes(1); + // A click on the anchor itself follows it once, not twice. + fireEvent.click(anchor); + expect(followed).toHaveBeenCalledTimes(2); + // Modifier keys carry over, so a ctrl or cmd click opens as on the label. + fireEvent.click(row, {ctrlKey: true}); + expect(followed).toHaveBeenCalledTimes(3); + expect(followed.mock.calls[2][0].ctrlKey).toBe(true); + }); + + it('keeps a row with both onClick and href on onClick for a click in its own box', () => { + const onClick = vi.fn(); + const {container} = render( + , + ); + const anchor = container.querySelector('a') as HTMLAnchorElement; + const followed = vi.fn((event: MouseEvent) => event.preventDefault()); + anchor.addEventListener('click', followed); + fireEvent.click(container.firstElementChild as HTMLElement); + expect(onClick).toHaveBeenCalledTimes(1); + expect(followed).not.toHaveBeenCalled(); + }); + it('sets target on anchor when provided', () => { const {container} = render( , diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsx index 34b264d00124d..0bce59eabcda1 100644 --- a/packages/core/src/Item/Item.tsx +++ b/packages/core/src/Item/Item.tsx @@ -4,7 +4,9 @@ /** * @file Item.tsx - * @input Uses React, ReactNode, StyleXStyles, theme tokens, useClickableContainer + * @input Uses React, ReactNode, StyleXStyles, theme tokens, useClickableContainer, + * the shared press overlays and the compositor press layer, and a row's + * trailing control (ItemTrailingContext) * @output Exports Item component, ItemProps type; publishes the shared inline inset * @position Core layout primitive; consumed by index.ts, tested by Item.test.tsx * @@ -28,6 +30,7 @@ import { lazy, Suspense, + use, useCallback, useId, useRef, @@ -45,6 +48,8 @@ import { import type {BaseProps} from '../BaseProps'; import {isRenderable, mergeProps} from '../utils'; import {ItemDescriptionContext} from './ItemDescriptionContext'; +import {ItemLabelContext} from './ItemLabelContext'; +import {ItemTrailingContext} from './ItemTrailingContext'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {computeTargetAndRel} from '../Link/computeTargetAndRel'; import {useLinkComponent} from '../Link/useLinkComponent'; @@ -53,6 +58,7 @@ import {useDevWarning} from '../hooks/useDevWarning'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; +import {rowPressLayerStyles} from '../utils/rowPressLayer'; import {usePressFeedback} from '../hooks/usePressFeedback'; import type {ItemSwipeBridge} from './ItemSwipeLayer'; @@ -671,6 +677,10 @@ export function Item({ // only once React runs it, such as an empty fragment, still publishes an id. const descriptionID = useId(); const hasRenderableDescription = isRenderable(description); + // The label element's id, published through ItemLabelContext for a control + // Item renders in a slot that is named after the row (`aria-labelledby`). + const labelID = useId(); + const hasRenderableLabel = isRenderable(label); const isStringLabel = typeof label === 'string'; const isStringDescription = typeof description === 'string'; @@ -700,6 +710,7 @@ export function Item({ const labelAndDescription = ( <> ('[data-astryx-row-link]') + ?.dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + ctrlKey: e.ctrlKey, + metaKey: e.metaKey, + shiftKey: e.shiftKey, + altKey: e.altKey, + button: e.button, + }), + ); + return; + } onClick?.(e); }; + // A control a row adds after the slots, unwrapped (ItemTrailingContext): + // a List row's reorder handle when the row has no end content. + const trailing = use(ItemTrailingContext); + const innerContent = ( <> {marker} @@ -768,6 +803,7 @@ export function Item({ href={href} target={target} rel={rel} + data-astryx-row-link="" aria-disabled={isDisabled || undefined} tabIndex={isDisabled ? -1 : undefined} {...stylex.props( @@ -810,6 +846,7 @@ export function Item({ {endContent} )} + {trailing} ); @@ -886,6 +923,10 @@ export function Item({ align === 'first-line' && styles.alignFirstLine, isInteractive && styles.interactive, isInteractive && interactionOverlayStyles.backgroundColor, + // The touch press on a compositor layer (after the overlay, whose + // own touch paint it turns off): the release keeps fading while + // script runs. + isInteractive && rowPressLayerStyles.cell, isLinkRoot && styles.linkRoot, isHighlighted && styles.highlighted, isSelected && styles.selected, @@ -898,10 +939,14 @@ export function Item({ )} role={role} onClick={rootOnClick}> - - {innerContent} - + + + + {innerContent} + + + {hasSwipe && ( // The panels: out-of-flow children of this root, so the DOM is the one // the row had before the split. Suspense and lazy add no element, and diff --git a/packages/core/src/Item/ItemLabelContext.tsx b/packages/core/src/Item/ItemLabelContext.tsx new file mode 100644 index 0000000000000..2b7a99199324b --- /dev/null +++ b/packages/core/src/Item/ItemLabelContext.tsx @@ -0,0 +1,24 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ItemLabelContext.tsx + * @input Uses React createContext + * @output Exports ItemLabelContext + * @position Internal seam between Item and a control it renders in a slot + * + * Item renders the row's label and owns the element that holds it. A control + * Item renders in a slot (a List row's reorder handle, which is named + * "Reorder" followed by the row's label) points at that element with + * `aria-labelledby`, so a label of any shape names it; only Item knows the + * element's id. Publishing it here keeps that wiring internal, as + * ItemDescriptionContext does for the description. + * + * `null` when the row renders no label. + */ + +import {createContext} from 'react'; + +export const ItemLabelContext = createContext(null); +ItemLabelContext.displayName = 'ItemLabelContext'; diff --git a/packages/core/src/Item/ItemTrailingContext.tsx b/packages/core/src/Item/ItemTrailingContext.tsx new file mode 100644 index 0000000000000..73c972e56b910 --- /dev/null +++ b/packages/core/src/Item/ItemTrailingContext.tsx @@ -0,0 +1,26 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ItemTrailingContext.tsx + * @input Uses React createContext + * @output Exports ItemTrailingContext + * @position Internal seam between Item and a row component that adds one + * control after Item's slots + * + * A List row's reorder handle is the one element reordering adds to a row + * (spec:AST-103 FR5). With end content, the handle joins Item's end slot; + * without it, putting the handle in `endContent` would wrap it in an end-slot + * element of its own, a second element. Such a row passes the handle here + * instead, and Item renders it after its slots, unwrapped. Item resets the + * context for what it renders, so a nested Item never renders its parent's + * control. + * + * `null` when the row adds nothing. + */ + +import {createContext, type ReactNode} from 'react'; + +export const ItemTrailingContext = createContext(null); +ItemTrailingContext.displayName = 'ItemTrailingContext'; diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjs index 81b2acaba52ec..bab59c7459f40 100644 --- a/packages/core/src/List/List.doc.mjs +++ b/packages/core/src/List/List.doc.mjs @@ -32,7 +32,7 @@ export const docs = { { name: 'density', type: "'compact' | 'balanced' | 'spacious'", - description: 'Spacing density for items.', + description: "Spacing density for items. Under a finger, an interactive row's hit target reaches 44px where its neighbors leave room, with no change to how rows look or lay out.", default: "'balanced'", }, { @@ -41,6 +41,18 @@ export const docs = { description: 'Show dividers between items.', default: 'false', }, + { + name: 'hasAnimatedChanges', + type: 'boolean', + description: 'Under a finger, animate changes to the rows the way an iOS table does: when rows are inserted, removed or reordered, the rows that stay slide to their new places, a removed row collapses in place, and new rows fade in once the rows sliding past have cleared them; a row that crosses rows moving the other way rides above them with the surface color behind it. Rows need stable keys. With a mouse nothing moves.', + default: 'false', + }, + { + name: 'reorderable', + type: 'Reorderable', + description: + "Makes the rows reorderable, with the object createReorderable({onReorder, isReorderable}) makes: each ListItem with an itemKey gets a reorder handle at its end, and each committed move calls onReorder once with the row's key and its index after the move ({key, to}); render the rows in the new order to apply it. A row the object's isReorderable rejects has no handle and keeps its place; one at either end of the list also bounds the others. The object may be made on every render. On a touch screen, a finger held still on a handle for a moment picks up its row (a flick on it still scrolls): the row stays in its place, dimmed, while a copy of it follows the finger and an accent line marks where it would land; the other rows stay still, the page scrolls near the edges, and on release the rows rearrange, gliding to their new places. A mouse drags a handle at once with the same copy and line, and the rows take their places without motion; a drag reports once, at the drop, and a cancelled drag puts everything back at once. In reorder mode the line marks the row's new place after each move. Without a drag, the handle is a toggle: a click, Space or Enter turns on reorder mode for its row (aria-pressed), in which each Up or Down arrow moves the row a place at once and reports it, and Escape or another activation ends the mode, keeping the moves. Each move is announced once it renders, with the row's place and its neighbours ('Milk, position 3 of 5, after Eggs, before Bread'), and a move into a row that keeps its place is refused and announced. While the mode is on, a hint anchored to the handle shows the moves and Done as buttons that do what the keys do, so a row can also be reordered by taps alone. The object's start(key) enters the same mode from your own UI, such as a row's context menu. A disabled row's handle stays focusable but moves nothing.", + }, { name: 'edge', type: "'padded' | 'flush' | 'outset' | 'bleed'", @@ -107,6 +119,8 @@ export const docs = { {name: 'Description', required: false, description: 'Supplementary text below the title.'}, {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', required: false, description: 'Additional detail for an individual list item.'}, + {name: 'Reorder handle', required: false, description: 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.'}, + {name: 'Reorder hint', required: false, description: "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons."}, ], }, }; @@ -129,6 +143,8 @@ export const docsZh = { {name: 'Description', required: false, description: 'Supplementary text below the title.'}, {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', required: false, description: 'Additional detail for an individual list item.'}, + {name: 'Reorder handle', required: false, description: 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.'}, + {name: 'Reorder hint', required: false, description: "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons."}, ], }, }; @@ -154,6 +170,8 @@ export const docsDense = { {name: 'Description', required: false, description: 'Supplementary text below the title.'}, {name: 'List items', required: true, description: 'Individual entries, which may include icons or images.'}, {name: 'Item description', required: false, description: 'Additional detail for an individual list item.'}, + {name: 'Reorder handle', required: false, description: 'With reorderable: the button at the end of each row that can move. It drags the row, and toggles its reorder mode.'}, + {name: 'Reorder hint', required: false, description: "While a row is in reorder mode: the hint below its handle, like Core's keyboard hint, whose moves and Done are buttons."}, ], }, }; diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsx index 8ed1f09f40b38..175e3b2b054ce 100644 --- a/packages/core/src/List/List.test.tsx +++ b/packages/core/src/List/List.test.tsx @@ -13,9 +13,45 @@ import {describe, it, expect, vi} from 'vitest'; import {cleanup, render, screen, waitFor} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import {rulesDeclaredFor} from '../__tests__/pressState'; + +/** + * The element's injected rules split by the touch gate: inside + * `@media (pointer: coarse)` (TOUCH_QUERY, utils/touchPresentation.ts), or + * not. + */ +function touchGatedRules(el: Element): {touch: string[]; other: string[]} { + const classes = el.className + .split(/\s+/) + .filter(Boolean) + .map(name => `.${name}`); + const out = {touch: [] as string[], other: [] as string[]}; + const visit = (rules: CSSRuleList, touch: boolean) => { + for (const rule of Array.from(rules)) { + if (rule instanceof CSSStyleRule) { + if (classes.some(cls => rule.selectorText.startsWith(cls))) { + (touch ? out.touch : out.other).push( + `${rule.selectorText} {${rule.style.cssText}}`, + ); + } + continue; + } + const nested = (rule as CSSGroupingRule).cssRules; + if (nested == null) { + continue; + } + const condition = (rule as CSSConditionRule).conditionText ?? ''; + visit(nested, touch || condition.includes('pointer: coarse')); + } + }; + for (const sheet of Array.from(document.styleSheets)) { + visit(sheet.cssRules, false); + } + return out; +} import {List} from './List'; import {ListItem} from './ListItem'; import {ListMarkerScope} from './ListContext'; +import {HIT_INSET_PROPERTIES} from '../utils/hitArea'; describe('List', () => { it('forwards ListItem align to its Item row unchanged', () => { @@ -488,6 +524,55 @@ describe('List', () => { expect(hrs).toHaveLength(0); }); + // =========================================================================== + // Touch hit area (`spec:AST-094` FR42; `component:List` FR10, #8571) + // =========================================================================== + + /** The rules among `rules` whose selector reaches the row's `::after`. */ + const afterRules = (rules: string[]): string[] => + rules.filter(rule => rule.slice(0, rule.indexOf('{')).includes('::after')); + + it('gives an interactive, enabled row an invisible hit layer under a finger only', () => { + render( + + {}} /> + + + {}} isDisabled /> + , + ); + const row = (text: string) => screen.getByText(text).closest('li')!; + for (const text of ['Pressable', 'Link']) { + const {touch, other} = touchGatedRules(row(text)); + const layer = afterRules(touch).join('\n'); + // Positioned past the row by the measured insets, clipped to the band + // outside the row's own box, and painting nothing. + expect(layer).toContain('position: absolute'); + expect(layer).toMatch(/clip-path: polygon\(evenodd/); + for (const side of ['top', 'right', 'bottom', 'left'] as const) { + expect(layer).toMatch( + new RegExp( + `${side}: calc\\(var\\(${HIT_INSET_PROPERTIES[side]}, ?0px\\) \\* -1\\)`, + ), + ); + } + expect(layer).not.toMatch(/background|border|box-shadow|outline|z-index/); + // At rest the row's stacking stays as it was: only a press isolates it + // (the press layer, utils/rowPressLayer.ts). + for (const rule of touch.filter(r => r.includes('isolation'))) { + expect(rule.slice(0, rule.indexOf('{'))).toContain( + '[data-astryx-press', + ); + } + // With a mouse: no pseudo-element. + expect(afterRules(other)).toEqual([]); + } + // A row with nothing to press offers no target. + for (const text of ['Read-only', 'Disabled']) { + expect(afterRules(touchGatedRules(row(text)).touch)).toEqual([]); + } + }); + // =========================================================================== // Interactive items — onClick (invisible button pattern) // =========================================================================== diff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsx index b2379d9104181..4418a57e5768a 100644 --- a/packages/core/src/List/List.tsx +++ b/packages/core/src/List/List.tsx @@ -10,6 +10,14 @@ * types * @position Core implementation; consumed by index.ts, tested by List.test.tsx * + * `hasAnimatedChanges` runs the update motion (utils/useListUpdateMotion.ts); + * `reorderable` runs the reorder session after it. List imports only the + * reorderable object's type and its key (List/listReorderContext.ts), and + * hands the reorder to its rows through ListContext: the session, its + * handle, its listeners and its menu come with the object + * (reorderable/createReorderable.ts), so a List without it loads no reorder + * code (spec:AST-103 FR2). + * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/List/List.doc.mjs * - /packages/core/src/List/List.test.tsx @@ -18,7 +26,8 @@ * - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks) */ -import {useId, useMemo, type ReactNode} from 'react'; +import {useId, useMemo, useRef, type ReactNode} from 'react'; +import type {Reorderable} from '../reorderable/createReorderable'; import * as stylex from '@stylexjs/stylex'; import {spacingVars} from '../theme/tokens.stylex'; import type {BaseProps} from '../BaseProps'; @@ -29,8 +38,16 @@ import { type ListMarkerStyle, } from './ListContext'; import {mergeProps} from '../utils'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import {keepPresentation, useListUpdateMotion} from './useListUpdateMotion'; import {themeProps} from '../utils/themeProps'; import {useDevWarning} from '../hooks/useDevWarning'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + REORDER_ENGINE, + type ListReorderOptions, + type ReorderableInternals, +} from './listReorderContext'; export { type ListDensity, @@ -57,6 +74,42 @@ export interface ListProps extends BaseProps< */ density?: ListDensity; + /** + * Under a finger (iOS and Android alike), animate the list's changes the + * way an iOS table does: when rows are inserted, removed or reordered, the rows + * that stay slide from where they were to where they are and new rows fade + * in once the rows sliding past have cleared them, on UIKit's table update + * spring. A row that crosses rows moving the other way rides above them + * with the surface color behind it. A removed row collapses in place, a + * swiped one with its action showing, while the rows below close its gap. + * Off by default; with a mouse nothing moves. + * @default false + */ + hasAnimatedChanges?: boolean; + + /** + * Makes the rows reorderable, with the object `createReorderable` makes: + * each ListItem with an `itemKey` gets a reorder handle at its end (one the + * object's `isReorderable` rejects keeps its place), and each committed + * move calls its `onReorder` once with the row's key and its index after + * the move. Apply it by rendering the rows in their new order; a drop on + * the starting place, a cancel, or a move the order does not take changes + * nothing. + * + * On a touch screen a finger held still on a handle for a moment picks up + * its row (a flick on it still scrolls); the row stays in its place, + * dimmed, while a copy of it follows the finger and an accent line marks + * where it would land, the other rows stay still, the list scrolls near the + * edges, and on release the rows rearrange. A mouse drags a handle at once, + * the same way. Without a drag, activating a + * handle (a click, Space or Enter) turns on reorder mode for its row: each + * arrow key moves it a place at once, reported and announced with its place + * and neighbours, and Escape or another activation ends the mode, keeping + * the moves. While it is on, a hint anchored to the handle shows the moves + * and Done as buttons, so taps alone can reorder. + */ + reorderable?: Reorderable; + /** * Whether to show dividers between list items. * @default false @@ -209,6 +262,8 @@ const dynamicStyles = stylex.create({ */ export function List({ children, + reorderable, + hasAnimatedChanges = false, density = 'balanced', hasDividers = false, edge: edgeProp, @@ -224,6 +279,27 @@ export function List({ ...props }: ListProps) { const headerId = useId(); + const listRef = useRef(null); + // The reorder's machinery comes with the object (spec:AST-103 FR2). The + // object may be made on every render: the session lasts as long as its + // machinery, and reads the object's latest callbacks. + const reorder = reorderable as ReorderableInternals | undefined; + const reorderEngine = reorder?.[REORDER_ENGINE]; + const reorderOptions = reorder?.options; + // The handles' instructions take the header's id with a suffix. + const reorderSession = useMemo( + () => reorderEngine?.createSession(() => listRef.current, `${headerId}h`), + [reorderEngine, headerId], + ); + useListUpdateMotion(listRef, hasAnimatedChanges); + // After the update motion, so a drop's commit is the reorder's. + useIsomorphicLayoutEffect(() => { + reorderSession?.commit(); + }); + const mergedRef = useMergedRefs( + listRef, + ref as React.Ref, + ); const isOrdered = listStyle === 'decimal'; const Tag = isOrdered ? 'ol' : 'ul'; // Plain use of the deprecated prop is reported by its @deprecated type; @@ -239,13 +315,32 @@ export function List({ const reachesContainerPadding = edge === 'outset' || edge === 'bleed'; const contextValue = useMemo( - () => ({density, hasDividers, edge, listStyle}), - [density, hasDividers, edge, listStyle], + () => ({ + density, + hasDividers, + edge, + listStyle, + keepRowPresentation: hasAnimatedChanges ? keepPresentation : undefined, + // With a session there is an object, so its options too. + reorder: reorderSession && { + session: reorderSession, + options: reorderOptions as ListReorderOptions, + }, + }), + [ + density, + hasDividers, + edge, + listStyle, + hasAnimatedChanges, + reorderSession, + reorderOptions, + ], ); const listElement = ( } + ref={mergedRef} // Consumer props first: everything the component sets for itself below // is part of its contract and wins on conflict. {...props} @@ -271,6 +366,7 @@ export function List({ (start != null && start !== 1 ? dynamicStyles.counterStart(start - 1) : styles.withCounter), + reorderSession?.listStyle, xstyle, ), className, @@ -280,8 +376,19 @@ export function List({ ); + // The session's options and listeners, and the handles' instructions. + const {reorder: reorderValue} = contextValue; + const reorderHost = reorderValue && ( + + ); + if (header == null) { - return {listElement}; + return ( + + {listElement} + {reorderHost} + + ); } return ( @@ -291,6 +398,7 @@ export function List({ {header} {listElement} + {reorderHost} ); diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsx index 2d48ed47e1d35..1bda601b23816 100644 --- a/packages/core/src/List/ListContext.tsx +++ b/packages/core/src/List/ListContext.tsx @@ -6,14 +6,15 @@ * @file ListContext.tsx * @input Layer-scoped React context * @output Exports ListContext for sharing density, dividers, the row edge - * treatment, and marker style between List and ListItem, and - * ListMarkerScope, which sets the marker for the items inside it, or a - * task item's checkbox in its place + * treatment, marker style and a reorderable List's reorder between List + * and ListItem, and ListMarkerScope, which sets the marker for the items + * inside it, or a task item's checkbox in its place * @position Internal context; consumed by List.tsx and ListItem.tsx */ import {use, useMemo, type ReactNode} from 'react'; import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext'; +import type {ListReorderContextValue} from './listReorderContext'; export type ListDensity = 'compact' | 'balanced' | 'spacious'; export type ListMarkerStyle = 'none' | 'disc' | 'decimal' | 'circle'; @@ -54,6 +55,19 @@ export interface ListContextValue { * `'none'`. */ task?: ListTaskMarker; + /** + * Set while the list animates its changes (`hasAnimatedChanges`); + * internal. A row leaving the list calls it as it unmounts, while it is + * still in the document, so the removal's collapse shows it as it was on + * screen (List/useListUpdateMotion.ts `keepPresentation`, the list's + * touch layer, reached only through the list). + */ + keepRowPresentation?: (row: HTMLElement) => void; + /** + * A reorderable List's reorder (`List reorderable`); internal. Its rows end + * with the handle it carries (List/listReorderContext.ts). + */ + reorder?: ListReorderContextValue | null; } export const ListContext = createContext(null); diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjs index 74b23fd4b92c6..b525737f49807 100644 --- a/packages/core/src/List/ListItem.doc.mjs +++ b/packages/core/src/List/ListItem.doc.mjs @@ -104,9 +104,16 @@ export const docs = { { name: 'isSelected', type: 'boolean', - description: 'Selected state; marks the item as the current one with aria-current="true" (a list item cannot carry aria-selected).', + description: + 'Selected state; marks the item as the current one with aria-current="true" (a list item cannot carry aria-selected).', default: 'false', }, + { + name: 'itemKey', + type: 'string | number', + description: + "The row's item key in a reorderable List (List reorderable), a string or a number from the data (the shape Table's idKey returns): the key the reorderable object's onReorder reports as given and isReorderable is asked about. A row without one has no reorder handle and keeps its place. Separate from React's key. No effect elsewhere.", + }, { name: 'swipeActions', type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}', @@ -196,7 +203,8 @@ export const docsZh = { { name: 'isSelected', type: 'boolean', - description: '选中状态;在项目上设置 aria-current="true",将其标为当前项(列表项不能使用 aria-selected)。', + description: + '选中状态;在项目上设置 aria-current="true",将其标为当前项(列表项不能使用 aria-selected)。', default: 'false', }, { @@ -223,6 +231,8 @@ export const docsDense = { propDescriptions: { align: "Start/end content alignment, passed to Item: 'center' (default), 'start', or 'first-line' (centered on the label's first line).", + itemKey: + 'In a reorderable List: the key onReorder reports; without one the row keeps its place.', label: 'Primary content. String auto-truncates; ReactNode renders as given.', description: 'Secondary text below label.', diff --git a/packages/core/src/List/ListItem.hitArea.test.tsx b/packages/core/src/List/ListItem.hitArea.test.tsx new file mode 100644 index 0000000000000..528153c77365f --- /dev/null +++ b/packages/core/src/List/ListItem.hitArea.test.tsx @@ -0,0 +1,187 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListItem.hitArea.test.tsx + * @input Vitest, Testing Library, and utils/hitArea.ts with `watchHitArea` + * spied (the rest real) + * @output Checks that ListItem keeps an interactive, enabled row's touch hit + * insets live through the shared utility (`spec:AST-094` FR42; `component:List` FR10, #8571): which + * rows it watches, that the insets land on the row, the theme's touch + * target size under a finger, that a measurement taken mid-motion waits for + * the motion to end, and that it stops when the row goes + * @position Test for ListItem's hit area wiring (ListItem.tsx, through + * utils/touchHitArea.ts); the layer's own CSS is checked in List.test.tsx, its + * hit testing in __tests__/ListTouchHitArea.interaction.browser.spec.ts + */ + +import {createRef} from 'react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {render, screen} from '@testing-library/react'; +import type * as HitAreaModule from '../utils/hitArea'; +import type {HitInsets} from '../utils/hitArea'; + +const watches = vi.hoisted( + () => + [] as { + element: Element; + onInsets: (insets: HitInsets) => void; + minSize: number | undefined; + stop: ReturnType; + }[], +); + +vi.mock('../utils/hitArea', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + watchHitArea: ( + element: Element, + onInsets: (insets: HitInsets) => void, + options?: {readonly minSize?: number}, + ) => { + const stop = vi.fn(); + watches.push({element, onInsets, minSize: options?.minSize, stop}); + return stop; + }, + }; +}); + +import {List} from './List'; +import {ListItem} from './ListItem'; + +describe('ListItem touch hit area (spec:AST-094 FR42; component:List FR10)', () => { + afterEach(() => { + watches.length = 0; + vi.unstubAllGlobals(); + }); + + const row = (text: string) => screen.getByText(text).closest('li')!; + + it('watches each interactive, enabled row, and no other', () => { + const control = createRef(); + render( + + {}} /> + + + Toggle + + } + /> + + {}} isDisabled /> + , + ); + expect(watches.map(watch => watch.element)).toEqual([ + row('Pressable'), + row('Link'), + row('Delegated'), + ]); + }); + + it('puts the measured insets on the row, where its layer reads them', () => { + render( + + {}} /> + , + ); + expect(watches).toHaveLength(1); + watches[0].onInsets({top: 4, right: 0, bottom: 1, left: 0}); + const style = row('Pressable').style; + expect(style.getPropertyValue('--astryx-hit-inset-top')).toBe('4px'); + expect(style.getPropertyValue('--astryx-hit-inset-bottom')).toBe('1px'); + expect(style.getPropertyValue('--astryx-hit-inset-left')).toBe('0px'); + }); + + it('grows toward the theme’s touch target under a finger, and 44px otherwise', () => { + const {unmount} = render( + + {}} + style={{['--size-touch-target' as string]: '48px'}} + /> + , + ); + // No coarse pointer: the 44px minimum, whatever the theme says. + expect(watches.map(watch => watch.minSize)).toEqual([44]); + unmount(); + watches.length = 0; + vi.stubGlobal('matchMedia', (media: string) => ({ + media, + matches: media === '(pointer: coarse)', + addEventListener: () => {}, + removeEventListener: () => {}, + })); + render( + + {}} + style={{['--size-touch-target' as string]: '48px'}} + /> + {}} /> + , + ); + expect(watches.map(watch => watch.minSize)).toEqual([48, 44]); + }); + + it('drops a measurement taken while the list moves, and watches the row afresh once the motion ends', async () => { + render( + + {}} /> + , + ); + const row = screen.getByText('Pressable').closest('li')!; + const list = row.parentElement!; + let finish = (): void => {}; + const finished = new Promise(resolve => { + finish = resolve; + }); + const motion = { + playState: 'running', + effect: {getComputedTiming: () => ({endTime: 300})}, + finished, + } as unknown as Animation; + list.getAnimations = () => [motion]; + expect(watches).toHaveLength(1); + watches[0].onInsets({top: 3, right: 0, bottom: 1, left: 0}); + // Mid-motion: nothing written. + expect(row.style.getPropertyValue('--astryx-hit-inset-top')).toBe(''); + list.getAnimations = () => []; + finish(); + await vi.waitFor(() => expect(watches).toHaveLength(2)); + // The old watch stopped, and the fresh one measures the row at rest. + expect(watches[0].stop).toHaveBeenCalledTimes(1); + watches[1].onInsets({top: 4, right: 0, bottom: 1, left: 0}); + expect(row.style.getPropertyValue('--astryx-hit-inset-top')).toBe('4px'); + }); + + it('stops watching when the row goes or turns disabled', () => { + const {rerender, unmount} = render( + + {}} /> + , + ); + expect(watches).toHaveLength(1); + rerender( + + {}} isDisabled /> + , + ); + expect(watches[0].stop).toHaveBeenCalledTimes(1); + expect(watches).toHaveLength(1); + rerender( + + {}} /> + , + ); + expect(watches).toHaveLength(2); + unmount(); + expect(watches[1].stop).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsx index 249d20f960efe..dc1588e99d6f6 100644 --- a/packages/core/src/List/ListItem.tsx +++ b/packages/core/src/List/ListItem.tsx @@ -5,12 +5,18 @@ /** * @file ListItem.tsx * @input Uses React, ReactNode, StyleXStyles, theme tokens, the List row edge - * treatment, CheckboxInput, and the marker or task checkbox a - * ListMarkerScope sets (Markdown's nested lists and the task items of mixed - * lists) + * treatment, the touch hit area (utils/touchHitArea.ts and its layer), the + * travelling marker of an update's slide (List/useListUpdateMotion.ts), + * CheckboxInput, and the marker or task checkbox a ListMarkerScope sets + * (Markdown's nested lists and the task items of mixed lists) * @output Exports ListItem component, ListItemProps type * @position Core implementation; consumed by List, index.ts, tested by List.test.tsx * + * In a reorderable List (`List reorderable`), each row with an `itemKey` + * that the reorderable object lets move ends with its handle, which comes + * through ListContext's `reorder` with the rest of the reorder machinery + * (List/listReorderContext.ts); a row without one keeps its place. + * * Composes Item for the shared start content + label + description + end content layout * and the invisible button/anchor interactive pattern. * @@ -22,7 +28,7 @@ * - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks) */ -import {use, type ReactNode} from 'react'; +import {use, useMemo, useRef, type ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; import type {StyleXStyles} from '@stylexjs/stylex'; import { @@ -35,9 +41,14 @@ import type {BaseProps} from '../BaseProps'; import {ListContext, type ListMarker} from './ListContext'; import {CheckboxInput} from '../CheckboxInput'; import {mergeProps} from '../utils'; +import {ItemTrailingContext} from '../Item/ItemTrailingContext'; import {Item} from '../Item'; import type {ItemAlign, ItemSwipeActions, ItemSwipeBehavior} from '../Item'; import {themeProps} from '../utils/themeProps'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import {useTouchHitArea} from '../utils/touchHitArea'; +import {touchHitAreaStyles} from '../utils/touchHitArea.stylex'; // ============================================================================= // Types @@ -128,6 +139,15 @@ export interface ListItemProps extends BaseProps { */ isSelected?: boolean; + /** + * The row's item key in a reorderable List (`List reorderable`), a string + * or a number from the data (the shape Table's `idKey` returns): the key + * the reorderable object's `onReorder` reports as given and `isReorderable` + * is asked about. A row without one has no reorder handle. Separate from + * React's `key`, which stays React's own. No effect elsewhere. + */ + itemKey?: string | number; + /** * Swipe actions for touch, passed through to `Item` unchanged: the verbs a * sideways drag uncovers on each side. See `Item.swipeActions`; `List` @@ -151,6 +171,24 @@ const styles = stylex.create({ withCounter: { counterIncrement: 'astryx-list', }, + // A row an update slides across rows moving the other way rides above them + // with the surface behind it, for the length of its slide (the attribute + // List/useListUpdateMotion.ts writes): a UIKit cell passes its neighbours + // opaque and on top, and rows here have no background of their own. The + // surface is an inset shadow across the padding box, under the press layer + // and the row's content, so the row's divider and its press stay visible; + // a selected row keeps its own fill. It takes no pseudo-element: under a + // finger the row's `::after` is its hit layer (List/listRow.stylex.ts). + travelling: { + zIndex: { + default: null, + '[data-astryx-travelling]': 1, + }, + boxShadow: { + default: null, + '[data-astryx-travelling]:not([aria-selected="true"],[aria-current="true"])': `inset 0 0 0 100vmax ${colorVars['--color-background-surface']}`, + }, + }, // List's edge treatments. Each reads --_item-inset-inline, the variable // Item derives its paddingInline from, on the row itself (custom properties // only cascade downward, so the
    cannot read it); density and theme @@ -319,6 +357,7 @@ export function ListItem({ rel, isDisabled = false, isSelected = false, + itemKey, align, xstyle, className, @@ -327,6 +366,72 @@ export function ListItem({ ...restProps }: ListItemProps) { const ctx = use(ListContext); + const rowRef = useRef(null); + const mergedRef = useMergedRefs(ref, rowRef); + const keepRowPresentation = ctx?.keepRowPresentation; + const keepRowPresentationRef = useRef(keepRowPresentation); + useIsomorphicLayoutEffect(() => { + keepRowPresentationRef.current = keepRowPresentation; + }); + // External system (`architecture:react-component-runtime` INV3): the Web + // Animations running on the row's parts (a swipe's travel, on the + // compositor), which a detached row loses. Leaving a list that animates + // its changes, the row writes what they present inline while it is still + // in the document (a parent's layout cleanup runs before React removes the + // row), so the removal's collapse shows it as it was on screen. + useIsomorphicLayoutEffect(() => { + const row = rowRef.current; + return () => { + if (row != null) { + keepRowPresentationRef.current?.(row); + } + }; + }, []); + // In a reorderable List: a trailing handle, or a row that stays put. + const reorder = ctx?.reorder; + const hasHandle = + reorder != null && + itemKey != null && + (reorder.options.isReorderable?.(itemKey) ?? true); + // The handle is the one element reordering adds to a row (spec:AST-103 + // FR5): with end content it joins the end slot; without, it is the row's + // own child (ItemTrailingContext), since an end slot of its own would be a + // second element. + const isHandleInRow = hasHandle && endContent == null; + const rowLabel = restProps['aria-label']; + const rowLabelledBy = restProps['aria-labelledby']; + const rowAlign = isHandleInRow ? (align ?? 'center') : undefined; + const Handle = reorder?.session.Handle; + const reorderHandle = useMemo( + () => + hasHandle && Handle != null && itemKey != null ? ( + + ) : null, + [ + Handle, + hasHandle, + isDisabled, + itemKey, + label, + rowAlign, + rowLabel, + rowLabelledBy, + ], + ); + // Under a finger, an interactive row's hit target grows toward the touch + // target where its neighbors leave room, with no visual or layout change + // (`spec:AST-094` FR42; `component:List` FR10, #8571): useTouchHitArea keeps the row's insets live, and + // its invisible layer (touchHitAreaStyles.layer) reads them. + const isTouchTarget = + (onClick != null || href != null || interactiveRef != null) && !isDisabled; + useTouchHitArea(rowRef, isTouchTarget); const density = ctx?.density ?? 'balanced'; const hasDividers = ctx?.hasDividers ?? false; const edge = ctx?.edge ?? 'padded'; @@ -368,15 +473,32 @@ export function ListItem({ ) : null; - return ( + // A row without a handle in a reorderable List still has a name for the + // announcements of the moves beside it. It follows the row, so the row's + // element is set when it records it. + const reorderName = + reorder && !reorderHandle ? ( + + ) : null; + + const row = ( + {endContent} + {reorderHandle} + + ) : ( + endContent + ) + } onClick={onClick} interactiveRef={interactiveRef} href={href} @@ -389,11 +511,16 @@ export function ListItem({ xstyle={ [ hasMarkers && styles.withCounter, + styles.travelling, hasDividers && styles.withDivider, hasDividers && embeddedStyles.noRadius, + isTouchTarget && touchHitAreaStyles.layer, edge === 'flush' && styles.edgeFlush, edge === 'outset' && styles.edgeOutset, edge === 'bleed' && styles.edgeBleed, + // A focused handle rings itself; the row's focus-within ring stays + // off for it (two rings, and the list clips the row's sides). + reorderHandle && reorder?.session.rowStyle, xstyle, ] as StyleXStyles } @@ -401,6 +528,16 @@ export function ListItem({ {...restProps} /> ); + return ( + <> + {/* One shape whether or not the handle is the row's own child, so the + row keeps its element when that changes. */} + + {row} + + {reorderName} + + ); } ListItem.displayName = 'ListItem'; diff --git a/packages/core/src/List/ListReorderHandle.tsx b/packages/core/src/List/ListReorderHandle.tsx new file mode 100644 index 0000000000000..7cff5d9f0f87b --- /dev/null +++ b/packages/core/src/List/ListReorderHandle.tsx @@ -0,0 +1,508 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ListReorderHandle.tsx + * @input The List's reorder session (List/listReorderEngine.tsx, through + * ListContext's `reorder`), the translator and theme tokens + * @output `ListReorderHandle`, `ListReorderRowName` and `reorderRowStyle`: + * the trailing handle of a reorderable List row, a button that a finger + * (held still for a moment, where the primary pointer is coarse) or a + * mouse drags, and a toggle (`aria-pressed`) whose activation without a + * drag (a click, Space or Enter) turns its row's reorder mode on and off + * (spec:AST-103 FR4); the name of a row without one; and the style of a + * row that has one + * @position Part of the reorder machinery that createReorderable carries: + * ListItem renders it, from the List's context, at the end of each row + * that can move + * + * UIKit's reorder control (iOS 26.2, measured): the three gray lines at the + * trailing edge of a row in edit mode. A finger held still on it for the + * scroll view's content-touch delay (150 ms) claims the drag; a flick that + * starts on it scrolls the table instead, so the handle leaves the browser + * everything but double-tap zoom (`manipulation`, for a long press: + * spec:AST-094 FR18) until the claim. All of that applies only where the + * primary pointer is coarse (spec:AST-094 FR19); + * elsewhere a finger gets the browser's defaults. The handle is the one + * element the reorder adds to a row (spec:AST-103 FR5): its lines are a + * pseudo-element, and it listens to nothing itself. The list's listeners + * (the session's) take its drags; its keys go through React's. + * + * SYNC: When modified, update List/listReorderEngine.tsx and + * List/ListItem.tsx. + */ + +import { + isValidElement, + use, + useEffect, + useRef, + useSyncExternalStore, + useId, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import * as stylex from '@stylexjs/stylex'; +import {colorVars, focusVars, typeScaleVars} from '../theme/tokens.stylex'; +import {focusOutlineProps} from '../utils/focusOutline.stylex'; +import {ownRingContainerStyles} from './ownRing.stylex'; +import {watchHitArea, writeHitInsets} from '../utils/hitArea'; +import {useTranslator} from '../i18n/useTranslator'; +import {devWarn} from '../utils/devWarning'; +import {ItemLabelContext} from '../Item/ItemLabelContext'; +import {ListContext} from './ListContext'; +import { + HANDLE_ATTRIBUTE, + type ListReorderHandleProps, + type ListReorderRowNameProps, +} from './listReorderContext'; +import type {ListReorderController} from './listReorderEngine'; + +/** + * The handle's side, for every pointer: a small control's size. A finger's + * 44 px target is an invisible coarse-only hit layer, clamped so it never + * takes from a neighbour (utils/hitArea.ts), not a bigger handle. + */ +const HANDLE_SIZE = 28; +/** The three lines' height: the handle's share of its row's height. */ +const LINES_HEIGHT = 14; +/** The lines' length and thickness, and the distance between them. */ +const LINE_WIDTH = 20; +const LINE_THICKNESS = 2; +const LINE_GAP = (LINES_HEIGHT - LINE_THICKNESS) / 2; + +const styles = stylex.create({ + handle: { + // Centred on its row, with the lines in its middle. It takes only the + // lines' height in the row's layout (the negative block margins), so a + // compact row stays compact; the handle and its focus ring reach past + // that into the row's padding, never past it: no further than the row's + // own inline inset, so a flush row's handle stays inside the list's clip. + position: 'relative', + alignSelf: 'center', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + flexShrink: 0, + width: HANDLE_SIZE, + height: HANDLE_SIZE, + marginBlock: (LINES_HEIGHT - HANDLE_SIZE) / 2, + marginInlineEnd: 'calc(-1 * min(8px, var(--_item-inset-inline, 8px)))', + padding: 0, + borderWidth: 0, + borderRadius: 4, + // The ring sits inside the handle: the handle reaches the row's inline + // end, and the list clips what passes it. + outlineOffset: { + default: '0', + ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`, + }, + // Pressed while its row is in reorder mode, as a pressed toggle button + // is; in forced colors, the system's highlight. + backgroundColor: { + default: 'transparent', + ':is([aria-pressed="true"])': { + default: colorVars['--color-overlay-pressed'], + '@media (forced-colors: active)': 'Highlight', + }, + }, + forcedColorAdjust: { + default: null, + ':is([aria-pressed="true"])': 'none', + }, + color: { + default: colorVars['--color-icon-secondary'], + ':is([aria-disabled="true"])': colorVars['--color-icon-disabled'], + ':is([aria-pressed="true"])': { + default: colorVars['--color-icon-secondary'], + '@media (forced-colors: active)': 'HighlightText', + }, + }, + // Grabbing while its list reorders (a drag holds the pointer). Not + // `:active`: that is the touch press controller's arm, and the handle + // paints no press. + cursor: { + default: 'grab', + ':is([data-astryx-reordering] *)': 'grabbing', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + // Where the primary pointer is coarse: until the hold claims the drag, + // the page keeps its scrolling and its pinch-zoom (a flick on the handle + // scrolls, as on iOS): `manipulation`, what a long press leaves the + // browser (spec:AST-094 FR18). Where it is fine, no pan: a pen drags the + // row at once, as a mouse does (FR43), and a pen that sends only pointer + // events would otherwise pan the page and cancel the drag. No text + // selection under a held finger: the hold's selection lock holds it while + // the finger is down, so a mouse keeps the page's selection as it was. + touchAction: { + default: null, + '@media (pointer: coarse)': 'manipulation', + '@media (pointer: fine)': 'none', + }, + WebkitTapHighlightColor: { + default: null, + '@media (pointer: coarse)': 'transparent', + }, + // The three lines: one bar and its two shadows, in the handle's color. + // Forced colors keep them (shadows and backgrounds go there otherwise), + // drawn in the system's button text. + '::before': { + content: '""', + display: 'block', + width: LINE_WIDTH, + height: LINE_THICKNESS, + borderRadius: LINE_THICKNESS / 2, + backgroundColor: 'currentColor', + boxShadow: `0 -${LINE_GAP}px currentColor, 0 ${LINE_GAP}px currentColor`, + forcedColorAdjust: 'none', + pointerEvents: 'none', + }, + // The coarse-only hit layer: invisible, grown toward 44 px by the insets + // the hit area writes where the primary pointer is coarse (0 elsewhere), + // each side capped at half the gap to a neighbouring target. + '::after': { + content: '""', + position: 'absolute', + // SYNC: utils/hitArea.ts HIT_INSET_PROPERTIES (StyleX reads no + // imported value). + inset: + 'calc(var(--astryx-hit-inset-top, 0px) * -1) calc(var(--astryx-hit-inset-right, 0px) * -1) calc(var(--astryx-hit-inset-bottom, 0px) * -1) calc(var(--astryx-hit-inset-left, 0px) * -1)', + }, + }, + // The row's own child (a row without end content, spec:AST-103 FR5): it + // ends the row, as the end slot would, and aligns as the row's `align` + // would align that slot. + inRow: { + marginInlineStart: 'auto', + }, + // `start`: at the top of the row's content. + inRowStart: { + alignSelf: 'flex-start', + }, + // `first-line`: centred on the label's first line, a line of body text at + // the top of the row's content (the line Item's first-line slots centre + // on). Its layout height stays the lines' height (the end margin). + inRowFirstLine: { + alignSelf: 'flex-start', + marginBlockStart: `calc((${typeScaleVars['--text-body-leading']} - ${HANDLE_SIZE}px) / 2)`, + }, +}); + +/** + * The style of a row that ends with a handle (ListItem applies it): its ring + * on focus within stays off for the handle, which rings itself. + */ +export const reorderRowStyle = ownRingContainerStyles.focusWithin; + +/** The insertion line's thickness, px (the engine centres it on a gap). */ +export const INSERTION_LINE_THICKNESS = 2; + +const listStyles = stylex.create({ + // The insertion line (design:ordered-collection-reordering): the list's own + // pseudo-element, decoration with no semantic role, so no element joins the + // list (architecture:component-style-authoring INV7). The engine shows it + // with `data-astryx-reorder-line` on the list and places it with the list's + // custom properties: its top (`--astryx-reorder-line-y`, a compositor + // translate) and its inline start and size (the dragged row's). + list: { + '::after': { + content: '""', + display: { + default: 'none', + '[data-astryx-reorder-line]': 'block', + }, + position: 'absolute', + top: 0, + insetInlineStart: 'var(--astryx-reorder-line-start, 0px)', + inlineSize: 'var(--astryx-reorder-line-size, 0px)', + blockSize: INSERTION_LINE_THICKNESS, + borderRadius: INSERTION_LINE_THICKNESS / 2, + backgroundColor: { + default: colorVars['--color-accent'], + '@media (forced-colors: active)': 'Highlight', + }, + forcedColorAdjust: 'none', + translate: '0 var(--astryx-reorder-line-y, 0px)', + // Turned across the step between two slots in a slot layout. + rotate: 'var(--astryx-reorder-line-angle, 0deg)', + pointerEvents: 'none', + zIndex: 2, + }, + }, + // The same line as an element of its own, for a container of plain + // elements, which carries no List style (createReorderable's attach): its + // container's custom properties place it the same way. + lineElement: { + position: 'absolute', + top: 0, + insetInlineStart: 'var(--astryx-reorder-line-start, 0px)', + inlineSize: 'var(--astryx-reorder-line-size, 0px)', + blockSize: INSERTION_LINE_THICKNESS, + borderRadius: INSERTION_LINE_THICKNESS / 2, + backgroundColor: { + default: colorVars['--color-accent'], + '@media (forced-colors: active)': 'Highlight', + }, + forcedColorAdjust: 'none', + translate: '0 var(--astryx-reorder-line-y, 0px)', + rotate: 'var(--astryx-reorder-line-angle, 0deg)', + pointerEvents: 'none', + zIndex: 2, + }, +}); + +/** The style of a reorderable list (List applies it): its insertion line. */ +export const reorderListStyle = listStyles.list; + +/** The insertion line as an element (createReorderable's attach draws it). */ +export const reorderLineElementStyle = listStyles.lineElement; + +/** + * The text a label shows: its strings and numbers, through its elements' + * children, with runs of space collapsed. Empty when it shows none (an icon, + * an image). + */ +function textOf(node: ReactNode): string { + if (typeof node === 'string' || typeof node === 'number') { + return String(node); + } + if (Array.isArray(node)) { + return node.map(textOf).join(''); + } + if (isValidElement<{children?: ReactNode}>(node)) { + return textOf(node.props.children); + } + return ''; +} + +/** The text the row's label element shows, collapsed; empty without one. */ +function labelTextOf(handle: HTMLElement | null, labelID: string | null) { + const element = + labelID == null + ? null + : (handle?.ownerDocument.getElementById(labelID) ?? null); + return (element?.textContent ?? '').replace(/\s+/g, ' ').trim(); +} + +/** + * Whether the row's label element names it: it shows text, or holds an icon + * or image with an accessible name of its own. + */ +function namesRow(element: HTMLElement | null): boolean { + if (element == null) { + return false; + } + return ( + (element.textContent ?? '').trim() !== '' || + element.querySelector( + '[aria-label]:not([aria-label=""]), [aria-labelledby], img[alt]:not([alt=""])', + ) != null + ); +} + +/** + * The reorder handle of a List row. Renders nothing outside a reorderable + * List. + */ +export function ListReorderHandle({ + label, + itemKey, + isDisabled = false, + rowLabel, + rowLabelledBy, + rowAlign, +}: ListReorderHandleProps) { + const ref = useRef(null); + const t = useTranslator(); + const controller = use(ListContext)?.reorder?.session as + ListReorderController | undefined; + // The row's label element, when the handle sits in an Item's slot. + const labelID = use(ItemLabelContext); + const verbID = useId(); + const text = textOf(label).replace(/\s+/g, ' ').trim(); + // Named "Reorder" followed by the row's name (spec:AST-103 FR4): the name + // its caller gave the row; else the elements that name the row (its + // caller's `aria-labelledby`, or the label element Item renders), so a + // label of any shape names it; outside an Item, the label's text. A row + // that shows no name is named after its place. + const callerLabel = rowLabel?.trim() || null; + const labelledBy = + callerLabel != null ? undefined : (rowLabelledBy ?? labelID ?? undefined); + const named = callerLabel != null || labelledBy != null || text !== ''; + const verb = t('@astryx.list.reorderHandleVerb'); + const warnedNamelessRef = useRef(false); + // The session moves the row only with its handle recorded, reports its + // moves with the row's key, and announces them with its name: a component + // label's text is read from its element, rendered by now. + useIsomorphicLayoutEffect(() => { + const spoken = + callerLabel ?? + (text !== '' ? text : labelTextOf(ref.current, labelID ?? null)); + return controller?.registerHandle(ref.current, itemKey, spoken); + }, [controller, itemKey, callerLabel, text, labelID]); + // Pressed while its row is in reorder mode. + const isPressed = useSyncExternalStore( + controller?.subscribeMode ?? subscribeNothing, + () => controller?.isInMode(ref.current) ?? false, + () => false, + ); + const isEnabled = controller != null && !isDisabled; + // The row the handle sits in, read after each commit: the list's own ref is + // attached after its rows' layout effects run, and by the cleanup below the + // handle may already be out of the row. + const rowRef = useRef(null); + useEffect(() => { + rowRef.current = controller?.rowOf(ref.current) ?? null; + }); + // A finger's target: the hit area watches the handle where the primary + // pointer is coarse and writes how far its hit layer may grow. + useIsomorphicLayoutEffect(() => { + const handle = ref.current; + if (handle == null) { + return undefined; + } + return watchHitArea(handle, insets => writeHitInsets(handle, insets)); + }, []); + // A handle that stops taking gestures mid-drag (its row disabled or no + // longer reorderable, the handle gone) sends a drag of its row home, + // whichever pointer or key drives it. + useIsomorphicLayoutEffect(() => { + if (!isEnabled || controller == null) { + return undefined; + } + return () => controller.release(rowRef.current); + }, [controller, isEnabled]); + // That place is read from the DOM after each commit (the row does not + // know its index). A passive effect: the list's own ref is attached after + // its rows' layout effects run. + useEffect(() => { + const handle = ref.current; + if (handle == null) { + return; + } + // Named by Item's label element only while it shows a name: a label of + // an unnamed icon alone falls back to the place. + if (labelID != null && labelledBy === labelID) { + if (namesRow(handle.ownerDocument.getElementById(labelID))) { + handle.setAttribute('aria-labelledby', `${verbID} ${labelID}`); + handle.setAttribute('aria-label', verb); + return; + } + handle.removeAttribute('aria-labelledby'); + } else if (named) { + return; + } + const position = controller?.positionOf(handle) ?? null; + if (position == null) { + return; + } + // Named after its place only: a person hears "Reorder item 3" with + // nothing to tell the rows apart. Development says so, once a handle. + if (!warnedNamelessRef.current) { + warnedNamelessRef.current = true; + devWarn( + 'ListItem', + 'A reorderable row has no accessible name, so its reorder handle is ' + + 'named after its place ("Reorder item N"). Give the row a text ' + + 'label or an aria-label.', + ); + } + handle.setAttribute( + 'aria-label', + t('@astryx.list.reorderHandleAt', {position}), + ); + }); + if (controller == null) { + return null; + } + // Named through the label element: the handle's own `aria-label` is the + // verb, and it lists itself first in its `aria-labelledby`, which reads its + // `aria-label` there ("Reorder" then the row's label). + const name = + callerLabel != null + ? t('@astryx.list.reorderHandle', {label: callerLabel}) + : labelledBy != null + ? verb + : text !== '' + ? t('@astryx.list.reorderHandle', {label: text}) + : undefined; + return ( + + + {items.map(item => ( + + ))} + + + ); + } + + it("starts reorder mode from the app's own UI with start(key): the focus moves to the handle, and the arrows move the row", async () => { + const user = userEvent.setup(); + const onReorder = vi.fn(); + render( + , + ); + await user.click(screen.getByRole('button', {name: 'Move Sent'})); + const handle = handleOf('Sent'); + expect(handle).toHaveAttribute('aria-pressed', 'true'); + expect(handle).toHaveFocus(); + await user.keyboard('{ArrowDown}'); + expect(onReorder).toHaveBeenCalledWith({key: 'Sent', to: 2}); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Sent, position 3 of 3, after Drafts, at the end', + ), + ); + await user.keyboard('{Escape}'); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + expect(labels()).toEqual(['Inbox', 'Drafts', 'Sent']); + }); + + it('keeps the mode start(key) entered when the UI that started it hands its focus back, as a closing menu does', async () => { + const user = userEvent.setup(); + render( + , + ); + await user.click(screen.getByRole('button', {name: 'Move Sent'})); + const handle = handleOf('Sent'); + await waitFor(() => expect(handle).toHaveFocus()); + expect(handle).toHaveAttribute('aria-pressed', 'true'); + }); + + it.each([ + ['cannot move', 'Pinned'], + ['is not mounted', 'Spam'], + ])( + 'does nothing with start(key) for a key that %s, and warns in development', + async (_, key) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const user = userEvent.setup(); + const onReorder = vi.fn(); + render( + , + ); + await user.click(screen.getByRole('button', {name: `Move ${key}`})); + for (const label of ['Inbox', 'Sent']) { + expect(handleOf(label)).toHaveAttribute('aria-pressed', 'false'); + } + await user.keyboard('{ArrowDown}'); + expect(onReorder).not.toHaveBeenCalled(); + expect( + warn.mock.calls.some(([message]) => + String(message).includes(`start(${key})`), + ), + ).toBe(true); + warn.mockRestore(); + }, + ); + + it('starts reorder mode in the list mounted last when one object serves two, and warns in development', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const reorderable = createReorderable({onReorder: () => {}}); + render( + <> + + + + + + + , + ); + act(() => reorderable.start('same')); + expect(handleOf("Later's")).toHaveAttribute('aria-pressed', 'true'); + expect(handleOf("Today's")).toHaveAttribute('aria-pressed', 'false'); + expect( + warn.mock.calls.some(([message]) => + String(message).includes('more than one collection'), + ), + ).toBe(true); + warn.mockRestore(); + }); + + it('shows a hint with the moves and Done while a row is in reorder mode', async () => { + const user = userEvent.setup(); + render(); + expect(hintButton('Move down')).toBeNull(); + handleOf('Sent').focus(); + await user.keyboard(' '); + const down = hintButton('Move down') as HTMLElement; + expect(hintButton('Move up')).toBeInTheDocument(); + expect(hintButton('Done')).toBeInTheDocument(); + // In the anchored hint layer, outside the list; never a tab stop. + expect(down.closest('[popover]')).not.toBeNull(); + expect(down.closest('ul')).toBeNull(); + expect(down).toHaveAttribute('tabindex', '-1'); + await user.keyboard('{Escape}'); + expect(hintButton('Move down')).toBeNull(); + }); + + it("gives the hint's buttons a finger's target as an invisible hit layer: the hit area writes their insets where the primary pointer is coarse", async () => { + stubPrimaryPointer(true); + const user = userEvent.setup(); + render(); + handleOf('Sent').focus(); + await user.keyboard(' '); + for (const name of ['Move up', 'Move down', 'Done']) { + const button = hintButton(name) as HTMLElement; + await waitFor(() => + expect( + button.style.getPropertyValue('--astryx-hit-inset-top'), + name, + ).toMatch(/px$/), + ); + } + }); + + it("starts the hint buttons' hit area only where the primary pointer is coarse (spec:AST-094 FR24)", async () => { + const observed: Element[] = []; + class Recording { + observe(target: Element) { + observed.push(target); + } + unobserve() {} + disconnect() {} + takeRecords() { + return []; + } + } + vi.stubGlobal('IntersectionObserver', Recording); + vi.stubGlobal('ResizeObserver', Recording); + try { + const user = userEvent.setup(); + const hintButtons = () => + ['Move up', 'Move down', 'Done'].map( + name => hintButton(name) as HTMLElement, + ); + stubPrimaryPointer(false); + const fine = render( + , + ); + handleOf('Sent').focus(); + await user.keyboard(' '); + for (const button of hintButtons()) { + expect(observed).not.toContain(button); + } + fine.unmount(); + // The positive control: under a finger it watches them. + stubPrimaryPointer(true); + render(); + handleOf('Sent').focus(); + await user.keyboard(' '); + for (const button of hintButtons()) { + await waitFor(() => expect(observed).toContain(button)); + } + } finally { + vi.unstubAllGlobals(); + } + }); + + it('takes an Escape that reaches the dismissal stack with the focus in the hint: the mode ends, and a layer below stays open', async () => { + const user = userEvent.setup(); + const outer = vi.fn(); + // A layer the list sits in, such as a Dialog. + function OuterLayer({children}: {children: ReactNode}) { + useLayerDismissal({isActive: true, onDismiss: outer}); + return {children}; + } + render( + + + , + ); + handleOf('Sent').focus(); + await user.keyboard(' '); + expect(handleOf('Sent')).toHaveAttribute('aria-pressed', 'true'); + // A screen reader moved into the hint: its Escape goes past the handle, + // to the stack, whose top-most layer is the hint. + fireEvent.keyDown(hintButton('Move up') as HTMLElement, {key: 'Escape'}); + expect(handleOf('Sent')).toHaveAttribute('aria-pressed', 'false'); + expect(hintButton('Move up')).toBeNull(); + expect(outer).not.toHaveBeenCalled(); + // The next Escape is the layer below's. + fireEvent.keyDown(document, {key: 'Escape'}); + expect(outer).toHaveBeenCalledTimes(1); + }); + + it("reorders by taps alone: the handle, the hint's moves, then Done, the focus staying on the handle", async () => { + const user = userEvent.setup(); + const onReorder = vi.fn(); + render( + , + ); + const handle = handleOf('Inbox'); + await user.click(handle); + await user.click(hintButton('Move down') as HTMLElement); + expect(onReorder).toHaveBeenCalledTimes(1); + expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 1}); + expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']); + expect(handle).toHaveFocus(); + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Inbox, position 2 of 3, after Sent, before Drafts', + ), + ); + await user.click(hintButton('Move down') as HTMLElement); + expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 2}); + await user.click(hintButton('Move up') as HTMLElement); + expect(onReorder).toHaveBeenCalledTimes(3); + expect(onReorder).toHaveBeenLastCalledWith({key: 'Inbox', to: 1}); + expect(handle).toHaveFocus(); + expect(handle).toHaveAttribute('aria-pressed', 'true'); + await user.click(hintButton('Done') as HTMLElement); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + expect(hintButton('Done')).toBeNull(); + expect(handle).toHaveFocus(); + // Done ends the mode as Escape does, announcing where the row is. + await waitFor(() => + expect(document.body).toHaveTextContent('Done, Inbox at position 2 of 3'), + ); + // Kept: nothing undone. + expect(onReorder).toHaveBeenCalledTimes(3); + expect(labels()).toEqual(['Sent', 'Inbox', 'Drafts']); + }); + + it("refuses the hint's move into a row that keeps its place, as the key does", async () => { + const user = userEvent.setup(); + const onReorder = vi.fn(); + render( + , + ); + await user.click(handleOf('Inbox')); + await user.click(hintButton('Move up') as HTMLElement); + expect(onReorder).not.toHaveBeenCalled(); + await waitFor(() => + expect(document.body).toHaveTextContent("Can't move past Pinned"), + ); + }); + + it('shows the same hint when start(key) enters reorder mode', async () => { + const user = userEvent.setup(); + render( + , + ); + await user.click(screen.getByRole('button', {name: 'Move Drafts'})); + await user.click(hintButton('Move up') as HTMLElement); + expect(labels()).toEqual(['Inbox', 'Drafts', 'Sent']); + expect(handleOf('Drafts')).toHaveFocus(); + expect(handleOf('Drafts')).toHaveAttribute('aria-pressed', 'true'); + }); + + it("keeps the mouse drag slop equal to the date wheel's", () => { + expect(MOUSE_DRAG_SLOP).toBe(DRAG_SLOP); + }); + + it('drags with a mouse once it moves the slop, from where it pressed; a smaller move stays a click', async () => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + // Under the slop: a click, so nothing is picked up and nothing announced. + fireEvent.pointerDown(handle, {...MOUSE, clientY: 322}); + fireEvent.pointerMove(handle, { + ...MOUSE, + clientY: 322 + MOUSE_DRAG_SLOP - 1, + }); + expect(list).not.toHaveAttribute('data-astryx-reordering'); + fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + MOUSE_DRAG_SLOP - 1}); + expect(document.body).not.toHaveTextContent('Picked up'); + // That click turns reorder mode on, and another turns it off. + fireEvent.click(handle); + expect(handle).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(handle); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + // Past it the row follows from the press point: past both boundaries. + mouseDrag(handle, 322, 322 + 70); + expect(list).toHaveAttribute('data-astryx-reordering'); + await waitFor(() => + expect(document.body).toHaveTextContent('Picked up, position 1 of 3'), + ); + act(() => { + fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70}); + }); + expect(onReorder).toHaveBeenCalledTimes(1); + expect(onReorder).toHaveBeenCalledWith({key: 'A', to: 2}); + expect(labels()).toEqual(['B', 'C', 'A']); + // The drag's own click leaves reorder mode off. + fireEvent.click(handle); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + await waitFor(() => + expect(document.body).toHaveTextContent('Dropped, position 3 of 3'), + ); + }); + + it('keeps the other rows still during a drag: the source dims in place, a preview follows the pointer, and an insertion line marks the drop position (design:ordered-collection-reordering)', async () => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const [a, b, c] = Array.from(list.querySelectorAll('li')); + const restCount = a.querySelectorAll('*').length; + mouseDrag(handleOf('A'), 322, 322 + 70); + // The rows the drag passes stay where they are. + for (const row of [a, b, c]) { + expect(['', '0px 0px', 'none']).toContain(row.style.translate); + } + // The source stays in its place, dimmed. + expect(a).toHaveAttribute('data-astryx-reorder-source'); + // A preview of it follows the pointer, hidden from assistive technology. + const preview = list.querySelector( + '[data-astryx-reorder-preview]', + ); + expect(preview).not.toBeNull(); + expect(preview).toHaveAttribute('aria-hidden', 'true'); + expect(preview!.textContent).toBe(a.textContent); + // The same item, moving: the row's reduced emphasis, not raised (DR2). + expect(preview!.style.opacity).toBe(a.style.opacity); + expect(preview!.style.boxShadow).toBe('none'); + expect(preview!.style.translate).toBe('0px 70px'); + // The preview, the one transient copy, sits right before its source: its + // counter reads the source's number in a numbered list, the source counts + // nothing while it is picked up, and the last row keeps :last-child. + expect(preview!.nextElementSibling).toBe(a); + expect(a.style.counterIncrement).toBe('none'); + // The line sits after C, where A would land (position 2 of 0-2): the + // list's own pseudo-element, so the list holds the rows and the preview + // only (component-style-authoring INV7), and the picked-up row holds what + // it held at rest (spec:AST-103 FR5). + expect(list).toHaveAttribute('data-astryx-reorder-line'); + expect(list.style.getPropertyValue('--astryx-reorder-line-y')).toBe( + '131px', + ); + expect(list.children).toHaveLength(4); + expect(a.querySelectorAll('*')).toHaveLength(restCount); + // The drop rearranges the rows and takes the preview and line away. + act(() => { + fireEvent.pointerUp(handleOf('A'), {...MOUSE, clientY: 322 + 70}); + }); + expect(onReorder).toHaveBeenCalledWith({key: 'A', to: 2}); + expect(labels()).toEqual(['B', 'C', 'A']); + expect(list.querySelector('[data-astryx-reorder-preview]')).toBeNull(); + expect(list).not.toHaveAttribute('data-astryx-reorder-line'); + expect(list.children).toHaveLength(3); + expect(a.querySelectorAll('*')).toHaveLength(restCount); + expect(a).not.toHaveAttribute('data-astryx-reorder-source'); + expect(a.style.counterIncrement).toBe(''); + }); + + it('announces Done when a drag ends reorder mode, keeping its moves', async () => { + stubPrimaryPointer(false); + render(); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + fireEvent.click(handle); + expect(handle).toHaveAttribute('aria-pressed', 'true'); + mouseDrag(handle, 322, 322 + 70); + expect(handle).toHaveAttribute('aria-pressed', 'false'); + await waitFor(() => + expect(document.body).toHaveTextContent('Done, A at position 1 of 3'), + ); + act(() => { + fireEvent.pointerUp(handle, {...MOUSE, clientY: 322 + 70}); + }); + }); + + it('restores a cancelled drag at once: no preview, no line, the source undimmed, nothing moved', async () => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const a = list.querySelector('li')!; + mouseDrag(handleOf('A'), 322, 322 + 70); + expect(list.querySelector('[data-astryx-reorder-preview]')).not.toBeNull(); + act(() => { + fireEvent.pointerCancel(handleOf('A'), {...MOUSE, clientY: 322 + 70}); + }); + expect(list.querySelector('[data-astryx-reorder-preview]')).toBeNull(); + expect(list).not.toHaveAttribute('data-astryx-reorder-line'); + expect(a).not.toHaveAttribute('data-astryx-reorder-source'); + expect(a.style.counterIncrement).toBe(''); + expect(onReorder).not.toHaveBeenCalled(); + expect(labels()).toEqual(['A', 'B', 'C']); + }); + + it.each([ + ['its row is disabled', {isDisabled: ['A']}], + ['its row stops being reorderable', {fixed: ['A']}], + ['the list stops being reorderable', {isReorderable: false}], + ])( + 'sends a mouse drag home when %s mid-drag', + async ( + _, + change: { + isDisabled?: ReadonlyArray; + fixed?: ReadonlyArray; + isReorderable?: boolean; + }, + ) => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + const rows = ({ + isDisabled = NONE, + fixed = NONE, + isReorderable = true, + }: typeof change) => ( + !fixed.includes(key as string), + }) + : undefined + }> + {['A', 'B', 'C'].map(item => ( + + ))} + + ); + const {rerender} = render(rows({})); + const list = screen.getByRole('list'); + layOut(list); + mouseDrag(handleOf('A'), 322, 322 + 70); + expect(list).toHaveAttribute('data-astryx-reordering'); + rerender(rows(change)); + // No pointer reports this end: the session sends the row home. + await waitFor(() => + expect(document.body).toHaveTextContent( + 'Reorder cancelled, back to position 1 of 3', + ), + ); + expect(list).not.toHaveAttribute('data-astryx-reordering'); + fireEvent.pointerUp(list, {...MOUSE, clientY: 322 + 70}); + expect(onReorder).not.toHaveBeenCalled(); + expect(labels()).toEqual(['A', 'B', 'C']); + }, + ); + + it("plays a committed move's glide on the shared settle role, springs.settle (spec:AST-105 FR4)", async () => { + stubPrimaryPointer(true); + const glide = vi.spyOn(touchMotion, 'glideBase'); + const user = userEvent.setup(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + handle.focus(); + await user.keyboard(' {ArrowDown}'); + await waitFor(() => expect(glide).toHaveBeenCalled()); + expect(glide.mock.results[0]?.value).toEqual({duration: 0.5, bounce: 0}); + expect(motionRole('springs.settle')).toBeDefined(); + glide.mockRestore(); + }); + + it('sends a still-gliding row home on the shared settle role, keeping its velocity (spec:AST-094 FR4, FR6)', async () => { + stubPrimaryPointer(true); + const home = vi.spyOn(touchMotion, 'home'); + const user = userEvent.setup(); + render(); + const list = screen.getByRole('list'); + layOut(list); + // A key move commits, and its rows glide on springs.settle. + handleOf('A').focus(); + await user.keyboard(' {ArrowDown}{Escape}'); + await waitFor(() => expect(labels()).toEqual(['B', 'A', 'C'])); + layOut(list); + // Picked up again while it still glides, then cancelled: it goes home on + // the same role, from where it is shown, at the speed it has. + const handle = handleOf('A'); + mouseDrag(handle, 344, 344 + 30); + fireEvent.pointerCancel(handle, {...MOUSE, clientY: 344 + 30}); + const draggedRow = handle.closest('li'); + const calls = home.mock.calls.filter(([element]) => element === draggedRow); + expect(calls.length).toBeGreaterThan(0); + for (const [, spring, , fromRest] of calls) { + expect(spring).toEqual({duration: 0.5, bounce: 0}); + expect(fromRest).toBe(false); + } + home.mockRestore(); + }); + + it('puts its listeners on the list: none on a row or a handle', () => { + stubPrimaryPointer(true); + const add = vi.spyOn(EventTarget.prototype, 'addEventListener'); + render(); + const list = screen.getByRole('list'); + const targets = add.mock.contexts; + const rows = Array.from(list.children); + const handles = Array.from( + list.querySelectorAll('[data-astryx-list-reorder]'), + ); + expect(handles).toHaveLength(3); + expect( + targets.filter(target => handles.includes(target as Element)), + ).toEqual([]); + expect(targets.filter(target => rows.includes(target as Element))).toEqual( + [], + ); + expect( + add.mock.calls.filter( + (_, index) => targets[index] === list && _[0] === 'pointerdown', + ), + ).toHaveLength(1); + add.mockRestore(); + }); + + it('attaches one hold to the list for every pointer (spec:AST-094 FR43, FR19)', () => { + const attached = (coarse: boolean) => { + stubPrimaryPointer(coarse); + const host = getGestureHost(document); + const attach = vi.spyOn(host, 'attach'); + const {unmount} = render( + , + ); + const elements = attach.mock.calls.map(([element]) => element); + const list = screen.getByRole('list'); + unmount(); + attach.mockRestore(); + return {elements, list}; + }; + const coarse = attached(true); + expect(coarse.elements).toEqual([coarse.list]); + const fine = attached(false); + expect(fine.elements).toEqual([fine.list]); + }); + + it('listens for presses on the document only while the list is mounted', () => { + // A touch screen: the hold attaches where the primary pointer is coarse. + stubPrimaryPointer(true); + // A document of its own, so no earlier test has touched it, in a window + // whose primary pointer is the page's. + const frame = document.createElement('iframe'); + document.body.append(frame); + const doc = frame.contentDocument as Document; + Object.defineProperty(frame.contentWindow, 'matchMedia', { + configurable: true, + value: (query: string) => window.matchMedia(query), + }); + // The host takes a finger from pointer events where it can and from + // touch events where it must: either kind counts. + const isPress = (type: string) => + type.startsWith('touch') || type.startsWith('pointer'); + const added = vi.spyOn(doc, 'addEventListener'); + const removed = vi.spyOn(doc, 'removeEventListener'); + const mount = () => { + const container = doc.createElement('div'); + doc.body.append(container); + return render(, { + container, + baseElement: doc.body, + }); + }; + const first = mount(); + const second = mount(); + const listeners = added.mock.calls.filter(([type]) => isPress(type)); + expect(listeners.length).toBeGreaterThan(0); + first.unmount(); + second.unmount(); + // Every press listener the lists put on the document went with them. + for (const [type, listener, options] of listeners) { + expect( + removed.mock.calls.some( + ([removedType, removedListener]) => + removedType === type && removedListener === listener, + ), + `${type} ${JSON.stringify(options)}`, + ).toBe(true); + } + added.mockRestore(); + removed.mockRestore(); + frame.remove(); + }); + + it('with a fine primary pointer puts no touch listener on the page until a press', () => { + // spec:AST-094 FR43, FR24: the hold attaches, and the page listens only + // while a press on the list is down. + stubPrimaryPointer(false); + const doc = document.implementation.createHTMLDocument('fine'); + const added = vi.spyOn(doc, 'addEventListener'); + const container = doc.createElement('div'); + doc.body.append(container); + const {unmount} = render(, { + container, + baseElement: doc.body, + }); + expect( + added.mock.calls.filter(([type]) => type.startsWith('touch')), + ).toEqual([]); + unmount(); + added.mockRestore(); + }); + + it('a pen drags a handle at once where the primary pointer is fine, and holds where it is coarse (spec:AST-094 FR43)', () => { + const PEN = {...MOUSE, pointerType: 'pen'}; + const drag = (coarse: boolean) => { + stubPrimaryPointer(coarse); + const onReorder = vi.fn(); + const {unmount} = render( + , + ); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + fireEvent.pointerDown(handle, {...PEN, clientY: 322}); + fireEvent.pointerMove(handle, {...PEN, clientY: 322 + MOUSE_DRAG_SLOP}); + fireEvent.pointerMove(handle, {...PEN, clientY: 322 + 70}); + const picked = + list.querySelector('[data-astryx-reorder-preview]') != null; + act(() => { + fireEvent.pointerUp(handle, {...PEN, clientY: 322 + 70}); + }); + const moves = onReorder.mock.calls.length; + unmount(); + return {picked, moves}; + }; + // Fine: the handle allows a pen no pan, so it drags as a mouse does. + expect(drag(false)).toEqual({picked: true, moves: 1}); + // Coarse: the handle keeps the page's pan, so a pen holds first, as a + // finger does; one that moves at once picks nothing up. + expect(drag(true)).toEqual({picked: false, moves: 0}); + }); + + it('starts no drag from a press that is no primary click (spec:AST-094 FR43)', () => { + stubPrimaryPointer(false); + const onReorder = vi.fn(); + render(); + const list = screen.getByRole('list'); + layOut(list); + const handle = handleOf('A'); + // A right click, as a pen's barrel button arrives. + const SECONDARY = {...MOUSE, button: 2}; + fireEvent.pointerDown(handle, {...SECONDARY, clientY: 322}); + fireEvent.pointerMove(handle, {...SECONDARY, clientY: 322 + 70}); + expect(list.querySelector('[data-astryx-reorder-preview]')).toBeNull(); + fireEvent.pointerUp(handle, {...SECONDARY, clientY: 322 + 70}); + expect(onReorder).not.toHaveBeenCalled(); + }); + it('a hold on the handle opens no row menu, and a hold elsewhere on the row opens it (spec:AST-103)', () => { + vi.useFakeTimers(); + const show = vi.spyOn(HTMLElement.prototype, 'showPopover'); + try { + render( + + {}})}> + + + + , + ); + const handle = handleOf('Inbox'); + show.mockClear(); + // Held past the menu's long press: the handle's hold is the row's, not + // the menu's. + fireEvent.touchStart(handle, {touches: [{clientX: 300, clientY: 20}]}); + act(() => { + vi.advanceTimersByTime(800); + }); + fireEvent.touchEnd(handle, {touches: []}); + expect(show).not.toHaveBeenCalled(); + // A finger's long press on the handle sends the menu no context + // request either. + const request = new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + }); + Object.defineProperty(request, 'pointerType', {value: 'touch'}); + act(() => { + handle.dispatchEvent(request); + }); + expect(request.defaultPrevented).toBe(true); + expect(show).not.toHaveBeenCalled(); + // A hold on the row's label opens the row's menu. + const label = screen.getByText('Inbox'); + fireEvent.touchStart(label, {touches: [{clientX: 40, clientY: 20}]}); + act(() => { + vi.advanceTimersByTime(500); + }); + fireEvent.touchEnd(label, {touches: []}); + expect(show).toHaveBeenCalled(); + } finally { + show.mockRestore(); + vi.useRealTimers(); + } + }); + + it("keeps the handle's touch from a row menu without hiding it from the gesture host or capture listeners", () => { + // The handle stops its touchstart in React's bubble phase. The gesture + // host and its recognizers listen in the capture phase (on the document + // and on armed elements), so they still see every touch that starts on + // the handle, as does any capture-phase listener. + stubPrimaryPointer(true); + render( + + {}})}> + + + + , + ); + const handle = handleOf('Inbox'); + const captured = vi.fn(); + document.addEventListener('touchstart', captured, {capture: true}); + const host = getGestureHost(document); + try { + const touch = {identifier: 0, clientX: 300, clientY: 20, target: handle}; + fireEvent.touchStart(handle, {touches: [touch], changedTouches: [touch]}); + expect(captured).toHaveBeenCalledTimes(1); + expect(host.fingersDown()).toBe(1); + fireEvent.touchEnd(handle, {touches: [], changedTouches: [touch]}); + expect(host.fingersDown()).toBe(0); + } finally { + document.removeEventListener('touchstart', captured, {capture: true}); + } + }); + + it('does not activate an interactive row from its handle', async () => { + const user = userEvent.setup(); + const onClick = vi.fn(); + render( + {}})}> + + , + ); + await user.click(handleOf('Inbox')); + expect(onClick).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts new file mode 100644 index 0000000000000..8aeb492a00092 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts @@ -0,0 +1,604 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderMode.interaction.browser.spec.ts + * @input The built List "Reorderable" and "Reorder From Your UI" stories, + * with a mouse and in the touch phone context, and the interaction + * harness's touch driver + * @output Browser proofs of reorder mode and its hint (spec:AST-103 FR4, + * FR4a), in each engine: a mouse click on a handle turns the mode on and + * shows the hint's moves and Done, with the focus on the handle and no drop + * announced; Space or Enter turns it on, each arrow commits a move at once + * with the focus on the handle, and Escape ends it keeping the moves, + * announcing where the row is; an Escape with the focus in the hint ends + * the mode too, and the focus goes back to the handle; start(key) from a + * button or a context menu enters the same mode with the focus on the + * handle; under a finger, taps alone reorder (the handle, the moves, then + * Done), a drag leaves the mode off, and each of the hint's buttons is a + * 44 px target centered on what it shows, none covering its neighbour + * @position Interaction evidence for List/listReorderEngine.tsx (reorder + * mode and its hint) and List/ListReorderHandle.tsx + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + drag, + openStory, + tap, + touchDriver, + withStorybook, + type Point, +} from '@astryxdesign/interaction-harness'; +import {reorder} from '../../motion/uikit/reorder'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--reorderable'; +const START_STORY = 'core-list--reorder-from-your-ui'; +const ROWS = ['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam', 'Trash']; +const HOLD_MS = reorder.claim.delayMs + 80; + +/** + * The list's rows, without the reorder's insertion line and drag preview: + * inert, aria-hidden ghosts of the list (`data-astryx-leaving`). + */ +const ROW = '#storybook-root li:not([data-astryx-leaving])'; + +const row = (page: Page, label: string) => + page.locator(ROW).filter({hasText: label}).first(); + +const handle = (page: Page, label: string) => + page.getByRole('button', {name: `Reorder ${label}`, exact: true}); + +const labels = async (page: Page) => + page + .locator(ROW) + .evaluateAll(rows => rows.map(element => element.textContent ?? '')); + +const translateY = async (element: Locator) => + element.evaluate(el => { + const value = getComputedStyle(el).translate; + if (value === 'none' || value === '') { + return 0; + } + const [, y = '0px'] = value.split(' '); + return Number.parseFloat(y); + }); + +/** Everything the page's live regions say right now. */ +const announced = async (page: Page) => + page.evaluate(() => + Array.from(document.querySelectorAll('[aria-live], [role="status"]')) + .map(element => element.textContent ?? '') + .join(' '), + ); + +async function centerOf(element: Locator): Promise { + const box = await element.boundingBox(); + if (box == null) { + throw new Error('no box'); + } + return {x: box.x + box.width / 2, y: box.y + box.height / 2}; +} + +test.describe('with a mouse', () => { + test.use({ + hasTouch: false, + isMobile: false, + viewport: {width: 900, height: 700}, + }); + + /** This context's primary pointer is fine: a case here is a mouse's. */ + const expectFinePointer = async (page: Page) => + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + + /** + * The open anchored hint: its surface (the theme roles it wears), its + * anchoring (the layer's placement rules), and where it sits against the + * element it is anchored to (the element whose `anchor-name` its + * `position-anchor` names): the gap below it, and which of its edges the + * hint lines up with (`start`, or `end` where the start would leave the + * viewport). + */ + const openHint = async (page: Page) => + page.evaluate(() => { + const hint = Array.from( + document.querySelectorAll('[popover]'), + ).find(element => element.matches(':popover-open')); + if (hint == null) { + return null; + } + const name = getComputedStyle(hint) + .getPropertyValue('position-anchor') + .trim(); + const anchor = Array.from( + document.querySelectorAll('*'), + ).find(element => + element.style + .getPropertyValue('anchor-name') + .split(',') + .map(part => part.trim()) + .includes(name), + ); + if (anchor == null) { + return null; + } + const box = hint.getBoundingClientRect(); + const anchorBox = anchor.getBoundingClientRect(); + const style = getComputedStyle(hint); + return { + below: box.top - anchorBox.bottom, + edge: + Math.abs(box.left - anchorBox.left) < 0.5 + ? 'start' + : Math.abs(box.right - anchorBox.right) < 0.5 + ? 'end' + : 'none', + inView: box.left >= 0 && box.right <= window.innerWidth, + anchoring: { + positionArea: style.getPropertyValue('position-area'), + positionTryFallbacks: style.getPropertyValue( + 'position-try-fallbacks', + ), + marginBlockStart: style.marginBlockStart, + }, + surface: { + backgroundColor: style.backgroundColor, + borderRadius: style.borderRadius, + boxShadow: style.boxShadow, + color: style.color, + fontSize: style.fontSize, + lineHeight: style.lineHeight, + padding: style.padding, + position: style.position, + }, + }; + }); + + test("reorder mode's hint sits where Core's keyboard hint does and wears the same surface", async ({ + page, + }) => { + // Core's keyboard hint: a tab list reached with the keyboard. + await openStory(page, storybook(), 'core-tablist--default'); + await expectFinePointer(page); + await page.keyboard.press('Tab'); + await expect.poll(async () => openHint(page)).not.toBeNull(); + await page.waitForTimeout(300); + const keyboard = await openHint(page); + // Reorder mode's hint, below the handle whose row is in the mode. The + // list is narrowed so its handles, at the rows' end, are as far from the + // viewport's edge as the tab list is: each hint has the room to line up + // with its anchor's start, and the layer flips neither. + await openStory(page, storybook(), STORY); + await page.evaluate(() => { + const root = document.getElementById('storybook-root'); + if (root != null) { + root.style.width = '420px'; + } + }); + await handle(page, 'Inbox').focus(); + await page.keyboard.press('Space'); + await expect(page.getByRole('button', {name: 'Done'})).toBeVisible(); + await page.waitForTimeout(300); + const reorderHint = await openHint(page); + // The same layer, anchoring and theme roles (spec:AST-103, FR4 hint): the + // same surface, the same placement rules, the same gap below the anchor, + // and the same edge to line up with. + expect(reorderHint?.surface).toEqual(keyboard?.surface); + expect(reorderHint?.anchoring).toEqual(keyboard?.anchoring); + expect( + Math.abs((reorderHint?.below ?? Number.NaN) - (keyboard?.below ?? 0)), + ).toBeLessThan(0.5); + expect(keyboard?.edge).toBe('start'); + expect(reorderHint?.edge).toBe('start'); + expect(reorderHint?.inView).toBe(true); + await page.keyboard.press('Escape'); + }); + + test("a mouse click on a handle turns on reorder mode and shows its hint's moves and Done, and announces no drop", async ({ + page, + }) => { + await openStory(page, storybook(), STORY); + await expectFinePointer(page); + await handle(page, 'Inbox').click(); + await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true'); + for (const name of ['Move up', 'Move down', 'Done']) { + await expect(page.getByRole('button', {name})).toBeVisible(); + } + // A click's focus is the handle's, whatever the engine does with a + // clicked button. + await expect(handle(page, 'Inbox')).toBeFocused(); + // Nothing was picked up: the click announces no drop. + expect(await announced(page)).not.toContain('Dropped'); + }); + + for (const key of ['Space', 'Enter']) { + test(`${key} turns on reorder mode, each arrow commits a move at once with the focus on the handle, and Escape ends the mode keeping the moves`, async ({ + page, + }) => { + // spec:AST-103 FR4, in this engine: the key's own activation of the + // button (Space's comes with its keyup) toggles the mode once. + await openStory(page, storybook(), STORY); + await expectFinePointer(page); + await page.keyboard.press('Shift'); + await handle(page, 'Inbox').focus(); + await page.keyboard.press(key); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'true', + ); + await expect(page.getByRole('button', {name: 'Done'})).toBeVisible(); + await page.keyboard.press('ArrowDown'); + await expect + .poll(async () => labels(page)) + .toEqual(['Sent', 'Inbox', 'Drafts', 'Archive', 'Spam', 'Trash']); + await expect(handle(page, 'Inbox')).toBeFocused(); + await page.keyboard.press('ArrowDown'); + await expect + .poll(async () => labels(page)) + .toEqual(['Sent', 'Drafts', 'Inbox', 'Archive', 'Spam', 'Trash']); + await expect(handle(page, 'Inbox')).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + await expect(page.getByRole('button', {name: 'Done'})).toBeHidden(); + // Leaving announces where the row is. + await expect + .poll(async () => announced(page)) + .toContain('Done, Inbox at position 3 of 6'); + // Kept, and at rest: with a mouse nothing travels. + expect(await labels(page)).toEqual([ + 'Sent', + 'Drafts', + 'Inbox', + 'Archive', + 'Spam', + 'Trash', + ]); + await expect(handle(page, 'Inbox')).toBeFocused(); + for (const label of ROWS) { + expect(await translateY(row(page, label))).toBe(0); + } + }); + } + + test('an Escape with the focus in the hint ends reorder mode, and the focus goes back to the handle', async ({ + page, + }) => { + // A screen reader can move the focus into the hint's buttons; their + // Escape reaches the shared dismissal stack, not the handle. + await openStory(page, storybook(), STORY); + await expectFinePointer(page); + await handle(page, 'Sent').click(); + await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'true'); + const up = page.getByRole('button', {name: 'Move up'}); + await up.focus(); + await expect(up).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'false'); + await expect(up).toBeHidden(); + await expect(handle(page, 'Sent')).toBeFocused(); + expect(await labels(page)).toEqual(ROWS); + }); + + for (const from of ['a button', 'the context menu']) { + test(`start(key) from ${from} turns on reorder mode with the focus on the handle, and the arrows and the hint work`, async ({ + page, + }) => { + // spec:AST-103 FR4a: a closing menu restores its trigger's focus; the + // handle takes it back. + await openStory(page, storybook(), START_STORY); + await expectFinePointer(page); + if (from === 'a button') { + await page.getByRole('button', {name: 'Move Sent'}).click(); + } else { + await row(page, 'Drafts').click({button: 'right'}); + await page.getByRole('menuitem', {name: 'Move Sent'}).click(); + } + await expect(handle(page, 'Sent')).toHaveAttribute( + 'aria-pressed', + 'true', + ); + await expect(handle(page, 'Sent')).toBeFocused(); + await expect(page.getByRole('button', {name: 'Done'})).toBeVisible(); + await page.keyboard.press('ArrowDown'); + await expect + .poll(async () => labels(page)) + .toEqual(['Inbox', 'Drafts', 'Sent', 'Archive', 'Spam', 'Trash']); + await page.getByRole('button', {name: 'Move up'}).click(); + await expect.poll(async () => labels(page)).toEqual(ROWS); + await expect(handle(page, 'Sent')).toBeFocused(); + await page.keyboard.press('Escape'); + await expect(handle(page, 'Sent')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + }); + } +}); + +test.describe('with a finger', () => { + /** + * Opens the story on a touch screen: Chromium's touch emulation is a + * coarse pointer. + */ + async function open(page: Page) { + await openStory(page, storybook(), STORY); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the touch hint runs on a touch screen'); + await expect(handle(page, 'Inbox')).toBeVisible(); + } + + test("taps alone reorder: the handle turns on reorder mode, the hint's moves move the row, and Done ends the mode", async ({ + page, + browserName, + }) => { + // Linux WebKit's injected touches dispatch pointer and touch events but + // no click, so a tap cannot activate a button there (iOS Safari's tap + // does). + test.skip(browserName === 'webkit', 'injected touches synthesize no click'); + await open(page); + const before = await labels(page); + const driver = await touchDriver(page); + await driver.play(tap(await centerOf(handle(page, 'Inbox')))); + await expect(handle(page, 'Inbox')).toHaveAttribute('aria-pressed', 'true'); + const down = page.getByRole('button', {name: 'Move down'}); + await expect(down).toBeVisible(); + await driver.play(tap(await centerOf(down))); + await expect + .poll(async () => labels(page)) + .toEqual([before[1], before[0], ...before.slice(2)]); + // The focus stayed on the handle through the taps. + await expect(handle(page, 'Inbox')).toBeFocused(); + await driver.play( + tap(await centerOf(page.getByRole('button', {name: 'Done'}))), + ); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + await expect(down).toBeHidden(); + expect(await labels(page)).toEqual([ + before[1], + before[0], + ...before.slice(2), + ]); + }); + + test('a drag does not also turn on reorder mode', async ({page}) => { + await open(page); + const pitch = await row(page, 'Inbox').evaluate(element => { + const next = element.nextElementSibling as HTMLElement | null; + return next == null + ? (element as HTMLElement).offsetHeight + : next.offsetTop - (element as HTMLElement).offsetTop; + }); + const from = await centerOf(handle(page, 'Inbox')); + const driver = await touchDriver(page); + await driver.play( + drag( + from, + {x: from.x, y: from.y + 1.2 * pitch}, + {holdMs: HOLD_MS, durationMs: 300, restMs: 150}, + ), + ); + await page.waitForTimeout(400); + await expect(handle(page, 'Inbox')).toHaveAttribute( + 'aria-pressed', + 'false', + ); + await expect(page.getByRole('button', {name: 'Done'})).toBeHidden(); + }); + + test("each of the hint's buttons keeps its size, and its touch target grows toward 44 px without covering its neighbour", async ({ + page, + browser, + browserName, + }) => { + // No control grows for a finger: where the primary pointer is coarse a + // target reaches toward 44 px through an invisible hit layer, each side + // stopping at half the gap to a neighbouring target, so a tap always goes + // to the nearer one (Cindy's size rule; design:bidirectionality DR8). + await open(page); + await handle(page, 'Sent').focus(); + await page.keyboard.press('Enter'); + await expect(handle(page, 'Sent')).toHaveAttribute('aria-pressed', 'true'); + const names = ['Move up', 'Move down', 'Done']; + for (const name of names) { + await expect(page.getByRole('button', {name})).toBeVisible(); + } + // The hit layer's insets are written a frame after the hint shows. + await expect + .poll(async () => + page + .getByRole('button', {name: 'Move up'}) + .evaluate(element => + getComputedStyle(element) + .getPropertyValue('--astryx-hit-inset-top') + .trim(), + ), + ) + .not.toBe(''); + const targets = await page.evaluate( + list => + list.map(name => { + const element = Array.from(document.querySelectorAll('button')).find( + button => + button.getAttribute('aria-label') === name || + button.textContent?.trim() === name, + ); + if (element == null) { + throw new Error(`no ${name}`); + } + const style = getComputedStyle(element); + const inset = (side: string) => + parseFloat(style.getPropertyValue(`--astryx-hit-inset-${side}`)) || + 0; + const box = element.getBoundingClientRect(); + const glyph = ( + element.firstElementChild ?? element + ).getBoundingClientRect(); + // What the button adds around what it shows: its glyph's box, or + // its text's. + // A text's height is its line's, which the button's height holds. + const range = document.createRange(); + range.selectNodeContents(element); + const glyphBox = element.firstElementChild?.getBoundingClientRect(); + const lineHeight = parseFloat(getComputedStyle(element).lineHeight); + const content = glyphBox ?? { + width: range.getBoundingClientRect().width, + height: Number.isFinite(lineHeight) + ? lineHeight + : range.getBoundingClientRect().height, + }; + return { + name, + chrome: { + x: box.width - content.width, + y: box.height - content.height, + }, + box: { + left: box.left, + right: box.right, + top: box.top, + bottom: box.bottom, + }, + hit: { + left: box.left - inset('left'), + right: box.right + inset('right'), + top: box.top - inset('top'), + bottom: box.bottom + inset('bottom'), + }, + glyph: {left: glyph.left, right: glyph.right}, + }; + }), + names, + ); + // The same hint where the primary pointer is fine: each button adds the + // same space around what it shows, since no control grows for a finger + // (spec:AST-094 FR42); only the invisible hit layer reaches further. The + // theme's type scale may set larger text where the primary pointer is + // coarse, so the comparison leaves the text's own size out. + const fineContext = await browser.newContext({ + viewport: page.viewportSize() ?? {width: 390, height: 844}, + hasTouch: false, + isMobile: false, + }); + const fine = await fineContext.newPage(); + await openStory(fine, storybook(), STORY); + expect( + await fine.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await handle(fine, 'Sent').focus(); + await fine.keyboard.press('Enter'); + await expect(handle(fine, 'Sent')).toHaveAttribute('aria-pressed', 'true'); + const fineSizes = await fine.evaluate( + list => + list.map(name => { + const element = Array.from(document.querySelectorAll('button')).find( + button => + button.getAttribute('aria-label') === name || + button.textContent?.trim() === name, + ); + if (element == null) { + throw new Error(`no ${name}`); + } + const box = element.getBoundingClientRect(); + // A text's height is its line's, which the button's height holds. + const range = document.createRange(); + range.selectNodeContents(element); + const glyphBox = element.firstElementChild?.getBoundingClientRect(); + const lineHeight = parseFloat(getComputedStyle(element).lineHeight); + const content = glyphBox ?? { + width: range.getBoundingClientRect().width, + height: Number.isFinite(lineHeight) + ? lineHeight + : range.getBoundingClientRect().height, + }; + return { + x: box.width - content.width, + y: box.height - content.height, + }; + }), + names, + ); + await fineContext.close(); + for (const [index, {name, box, hit, chrome}] of targets.entries()) { + // Its own size around what it shows: the same as under a fine pointer. + expect( + Math.abs(chrome.x - fineSizes[index].x), + `${name} adds no width for a finger`, + ).toBeLessThanOrEqual(0.5); + expect( + Math.abs(chrome.y - fineSizes[index].y), + `${name} adds no height for a finger`, + ).toBeLessThanOrEqual(0.5); + // The hit layer only grows, and never past 44 px unless the button + // itself is larger. + const width = box.right - box.left; + const height = box.bottom - box.top; + expect( + hit.right - hit.left, + `${name} target width`, + ).toBeGreaterThanOrEqual(width); + expect(hit.bottom - hit.top).toBeGreaterThanOrEqual(height); + expect(hit.right - hit.left).toBeLessThanOrEqual( + Math.max(44, width) + 0.5, + ); + expect(hit.bottom - hit.top).toBeLessThanOrEqual( + Math.max(44, height) + 0.5, + ); + } + // Neighbouring targets meet at most halfway: none covers the next. + for (let index = 0; index + 1 < targets.length; index += 1) { + expect( + targets[index].hit.right, + `${targets[index].name} stops short of ${targets[index + 1].name}`, + ).toBeLessThanOrEqual(targets[index + 1].hit.left + 0.5); + } + // Every point of each glyph, and the edge of each target, hits its own + // button. + for (const {name, box, hit, glyph} of targets) { + const y = (box.top + box.bottom) / 2; + for (const x of [ + glyph.left + 1, + glyph.right - 1, + hit.left + 1, + hit.right - 1, + ]) { + const label = await page.evaluate( + ([px, py]) => { + const button = document.elementFromPoint(px, py)?.closest('button'); + return ( + button?.getAttribute('aria-label') ?? + button?.textContent?.trim() ?? + null + ); + }, + [x, y] as const, + ); + expect(label, `${name} at x=${x.toFixed(1)}`).toBe(name); + } + } + // A tap in Move up's target just past its visible edge, nearer it than + // Move down, moves the row up (a tap activates a button everywhere but + // Linux WebKit's injected touches). + if (browserName === 'webkit') { + return; + } + const [up] = targets; + const driver = await touchDriver(page); + await driver.play( + tap({x: up.hit.right - 1, y: (up.box.top + up.box.bottom) / 2}), + ); + await expect + .poll(async () => labels(page)) + .toEqual(['Sent', 'Inbox', 'Drafts', 'Archive', 'Spam', 'Trash']); + }); +}); diff --git a/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts new file mode 100644 index 0000000000000..0d70c81e106e8 --- /dev/null +++ b/packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts @@ -0,0 +1,448 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListReorderTouch.interaction.browser.spec.ts + * @input The built List reorder stories, real touch input (Chromium CDP / + * WebKit's input command) through the interaction harness, and the claim + * delay from the UIKit constants table (motion/uikit/reorder.ts) + * @output Interaction proofs for a reorderable List under a finger + * (spec:AST-103 verification): a hold on a handle then a drag moves the row + * and the drop settles it into its new place; while the finger holds the + * drag the rows stay still, the source dims, a preview follows and an + * insertion line marks the drop position; a flick on a handle scrolls + * and moves nothing; a cancelled drag puts the row back; with Reduce Motion + * the drop takes its place without travel; and a flush row's handle stays + * inside the list + * @position Interaction evidence for List's reorder (List/listReorderEngine.tsx, + * List/ListReorderTouch.ts, List/ListReorderHandle.tsx) in the touch phone + * context (./touchStory.ts) + */ + +import {expect, test, type CDPSession, type Page} from '@playwright/test'; +import { + flick, + holdThenDrag, + toTouchEvents, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; +import {solveSpring, toSpring} from '../../motion/spring'; +import {reorder} from '../../motion/uikit/reorder'; +import {springs} from '../../motion/uikit/springs'; +import {openStory} from './touchStory'; + +const storybook = withStorybook(test); + +/** Past the claim delay: the hold claims the drag. */ +const HOLD_MS = reorder.claim.delayMs + 150; +/** + * Long enough for a drop's glide to settle: it plays the shared settle role, + * springs.settle (spec:AST-105 FR4). + */ +const SETTLE_MS = + solveSpring(toSpring(springs.settle), {from: 0, to: 1}).settleTime(0.001) * + 1000 + + 300; + +const isTouch = async (page: Page) => + page.evaluate(() => matchMedia('(pointer: coarse)').matches); + +/** The story's row labels, in order. */ +async function labels(page: Page): Promise { + return page + .locator('#storybook-root li:not([data-astryx-leaving])') + .evaluateAll(rows => rows.map(row => row.textContent?.trim() ?? '')); +} + +/** The centre of `label`'s handle and the height of its row. */ +async function handleOf(page: Page, label: string) { + const handle = page.getByRole('button', {name: `Reorder ${label}`}); + await expect(handle).toBeVisible(); + const box = await handle.boundingBox(); + const row = await handle + .locator('xpath=ancestor::li[1]') + .evaluate(element => element.getBoundingClientRect().height); + if (box == null) { + throw new Error(`no handle for ${label}`); + } + return { + at: {x: box.x + box.width / 2, y: box.y + box.height / 2}, + rowHeight: row, + }; +} + +/** + * A hold on `at` then a drag to `to`, all but the lift, sent through + * Chromium's CDP on the script's own clock: the harness's player takes only + * scripts that end with every finger lifted. Resolves when the lift would + * have come, with the session that ends the touch. + */ +async function holdAndDragWithoutLift( + page: Page, + at: {x: number; y: number}, + to: {x: number; y: number}, +): Promise { + const events = toTouchEvents( + holdThenDrag(at, to, {holdMs: HOLD_MS, durationMs: 400, restMs: 120}), + ); + const lift = events[events.length - 1]; + const cdp = await page.context().newCDPSession(page); + let now = 0; + for (const step of events.slice(0, -1)) { + await page.waitForTimeout(step.t - now); + now = step.t; + await cdp.send('Input.dispatchTouchEvent', { + type: step.type, + touchPoints: step.fingers.map(f => ({ + x: f.x, + y: f.y, + id: f.id, + radiusX: 1, + radiusY: 1, + force: 1, + })), + }); + } + await page.waitForTimeout(lift.t - now); + return cdp; +} + +/** The layout top of each row, by label, once nothing animates. */ +async function settledTops(page: Page): Promise> { + return page + .locator('#storybook-root li:not([data-astryx-leaving])') + .evaluateAll(rows => { + const tops: Record = {}; + for (const row of rows) { + tops[row.textContent?.trim() ?? ''] = Math.round( + row.getBoundingClientRect().top, + ); + } + return tops; + }); +} + +test.describe('under a finger', () => { + test.beforeEach(async ({page}) => { + await openStory(page, storybook(), 'core-list--reorderable'); + test.skip( + !(await isTouch(page)), + 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)', + ); + }); + + test('a hold on a handle then a drag moves the row, and the drop settles it into its new place', async ({ + page, + }) => { + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const driver = await touchDriver(page); + await driver.play( + holdThenDrag( + at, + {x: at.x, y: at.y + rowHeight * 2}, + {holdMs: HOLD_MS, durationMs: 400, restMs: 120}, + ), + ); + await page.waitForTimeout(SETTLE_MS); + expect(await labels(page)).toEqual([ + 'Sent', + 'Drafts', + 'Inbox', + 'Archive', + 'Spam', + 'Trash', + ]); + // Settled: the dropped row sits in the third place, nothing moving. + const after = await settledTops(page); + expect(after.Inbox).toBe(before.Drafts); + expect( + await page + .locator('#storybook-root li') + .evaluateAll(rows => + rows.some(row => + row + .getAnimations({subtree: true}) + .some(animation => animation.playState === 'running'), + ), + ), + ).toBe(false); + }); + + test('while the finger holds a drag, the rows stay still: the source dims in place, a preview follows, and an insertion line marks the drop position', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the held finger lifts through Chromium CDP', + ); + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const cdp = await holdAndDragWithoutLift(page, at, { + x: at.x, + y: at.y + rowHeight * 2, + }); + expect(await settledTops(page)).toEqual(before); + const state = await page.evaluate(() => { + const source = document.querySelector( + '[data-astryx-reorder-source]', + ); + const preview = document.querySelector( + '[data-astryx-reorder-preview]', + ); + // The insertion line is the list's own ::after (no element joins the + // list), placed by a translate from the list's padding box. + const list = document.querySelector('#storybook-root ul'); + const line = list == null ? null : getComputedStyle(list, '::after'); + const lineY = + line == null ? Number.NaN : parseFloat(line.translate.split(' ')[1]); + return { + sourceOpacity: source == null ? null : getComputedStyle(source).opacity, + previewTop: preview?.getBoundingClientRect().top ?? null, + lineShown: line != null && line.display !== 'none', + lineTop: + list == null + ? null + : list.getBoundingClientRect().top + list.clientTop + lineY, + }; + }); + expect(Number(state.sourceOpacity)).toBeLessThan(1); + expect(state.previewTop).toBeGreaterThan(before.Inbox + rowHeight); + expect(state.lineShown).toBe(true); + // In the gap after Drafts, where Inbox would land. + expect( + Math.abs((state.lineTop ?? Number.NaN) - (before.Drafts + rowHeight)), + ).toBeLessThan(4); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + }); + await page.waitForTimeout(SETTLE_MS); + expect(await labels(page)).toEqual([ + 'Sent', + 'Drafts', + 'Inbox', + 'Archive', + 'Spam', + 'Trash', + ]); + expect( + await page.evaluate( + () => + document.querySelector( + '[data-astryx-reorder-preview], [data-astryx-reorder-line]', + ) == null, + ), + ).toBe(true); + }); + + test('a cancelled drag puts the row back and moves nothing', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'the cancel is a touchcancel through Chromium CDP', + ); + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + // The cancel comes when the lift would have. + const cdp = await holdAndDragWithoutLift(page, at, { + x: at.x, + y: at.y + rowHeight * 2, + }); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchCancel', + touchPoints: [], + }); + await page.waitForTimeout(SETTLE_MS); + expect(await labels(page)).toEqual([ + 'Inbox', + 'Sent', + 'Drafts', + 'Archive', + 'Spam', + 'Trash', + ]); + expect((await settledTops(page)).Inbox).toBe(before.Inbox); + }); + + test('with Reduce Motion the drop takes its place without travel', async ({ + page, + }) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + const before = await settledTops(page); + const {at, rowHeight} = await handleOf(page, 'Inbox'); + const driver = await touchDriver(page); + await driver.play( + holdThenDrag( + at, + {x: at.x, y: at.y + rowHeight * 2}, + {holdMs: HOLD_MS, durationMs: 400, restMs: 120}, + ), + ); + // Two frames after the lift: already in place, nothing travelling. + await page.evaluate( + async () => + new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + expect(await labels(page)).toEqual([ + 'Sent', + 'Drafts', + 'Inbox', + 'Archive', + 'Spam', + 'Trash', + ]); + expect((await settledTops(page)).Inbox).toBe(before.Drafts); + // Nothing travels. A running animation may only fade: the rows the drop + // passed take Reduce Motion's opacity dip in their new places + // (design:reduced-motion), and none moves. + expect( + await page + .locator('#storybook-root li') + .evaluateAll(rows => + rows.some(row => + row + .getAnimations({subtree: true}) + .some( + animation => + animation.playState === 'running' && + animation.effect instanceof KeyframeEffect && + animation.effect + .getKeyframes() + .some(frame => + ['translate', 'transform', 'top', 'insetBlockStart'].some( + property => frame[property] != null, + ), + ), + ), + ), + ), + ).toBe(false); + }); +}); + +test.describe('a row that reorders and has a menu', () => { + test.beforeEach(async ({page, browserName}) => { + await openStory(page, storybook(), 'core-list--reorder-from-your-ui'); + test.skip( + !(await isTouch(page)), + 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)', + ); + test.skip( + browserName !== 'chromium', + 'the held finger lifts through Chromium CDP', + ); + }); + + /** A finger held still at `at` for `ms`, read while it is down, then lifted. */ + async function holdStill( + page: Page, + at: {x: number; y: number}, + ms: number, + ): Promise<{picked: boolean; menu: boolean}> { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [ + {x: at.x, y: at.y, id: 0, radiusX: 1, radiusY: 1, force: 1}, + ], + }); + await page.waitForTimeout(ms); + const held = await page.evaluate(() => ({ + picked: document.querySelector('[data-astryx-reorder-preview]') != null, + menu: Array.from(document.querySelectorAll('[role="menu"]')).some( + element => element.getBoundingClientRect().height > 0, + ), + })); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchEnd', + touchPoints: [], + }); + return held; + } + + const menuShown = async (page: Page) => + page.evaluate(() => + Array.from(document.querySelectorAll('[role="menu"]')).some( + element => element.getBoundingClientRect().height > 0, + ), + ); + + test('a hold on the reorder handle picks the row up and opens no menu', async ({ + page, + }) => { + const order = await labels(page); + const {at} = await handleOf(page, 'Inbox'); + // Held still past the row menu's long press (500 ms). + const held = await holdStill(page, at, 800); + expect(held.picked).toBe(true); + expect(held.menu).toBe(false); + await page.waitForTimeout(SETTLE_MS); + expect(await menuShown(page)).toBe(false); + expect(await labels(page)).toEqual(order); + }); + + test('a hold anywhere else on the row opens its menu and picks nothing up', async ({ + page, + }) => { + const row = page + .locator('#storybook-root li:not([data-astryx-leaving])') + .filter({hasText: 'Inbox'}) + .first(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const held = await holdStill( + page, + {x: box.x + 40, y: box.y + box.height / 2}, + 800, + ); + expect(held.picked).toBe(false); + expect(held.menu).toBe(true); + await page.keyboard.press('Escape'); + }); +}); + +test('a flick on a handle scrolls the page and moves nothing', async ({ + page, +}) => { + await openStory(page, storybook(), 'core-list--reorder-long-list'); + test.skip( + !(await isTouch(page)), + 'this engine reports a fine primary pointer; the touch hold applies under (pointer: coarse)', + ); + const order = await labels(page); + const {at} = await handleOf(page, 'Item 8'); + const driver = await touchDriver(page); + test.skip( + !driver.drivesNativeGestures, + "this engine's injected touches drive no native scroll (the harness's drivesNativeGestures)", + ); + const scrolled = await page.evaluate(() => window.scrollY); + await driver.play(flick(at, {velocity: {x: 0, y: -1500}})); + await page.waitForTimeout(SETTLE_MS); + expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(scrolled); + expect(await labels(page)).toEqual(order); +}); + +test('a flush row keeps its handle inside the list', async ({page}) => { + await openStory(page, storybook(), 'core-list--reorder-flush'); + const handle = page.getByRole('button', {name: 'Reorder Inbox'}); + await expect(handle).toBeVisible(); + const [handleBox, listBox] = await Promise.all([ + handle.boundingBox(), + page.locator('#storybook-root ul').first().boundingBox(), + ]); + if (handleBox == null || listBox == null) { + throw new Error('no handle or list'); + } + expect(handleBox.x + handleBox.width).toBeLessThanOrEqual( + listBox.x + listBox.width + 0.5, + ); +}); diff --git a/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts new file mode 100644 index 0000000000000..60101b2a5c5ed --- /dev/null +++ b/packages/core/src/List/__tests__/ListRowPress.interaction.browser.spec.ts @@ -0,0 +1,475 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListRowPress.interaction.browser.spec.ts + * @input The built List, TreeList and press feedback stories, real touch input + * (Chromium CDP / WebKit's input command), the interaction harness, and the + * cell release clock and curve from the UIKit constants table + * (motion/uikit/list.ts) + * @output Interaction and animation proofs for a list row's touch press + * release: a held row paints the pressed token at full strength, and the + * release follows the cell release curve sampled frame by frame (both + * engines); the release keeps fading on every frame while the main thread + * is blocked (Chromium screencast, WebKit video); the release does no + * Layout or Paint; storyboards of the release and of the blocked window + * @position Interaction evidence for the row press layer (utils/interactionOverlay.stylex.ts `cell`) as composed + * by Item (List rows) and TreeList rows + * + * The press strength is read from pixels: the row's own background before + * the press is strength 0, the frame the press is believed is strength 1, and + * every other frame is placed between the two. The pressed overlay is a + * translucent token, so the sampled channel moves linearly with the layer's + * opacity. + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + animationStoryboard, + blockMainThread, + castStoryboard, + compareCurve, + countBetween, + cubicBezier, + freezeTimers, + holdAnimations, + installLongTaskLog, + installTimerGate, + openStory, + readLongTasks, + releaseAnimations, + seekAnimations, + startScreencast, + tap, + thawTimers, + timeline, + touchDriver, + traceRendering, + waitForAnimation, + withStorybook, + writeEvidence, + type TouchDriver, +} from '@astryxdesign/interaction-harness'; +import {list} from '../../motion/uikit/list'; +import { + blockBehindBeaconOn, + installBeacon, + samplePixel, + sampleVideo, +} from './rowPixels'; + +const storybook = withStorybook(test); + +const RELEASE_MS = list.highlight.releaseMs; +const releaseEase = cubicBezier(...list.highlight.releaseCurve); +/** The layer's opacity t ms into the release: the strength, 1 → 0. */ +const expectedStrength = (t: number) => + 1 - releaseEase(Math.min(1, Math.max(0, t / RELEASE_MS))); + +/** Long enough that the press is believed (scroll.delaysContentTouchesMs). */ +const HOLD_MS = 400; + +interface RowStory { + readonly name: string; + readonly story: string; + /** The pressable row under test. */ + readonly row: (page: Page) => Locator; +} + +const LIST_ROW: RowStory = { + name: 'List row', + story: 'core-list--interactive', + // "Sent": not the selected row, so its resting background is the page's. + row: page => + page.locator('[data-astryx-pressable]').filter({hasText: 'Sent'}).first(), +}; + +const SCROLLER_ROW: RowStory = { + name: 'Item row in a scroller', + story: 'core-press-feedback-touch--rows', + row: page => + page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Conversation 2'}) + .first(), +}; + +const TREE_ROW: RowStory = { + name: 'TreeList row', + story: 'core-treelist--basic', + row: page => + page + .locator('[data-astryx-pressable]') + .filter({hasText: 'App.tsx'}) + .first(), +}; + +interface OpenRow { + driver: TouchDriver; + row: Locator; + /** + * A point inside the row's trailing padding, clear of its text, icons and + * (in a tree) the guide lines, CSS px. + */ + probe: {x: number; y: number}; + center: {x: number; y: number}; +} + +async function openRow(page: Page, story: RowStory): Promise { + await installLongTaskLog(page); + await openStory(page, storybook(), story.story); + const driver = await touchDriver(page); + const row = story.row(page); + await expect(row).toBeVisible(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error(`${story.name}: no row`); + } + return { + driver, + row, + probe: { + x: Math.round(box.x + box.width - 3), + y: Math.round(box.y + box.height / 2), + }, + center: {x: box.x + box.width / 2, y: box.y + box.height / 2}, + }; +} + +/** Opacity of the row's press layer (the `::before`), as the engine presents it. */ +/** The press layer's strength: 0 while the row has no layer box (at rest). */ +const layerOpacity = async (row: Locator) => + row.evaluate(el => { + const before = getComputedStyle(el, '::before'); + return before.content === 'none' || before.content === 'normal' + ? 0 + : Number(before.opacity); + }); + +/** The press attribute the controller writes on the row. */ +const pressState = async (row: Locator) => + row.evaluate(el => el.getAttribute('data-astryx-press')); + +test('a held row paints the pressed token and its release follows the cell release curve, sampled frame by frame', async ({ + page, +}, testInfo) => { + const {driver, row, center} = await openRow(page, LIST_ROW); + expect(await layerOpacity(row)).toBe(0); + // Gate the page's timers before the press, so the controller's own release + // timer (which removes the attribute after the clock) can be held while the + // release is seeked. + await installTimerGate(page); + await driver.play(tap(center, {holdMs: HOLD_MS})); + expect(await pressState(row)).toBe('fading'); + await freezeTimers(page); + const held = await holdAnimations(page, row); + const release = held.find( + a => a.target?.startsWith('li') && a.kind === 'CSSAnimation', + ); + expect(release, JSON.stringify(held)).toBeDefined(); + expect(release?.durationMs).toBe(RELEASE_MS); + const samples: {t: number; value: number}[] = []; + for (const t of timeline(RELEASE_MS)) { + await seekAnimations(page, t); + samples.push({t, value: await layerOpacity(row)}); + } + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + const comparison = compareCurve(samples, expectedStrength, 0.005); + await writeEvidence( + 'curves/list-row-press-release', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + releaseMs: RELEASE_MS, + curve: list.highlight.releaseCurve, + held, + samples, + comparison, + }, + null, + 2, + ), + }, + testInfo, + ); + expect(samples[0].value).toBeCloseTo(1, 2); + expect( + comparison.maxError, + JSON.stringify(comparison.worst), + ).toBeLessThanOrEqual(0.005); + // At rest after the release: no press, no layer. + await expect.poll(async () => pressState(row)).toBeNull(); + expect(await layerOpacity(row)).toBe(0); +}); + +for (const story of [LIST_ROW, SCROLLER_ROW, TREE_ROW]) { + test(`${story.name}: the release keeps fading on 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 has its own video proof below', + ); + const {driver, row, center, probe} = await openRow(page, story); + const cast = await startScreencast(page); + // Strength 0 is the row at rest; strength 1 the believed press. + await driver.play(tap(center, {holdMs: HOLD_MS})); + const [release] = await waitForAnimation(row, {minProgressMs: 16}); + const block = await blockMainThread(page, 700); + await page.waitForTimeout(150); + const frames = await cast.stop(); + const pixels = await samplePixel(page, frames, probe); + const rest = pixels[0].value; + const pressedFrames = pixels.filter(p => p.t < release.from); + const pressed = Math.min(...pressedFrames.map(p => p.value)); + const strength = (v: number) => (rest - v) / (rest - pressed); + // Judge the release while it was still visibly moving inside the block. + const end = Math.min(block.to, release.to) - 10; + const during = pixels.filter(p => p.t > block.from && p.t <= end); + const strengths = during.map(p => ({ + t: +(p.t - block.from).toFixed(1), + strength: +strength(p.value).toFixed(3), + })); + const intervals = during + .map((p, i) => (i === 0 ? p.t - block.from : p.t - during[i - 1].t)) + .filter(dt => dt > 0); + const longestGap = Math.max( + end - (during.at(-1)?.t ?? block.from), + ...intervals, + ); + await writeEvidence( + `busy-main-thread/${story.story}`, + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {block, release, rest, pressed, strengths}, + null, + 1, + ), + }, + testInfo, + ); + const film = await castStoryboard(page, frames, { + name: `${story.story}-release-busy-main-thread`, + zero: block.from, + from: release.from - 40, + to: release.to + 40, + columns: 6, + cellScale: 0.45, + data: t => { + const p = pixels.find(f => f.t === t); + return {strength: p == null ? -1 : +strength(p.value).toFixed(3)}; + }, + }); + await film.write(testInfo, {block, release}); + // The press painted at full strength before the lift. + expect(rest - pressed).toBeGreaterThan(10); + // Frames kept coming through the block, each one further along the fade. + expect(during.length, JSON.stringify(strengths)).toBeGreaterThanOrEqual( + Math.floor((end - block.from) / (1000 / 60)) - 2, + ); + expect(longestGap).toBeLessThan(40); + for (let i = 1; i < strengths.length; i++) { + expect(strengths[i].strength).toBeLessThanOrEqual( + strengths[i - 1].strength + 0.01, + ); + } + const last = strengths.at(-1); + expect(last).toBeDefined(); + expect(strengths[0].strength).toBeGreaterThan((last?.strength ?? 1) + 0.2); + }); +} + +test('a busy first frame after the lift delays the release instead of skipping into it', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'WebKit starts an animation created just before a block at its last frame time (motion/animator.ts, known limits)', + ); + const {driver, row, center} = await openRow(page, LIST_ROW); + // When the press controller writes the release, 150 ms of script hold the + // main thread before the first frame. The release starts when the browser + // styles it, so the first frame due after the block shows it at most one + // frame in. + await row.evaluate(el => { + (window as unknown as {__first: Promise}).__first = new Promise( + resolve => { + const observer = new MutationObserver(() => { + if (el.getAttribute('data-astryx-press') !== 'fading') { + return; + } + observer.disconnect(); + const until = performance.now() + 150; + while (performance.now() < until) { + // Busy: the main thread is held. + } + // The first frame due after the block: a frame scheduled before + // it runs with that earlier time. + const read = () => { + if ((document.timeline.currentTime as number) < until) { + requestAnimationFrame(read); + return; + } + resolve(Number(getComputedStyle(el, '::before').opacity)); + }; + requestAnimationFrame(read); + }); + observer.observe(el, {attributeFilter: ['data-astryx-press']}); + }, + ); + }); + await driver.play(tap(center, {holdMs: 300})); + const first = await page.evaluate( + async () => (window as unknown as {__first: Promise}).__first, + ); + // At most one frame into the release: its ease-out curve takes the first + // frame to about 0.74; a start pinned before the block would be past 0.4. + expect(first).toBeGreaterThan(0.7); + await expect.poll(async () => layerOpacity(row)).toBe(0); +}); + +test('the release does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + const {driver, row, center} = await openRow(page, LIST_ROW); + let release = {from: 0, to: 0}; + const started = Date.now(); + const trace = await traceRendering(page, async () => { + await driver.play(tap(center, {holdMs: HOLD_MS})); + [release] = await waitForAnimation(row); + await page.waitForTimeout(RELEASE_MS + 100); + }); + // The steady part of the release: its first and last frames may commit. + const during = countBetween(trace, release.from + 30, release.to - 30); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); + expect(await readLongTasks(page, {from: started, to: Date.now()})).toEqual( + [], + ); +}); + +test('WebKit: the release keeps fading while the main thread is blocked (video)', async ({ + browser, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'webkit', + 'the Chromium screencast test covers Chromium', + ); + const size = {width: 402, height: 714}; + const context = await browser.newContext({ + viewport: size, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + recordVideo: {dir: testInfo.outputPath('video'), size}, + }); + const page = await context.newPage(); + const {driver, center, probe} = await openRow(page, LIST_ROW); + await installBeacon(page); + await blockBehindBeaconOn(page, 'touchend', 700); + await page.waitForTimeout(300); + await driver.play(tap(center, {holdMs: HOLD_MS})); + await page.waitForTimeout(1300); + const video = page.video(); + await context.close(); + const path = await video?.path(); + expect(path).toBeTruthy(); + const samples = await sampleVideo(path as string, probe, size); + const blocked = samples.filter(s => s.beacon === 'blocked'); + const rest = Math.max( + ...samples.filter(s => s.beacon === 'before').map(s => s.value), + ); + // Judge the release up to the frame it reaches the row's resting color. + // (Measured in the Linux WebKit build: once an accelerated animation has + // finished while script is still blocked, the compositor shows the value + // the main thread last committed until script runs again. That is this + // build's end-of-animation hand-back, after the release; iOS Safari 26.2 + // holds the resting color on the simulator. It is recorded below, not + // judged here.) + const restIndex = blocked.findIndex(s => s.value >= rest - 1); + const fading = restIndex === -1 ? blocked : blocked.slice(0, restIndex + 1); + const distinct = fading + .map(s => Math.round(s.value)) + .filter((v, i, all) => i === 0 || v !== all[i - 1]); + const afterEnd = restIndex === -1 ? [] : blocked.slice(restIndex + 1); + await writeEvidence( + 'busy-main-thread/list-row-release-webkit', + { + 'webkit.json': JSON.stringify( + {rest, blocked, distinct, afterEnd}, + null, + 1, + ), + }, + testInfo, + ); + testInfo.annotations.push({ + type: 'WebKit frames during the block', + description: `release: ${distinct.join(' ')}; after it ended, still blocked: ${[ + ...new Set(afterEnd.map(s => Math.round(s.value))), + ].join(' ')}`, + }); + expect(blocked.length).toBeGreaterThan(0); + // The row kept getting lighter while script could not run, all the way + // to its resting color: from a frame still short of rest, it reached rest + // inside the blocked window. A release on the main thread would hold its + // first frame's value until the block ends, 700 ms on, and could not. (The + // recording's frames are 40 ms apart, so how many land inside the 250 ms + // release depends on its phase: the count is not judged.) + const values = JSON.stringify(blocked.map(s => Math.round(s.value))); + expect(blocked[0].value, values).toBeLessThan(rest - 1); + expect(restIndex, values).toBeGreaterThan(0); + for (let i = 1; i < distinct.length; i++) { + expect(distinct[i], values).toBeGreaterThan(distinct[i - 1]); + } +}); + +test( + 'storyboard: a row released after a hold', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + const {driver, row, center} = await openRow(page, LIST_ROW); + await installTimerGate(page); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const clip = { + x: 0, + y: Math.max(0, box.y - 16), + width: page.viewportSize()?.width ?? 402, + height: box.height + 32, + }; + await driver.play(tap(center, {holdMs: HOLD_MS})); + await freezeTimers(page); + const {storyboard} = await animationStoryboard(page, { + name: 'list-row-press-release', + clip, + scope: row, + measure: async () => ({ + opacity: await layerOpacity(row), + state: await pressState(row), + }), + columns: 7, + cellScale: 0.6, + }); + await releaseAnimations(page, {finish: true}); + await thawTimers(page); + await storyboard.write(testInfo); + // The trace is the assertion; the sheet is the evidence. + const opacities = storyboard.frames.map(f => f.data.opacity as number); + expect(opacities[0]).toBeCloseTo(1, 2); + expect(opacities.at(-1)).toBeLessThan(0.01); + for (let i = 1; i < opacities.length; i++) { + expect(opacities[i]).toBeLessThanOrEqual(opacities[i - 1] + 1e-6); + } + storyboard.frames.forEach(f => + expect(f.data.opacity as number).toBeCloseTo(expectedStrength(f.t), 2), + ); + }, +); diff --git a/packages/core/src/List/__tests__/ListRowPressPaths.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListRowPressPaths.interaction.browser.spec.ts new file mode 100644 index 0000000000000..7e5f9ad6b62e8 --- /dev/null +++ b/packages/core/src/List/__tests__/ListRowPressPaths.interaction.browser.spec.ts @@ -0,0 +1,360 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListRowPressPaths.interaction.browser.spec.ts + * @input The built List "Interactive" and Press Feedback "Rows" stories, the + * interaction harness, and the cell release clock (motion/uikit/list.ts) + * @output The row press paths beside the main release proofs: a press the + * browser takes for a scroll drops the highlight at once (the press + * controller's cancel, unchanged by the compositor layer); Reduce + * Motion keeps the fade (a fade, not a movement); a mouse press and hover on + * a fine pointer leave the press layer out of it + * @position Interaction evidence for the row press layer (utils/interactionOverlay.stylex.ts `cell`), beside + * ListRowPress.interaction.browser.spec.ts + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + drag, + holdAnimations, + openStory, + releaseAnimations, + seekAnimations, + tap, + touchDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; +import {list} from '../../motion/uikit/list'; + +const storybook = withStorybook(test); + +const RELEASE_MS: number = list.highlight.releaseMs; + +/** The press layer's strength: 0 while the row has no layer box (at rest). */ +const layerOpacity = async (row: Locator) => + row.evaluate(el => { + const before = getComputedStyle(el, '::before'); + return before.content === 'none' || before.content === 'normal' + ? 0 + : Number(before.opacity); + }); + +const pressState = async (row: Locator) => + row.evaluate(el => el.getAttribute('data-astryx-press')); + +async function touchOnly(page: Page) { + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the press layer serves a touch screen'); +} + +test("a press the browser takes for a scroll drops the highlight at once (the controller's cancel, unchanged)", async ({ + page, +}) => { + await openStory(page, storybook(), 'core-press-feedback-touch--rows'); + await touchOnly(page); + const driver = await touchDriver(page); + const row = page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Conversation 2'}) + .first(); + await expect(row).toBeVisible(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // Every press state the controller writes, and every animation the row's + // layer starts, with page times. + await row.evaluate(el => { + const log: string[] = []; + (window as unknown as {__pressLog: string[]}).__pressLog = log; + new MutationObserver(() => + log.push(`press:${el.getAttribute('data-astryx-press')}`), + ).observe(el, {attributeFilter: ['data-astryx-press']}); + el.addEventListener('animationstart', event => + log.push(`start:${(event as AnimationEvent).pseudoElement}`), + ); + }); + const from = {x: box.x + box.width / 2, y: box.y + box.height / 2}; + // Held long enough for the highlight to show, then a vertical pan the + // scroller takes: the browser cancels the touch for the page. + await driver.play( + drag(from, {x: from.x, y: from.y - 80}, {holdMs: 300, durationMs: 160}), + ); + await expect.poll(async () => pressState(row)).toBeNull(); + const log = await page.evaluate( + () => (window as unknown as {__pressLog: string[]}).__pressLog, + ); + // Highlighted while held, then the scroll's cancel removes it outright: + // no release fade starts, and the row is at rest. + expect(log, JSON.stringify(log)).toContain('press:on'); + expect(log.at(-1), JSON.stringify(log)).toBe('press:null'); + expect(log, JSON.stringify(log)).not.toContain('press:fading'); + expect(log, JSON.stringify(log)).not.toContain('start:::before'); + expect(await layerOpacity(row)).toBe(0); +}); + +test('Reduce Motion keeps the release fade: a fade, not a movement', async ({ + page, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await openStory(page, storybook(), 'core-list--interactive'); + await touchOnly(page); + const driver = await touchDriver(page); + const row = page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Sent'}) + .first(); + await expect(row).toBeVisible(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + await driver.play( + tap({x: box.x + box.width / 2, y: box.y + box.height / 2}, {holdMs: 300}), + ); + await holdAnimations(page); + await seekAnimations(page, 0); + expect(await layerOpacity(row)).toBeCloseTo(1, 2); + await seekAnimations(page, RELEASE_MS / 2); + const midway = await layerOpacity(row); + expect(midway).toBeGreaterThan(0.05); + expect(midway).toBeLessThan(0.95); + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => layerOpacity(row)).toBe(0); +}); + +test('a mouse press and hover on a fine pointer leave the press layer out of it', async ({ + browser, +}) => { + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), 'core-list--interactive'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const fine = await page.evaluate( + () => matchMedia('(pointer: fine)').matches, + ); + expect(fine).toBe(true); + const row = page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Sent'}) + .first(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // No layer at all with a fine pointer: hovering, pressing and lifting + // never give the row a `::before` box. + const layer = async () => + row.evaluate(el => getComputedStyle(el, '::before').content); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + expect(await layer()).toBe('none'); + await page.mouse.down(); + expect(await pressState(row)).toBeNull(); + expect(await layer()).toBe('none'); + await page.mouse.up(); + expect(await pressState(row)).toBeNull(); + expect(await layer()).toBe('none'); + } finally { + await context.close(); + } +}); + +test('a fine pointer: a row is as it was, with no press layer and no stacking context (desktop unchanged)', async ({ + browser, +}) => { + // AST-017 FR59/DEC-25: touch work leaves a fine pointer's rows as they were. The + // press layer and the stacking context it needs exist under a finger only, + // so a caller's own `::before` and z-index behave as before. + const context = await browser.newContext({ + viewport: {width: 1024, height: 768}, + hasTouch: false, + isMobile: false, + }); + const page = await context.newPage(); + try { + const rowBox = async (story: string, selector: string, label: string) => { + await openStory(page, storybook(), story); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const row = page.locator(selector).filter({hasText: label}).first(); + await expect(row).toBeVisible(); + return row.evaluate(el => ({ + before: getComputedStyle(el, '::before').content, + isolation: getComputedStyle(el).isolation, + })); + }; + expect( + await rowBox('core-list--interactive', '[data-astryx-pressable]', 'Sent'), + ).toEqual({before: 'none', isolation: 'auto'}); + // A row's own `::before` is exactly as its author wrote it: nothing of + // the layer (its opacity, stacking, hit testing) reaches it. + const own = await page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Sent'}) + .first() + .evaluate(el => { + const style = document.createElement('style'); + style.textContent = + '[data-test-own]::before{content:"•";position:static;opacity:1}'; + document.head.append(style); + el.setAttribute('data-test-own', ''); + const before = getComputedStyle(el, '::before'); + return { + content: before.content, + opacity: before.opacity, + position: before.position, + zIndex: before.zIndex, + pointerEvents: before.pointerEvents, + }; + }); + expect(own).toEqual({ + content: '"•"', + opacity: '1', + position: 'static', + zIndex: 'auto', + pointerEvents: 'auto', + }); + expect( + await rowBox( + 'core-treelist--interactive', + '#storybook-root [role="treeitem"] [data-astryx-pressable]', + 'Settings', + ), + ).toEqual({before: 'none', isolation: 'auto'}); + } finally { + await context.close(); + } +}); + +test('a radio row under a finger paints its circle’s press, and keeps its bare look: no row layer', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the held touch is driven with Chromium touch events (CDP)', + ); + await openStory(page, storybook(), 'core-radiolist--default'); + await touchOnly(page); + const row = page.locator('#storybook-root [data-astryx-pressable]').first(); + await expect(row).toBeVisible(); + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // On the label, away from the circle: the row takes the press. + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [{x: box.x + box.width * 0.6, y: box.y + box.height / 2}], + }); + await expect.poll(async () => pressState(row)).toBe('on'); + const look = await row.evaluate(el => { + const wrapper = [...el.querySelectorAll('*')].find( + child => + child.querySelector(':scope > input[type="radio"]') != null && + getComputedStyle(child, '::after').content !== 'none', + ); + return { + circle: + wrapper == null + ? null + : getComputedStyle(wrapper, '::after').backgroundImage, + layer: getComputedStyle(el, '::before').content, + }; + }); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchCancel', + touchPoints: [], + }); + // The circle's own press paint: the pressed token, not a transparent + // gradient. + expect(look.circle).toMatch(/gradient/); + expect(look.circle).not.toMatch( + /^linear-gradient\(rgba\(0, 0, 0, 0\), rgba\(0, 0, 0, 0\)\)$/, + ); + // Only the circle paints, as with a mouse: the row has no layer. + expect(look.layer).toBe('none'); +}); + +test('under a finger, a row at rest is as it was: its own ::before keeps its look and it is no stacking context; the press layer takes the ::before only while pressed', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the held touch is driven with Chromium touch events (CDP)', + ); + await openStory(page, storybook(), 'core-list--interactive'); + await touchOnly(page); + const row = page + .locator('[data-astryx-pressable]') + .filter({hasText: 'Sent'}) + .first(); + await expect(row).toBeVisible(); + const look = async () => + row.evaluate(el => { + const before = getComputedStyle(el, '::before'); + return { + content: before.content, + opacity: before.opacity, + position: before.position, + zIndex: before.zIndex, + pointerEvents: before.pointerEvents, + isolation: getComputedStyle(el).isolation, + }; + }); + // A caller's own decoration on the row's `::before` (a page rule beats + // the components' layered styles for what it sets; the rest is theirs). + await row.evaluate(el => { + const style = document.createElement('style'); + style.textContent = '[data-test-own]::before{content:"•"}'; + document.head.append(style); + el.setAttribute('data-test-own', ''); + }); + const own = { + content: '"•"', + opacity: '1', + position: 'static', + zIndex: 'auto', + pointerEvents: 'auto', + isolation: 'auto', + }; + expect(await look()).toEqual(own); + // A press: the layer takes the `::before`, in its own stacking context. + const box = await row.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchStart', + touchPoints: [{x: box.x + box.width / 2, y: box.y + box.height / 2}], + }); + await expect.poll(async () => pressState(row)).toBe('on'); + // The layer's box (with the caller's content), painted, in its own + // stacking context. + const pressed = await look(); + expect(pressed.content).toBe('"•"'); + expect(pressed.position).toBe('absolute'); + expect(pressed.zIndex).toBe('-1'); + expect(pressed.opacity).toBe('1'); + expect(pressed.isolation).toBe('isolate'); + await cdp.send('Input.dispatchTouchEvent', { + type: 'touchCancel', + touchPoints: [], + }); + // The press over, the row's own decoration is back as it was. + await expect.poll(async () => pressState(row)).toBeNull(); + expect(await look()).toEqual(own); +}); diff --git a/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts new file mode 100644 index 0000000000000..7421d176350ac --- /dev/null +++ b/packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts @@ -0,0 +1,393 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListTouchHitArea.interaction.browser.spec.ts + * @input The built List stories in the touch phone context (primary pointer + * coarse) and in a mouse context of the same viewport and scale + * @output Proofs for `spec:AST-094` FR42 (`component:List` FR10, #8571) under a finger: an interactive + * row's hit layer grows toward the touch target, taking half the gap to + * each neighboring row and growing further only where nothing is near; a + * tap in that growth activates the row and a tap past it does not; no two + * rows' areas overlap; the row's own content keeps its taps; a row already + * as tall as the touch target and a disabled row gain nothing; the theme's + * touch target and row padding reach it; the layer adds no layout and + * paints nothing; a mouse gets no layer. Geometry is read from the layer's + * computed edges: Chromium's elementFromPoint snaps a point to whole CSS + * pixels, too coarse for a 1 px half gap, so the hit tests probe whole + * pixels inside a wider growth + * @position Interaction evidence for ListItem's touch hit area + * (utils/touchHitArea.stylex.ts, kept live by utils/touchHitArea.ts) under a finger + * (./touchStory.ts) + */ + +import { + expect, + test, + type Browser, + type Page, + type TestInfo, +} from '@playwright/test'; +import {withStorybook} from '@astryxdesign/interaction-harness'; +import {openStory} from './touchStory'; + +const storybook = withStorybook(test); + +interface Row { + readonly text: string; + readonly top: number; + readonly bottom: number; + readonly height: number; + readonly x: number; + readonly layer: { + readonly content: string; + readonly top: number; + readonly bottom: number; + readonly paint: string; + }; + readonly isolation: string; + readonly written: string; +} + +/** The story's rows (Storybook's own hidden error page has list items too). */ +async function rowsOf(page: Page): Promise { + return page.locator('#storybook-root li').evaluateAll(elements => + elements.map(el => { + const box = el.getBoundingClientRect(); + const layer = getComputedStyle(el, '::after'); + return { + text: el.textContent?.trim() ?? '', + top: box.top, + bottom: box.bottom, + height: box.height, + x: box.left + box.width / 2, + layer: { + content: layer.content, + // How far the layer reaches past the row, px (its insets negated). + top: layer.content === 'none' ? 0 : 0 - Number.parseFloat(layer.top), + bottom: + layer.content === 'none' ? 0 : 0 - Number.parseFloat(layer.bottom), + paint: [ + layer.backgroundColor, + layer.backgroundImage, + layer.boxShadow, + layer.borderTopWidth, + layer.outlineStyle, + ].join(' | '), + }, + isolation: getComputedStyle(el).isolation, + written: (el as HTMLElement).style.getPropertyValue( + '--astryx-hit-inset-top', + ), + }; + }), + ); +} + +/** + * The rows once the shared hit area has measured them: its pass runs in a + * frame after the rows show, and writes only insets that differ from 0, so + * wait a few frames and then until two frames read the same. + */ +async function measuredRowsOf(page: Page): Promise { + const frames = async (count: number) => + page.evaluate(async n => { + for (let i = 0; i < n; i++) { + await new Promise(resolve => requestAnimationFrame(resolve)); + } + }, count); + await frames(4); + let previous = JSON.stringify(await rowsOf(page)); + await expect + .poll(async () => { + await frames(2); + const current = JSON.stringify(await rowsOf(page)); + const settled = current === previous; + previous = current; + return settled; + }) + .toBe(true); + return rowsOf(page); +} + +/** A theme that sets the touch target size, before the story renders. */ +async function themeTouchTarget(page: Page, size: string): Promise { + // Storybook rewrites the root element's style attribute, so a stylesheet. + await page.addInitScript(value => { + document.addEventListener('DOMContentLoaded', () => { + const style = document.createElement('style'); + style.textContent = `:root { --size-touch-target: ${value}; }`; + document.head.append(style); + }); + }, size); +} + +/** The story row the browser hit-tests at a point, by its text. */ +async function rowAt(page: Page, x: number, y: number): Promise { + return page.evaluate( + ([px, py]) => + document + .elementFromPoint(px, py) + ?.closest('#storybook-root li') + ?.textContent?.trim() ?? null, + [x, y] as const, + ); +} + +const isTouch = async (page: Page) => + page.evaluate(() => matchMedia('(pointer: coarse)').matches); + +/** FR42's invariant: no row's area reaches into the next row's area. */ +function expectNoOverlap(rows: ReadonlyArray): void { + for (let i = 0; i + 1 < rows.length; i++) { + expect( + rows[i].bottom + rows[i].layer.bottom, + JSON.stringify(rows), + ).toBeLessThanOrEqual(rows[i + 1].top - rows[i + 1].layer.top + 0.01); + } +} + +/** The same page with a mouse: the phone's viewport and scale, a fine pointer. */ +async function withMouse( + browser: Browser, + testInfo: TestInfo, + run: (page: Page) => Promise, +): Promise { + const {viewport, deviceScaleFactor} = testInfo.project.use; + const context = await browser.newContext({ + viewport, + deviceScaleFactor, + hasTouch: false, + isMobile: false, + }); + try { + const page = await context.newPage(); + return await run(page); + } finally { + await context.close(); + } +} + +test('under a finger, a short interactive row takes half the gap to each neighbor and grows toward the touch target where nothing is near', async ({ + page, +}) => { + await openStory(page, storybook(), 'core-list--interactive'); + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + const rows = await measuredRowsOf(page); + expect(rows).toHaveLength(3); + const gap = rows[1].top - rows[0].bottom; + const grow = (44 - rows[0].height) / 2; + const summary = JSON.stringify({gap, grow, rows}); + // One-line rows, shorter than the 44px touch target, 2px apart. + expect(rows[0].height, summary).toBeLessThan(44); + expect(gap, summary).toBeCloseTo(2, 1); + // Half the gap between rows; the full growth past the list's ends, where + // nothing interactive is near. + const reach = rows.map(row => [row.layer.top, row.layer.bottom]); + expect(reach, summary).toEqual([ + [grow, gap / 2], + [gap / 2, gap / 2], + [gap / 2, grow], + ]); + expectNoOverlap(rows); +}); + +test('under a finger, a tap in a row’s growth activates that row, and nothing is hit past it', async ({ + page, +}) => { + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + // A theme with a 60px touch target, so the growth past the list's first row + // spans whole pixels a tap can land on. + await themeTouchTarget(page, '60px'); + await openStory(page, storybook(), 'core-list--interactive'); + const rows = await measuredRowsOf(page); + const grow = (60 - rows[0].height) / 2; + expect(rows[0].layer.top, JSON.stringify(rows)).toBeCloseTo(grow, 1); + const inside = Math.round(rows[0].top - grow / 2); + const outside = Math.round(rows[0].top - grow - 3); + // The browser's own hit test at each point, then a real tap in the growth. + // (No tap past it: a touch engine's own touch adjustment may move a tap + // that lands a few pixels from a target onto it.) + expect(await rowAt(page, rows[0].x, inside)).toBe(rows[0].text); + expect(await rowAt(page, rows[0].x, outside)).toBe(null); + await page.evaluate(() => { + const taps: string[] = []; + (window as unknown as {taps: string[]}).taps = taps; + for (const row of document.querySelectorAll('#storybook-root li')) { + row.addEventListener('click', () => + taps.push(row.textContent?.trim() ?? ''), + ); + } + }); + await page.touchscreen.tap(rows[0].x, inside); + expect( + await page.evaluate(() => (window as unknown as {taps: string[]}).taps), + ).toEqual([rows[0].text]); +}); + +test('under a finger, the row’s own content keeps its taps', async ({page}) => { + await openStory(page, storybook(), 'core-list--interactive'); + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + await measuredRowsOf(page); + const hits = await page.locator('#storybook-root li').evaluateAll(rows => + rows.map(row => { + // The row's end content (its chevron), above the layer. + const icons = row.querySelectorAll('svg'); + const end = icons[icons.length - 1]; + const box = end.getBoundingClientRect(); + const hit = document.elementFromPoint( + box.left + box.width / 2, + box.top + box.height / 2, + ); + return hit != null && hit !== row && row.contains(hit); + }), + ); + expect(hits).toEqual([true, true, true]); +}); + +test('under a finger, a row already as tall as the touch target gains nothing, rows that touch take nothing from each other, and a disabled row has no layer', async ({ + page, +}) => { + test.slow(); + // Links: a one-line row, then two rows with descriptions (taller than the + // touch target): only the short row grows. + await openStory(page, storybook(), 'core-list--links'); + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + const links = await measuredRowsOf(page); + const summary = JSON.stringify(links); + expect(links[0].height, summary).toBeLessThan(44); + expect(links[0].layer.bottom, summary).toBeCloseTo( + (links[1].top - links[0].bottom) / 2, + 1, + ); + for (const row of links.slice(1)) { + expect(row.height, summary).toBeGreaterThanOrEqual(44); + expect([row.layer.top, row.layer.bottom], summary).toEqual([0, 0]); + } + expectNoOverlap(links); + // Compact with dividers: the rows touch, so between them nothing grows. + await openStory(page, storybook(), 'core-list--compact'); + const compact = await measuredRowsOf(page); + expect(compact.length).toBeGreaterThan(1); + for (let i = 0; i + 1 < compact.length; i++) { + expect(compact[i].layer.bottom, JSON.stringify(compact)).toBe(0); + expect(compact[i + 1].layer.top, JSON.stringify(compact)).toBe(0); + } + expectNoOverlap(compact); + // A disabled row offers no target: no layer, nothing measured. + await openStory(page, storybook(), 'core-list--disabled-items'); + await measuredRowsOf(page); + const disabled = await page + .locator('#storybook-root li[aria-disabled="true"]') + .evaluateAll(rows => + rows.map(row => [ + getComputedStyle(row, '::after').content, + (row as HTMLElement).style.getPropertyValue('--astryx-hit-inset-top'), + ]), + ); + expect(disabled.length).toBeGreaterThan(0); + for (const [content, written] of disabled) { + expect(content).toBe('none'); + expect(written).toBe(''); + } +}); + +test('under a finger, a page can raise the touch target but never lower it below 44px, and row padding reaches the layer', async ({ + page, +}) => { + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + // A page's touch target under 44px leaves the 44px target (spec:AST-094 + // FR42): the rows grow exactly as with none set. + await openStory(page, storybook(), 'core-list--interactive'); + const plain = (await measuredRowsOf(page)).map(row => row.layer); + await themeTouchTarget(page, '30px'); + await openStory(page, storybook(), 'core-list--interactive'); + const lowered = (await measuredRowsOf(page)).map(row => row.layer); + expect(plain.some(layer => layer.top > 0 || layer.bottom > 0)).toBe(true); + expect(lowered).toEqual(plain); + // A theme whose row padding makes the row as tall as the target (the later + // stylesheet's 44px wins over the 30px one). + await themeTouchTarget(page, '44px'); + await page.addInitScript(() => { + document.addEventListener('DOMContentLoaded', () => { + const style = document.createElement('style'); + style.textContent = + '#storybook-root li { padding-block: 12px !important; }'; + document.head.append(style); + }); + }); + await openStory(page, storybook(), 'core-list--interactive'); + const padded = await measuredRowsOf(page); + expect(padded[0].height).toBeGreaterThanOrEqual(44); + for (const row of padded) { + expect([row.layer.top, row.layer.bottom]).toEqual([0, 0]); + } +}); + +test('under a finger, a tap in a link row’s growth follows its link', async ({ + page, +}) => { + test.skip(!(await isTouch(page)), 'the hit area applies under a finger only'); + // A 60px touch target, so the growth above the first row spans whole + // pixels a tap can land on, well clear of the row's anchor. + await themeTouchTarget(page, '60px'); + await openStory(page, storybook(), 'core-list--links'); + const rows = await measuredRowsOf(page); + const grow = rows[0].layer.top; + expect(grow, JSON.stringify(rows)).toBeGreaterThan(4); + const inside = Math.round(rows[0].top - grow / 2); + expect(await rowAt(page, rows[0].x, inside)).toBe(rows[0].text); + // The row is the Links story's "Documentation" (`href="/docs"`). + const followed = page.waitForURL(/\/docs$/, {timeout: 5000}); + await page.touchscreen.tap(rows[0].x, inside); + await followed; +}); + +for (const story of [ + 'core-list--interactive', + 'core-list--links', + 'core-list--compact', + 'core-list--with-media', +]) { + test(`${story}: the layer adds no layout and paints nothing, and a mouse gets none`, async ({ + browser, + page, + }, testInfo) => { + await openStory(page, storybook(), story); + test.skip( + !(await isTouch(page)), + 'the hit area applies under a finger only', + ); + const touch = await measuredRowsOf(page); + // The same page with every row's layer taken away: the same boxes. + await page.addStyleTag({ + content: '#storybook-root li::after { display: none !important; }', + }); + const bare = await rowsOf(page); + const mouse = await withMouse(browser, testInfo, async mousePage => { + await openStory(mousePage, storybook(), story); + expect(await isTouch(mousePage)).toBe(false); + // A frame for a pass that must not come. + await mousePage.evaluate(async () => { + await new Promise(resolve => requestAnimationFrame(resolve)); + }); + return rowsOf(mousePage); + }); + const summary = JSON.stringify({touch, bare, mouse}); + expect(touch.length, summary).toBeGreaterThan(0); + expect(bare.length, summary).toBe(touch.length); + expect(mouse.length, summary).toBe(touch.length); + for (const [i, row] of touch.entries()) { + expect(row.top, summary).toBeCloseTo(bare[i].top, 2); + expect(row.height, summary).toBeCloseTo(bare[i].height, 2); + if (row.layer.content !== 'none') { + expect(row.layer.paint, summary).toMatch( + /^rgba\(0, 0, 0, 0\) \| none \| none \| 0px \| none$/, + ); + } + // A mouse: no pseudo-element, no stacking context, nothing measured. + expect(mouse[i].layer.content, summary).toBe('none'); + expect(mouse[i].isolation, summary).toBe('auto'); + expect(mouse[i].written, summary).toBe(''); + } + }); +} diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts new file mode 100644 index 0000000000000..8b7ce4949ba43 --- /dev/null +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -0,0 +1,882 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListUpdates.interaction.browser.spec.ts + * @input The built List "Animated Changes" story in the touch phone context, + * the interaction harness and the table spring from the UIKit constants + * table (motion/uikit/list.ts) + * @output Interaction and animation proofs for a List with `hasAnimatedChanges`: + * after a removal the rows below start where they were and slide up on the + * table spring; after an insert the rows below slide down and the new row + * fades in once they have cleared its band; a reorder moves rows to their + * new places, the row crossing the others riding above them with the + * surface behind it; content after the list takes its new place at once, + * never translated, a fixed element inside it staying fixed, and after a + * removal the rows sliding up are clipped to the list's box; a change + * while rows still move makes no jump; under reduced motion a removal, an + * insert and a reorder cross-fade, opacity only, within 200 ms + * (`design:reduced-motion`); a + * theme's table spring times it; a removed row collapses in place, its + * bottom edge on the next row's top every frame, and a row swiped away + * collapses the same way while the rows below close the gap, as it was on + * screen (a compositor animation on its parts kept); the rows keep + * moving while the main thread is blocked, with no Layout or Paint; a + * storyboard of a removal + * @position Interaction evidence for List/useListUpdateMotion.ts under a + * finger (./touchStory.ts), with an Android case that moves the same way and + * a mouse case where the rows land in place with the commit + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + animationStoryboard, + blockMainThread, + busyWindowProof, + compareCurve, + countBetween, + holdAnimations, + markElement, + releaseAnimations, + seekAnimations, + startScreencast, + timeline, + trackMarker, + traceRendering, + waitForAnimation, + withStorybook, + writeEvidence, +} from '@astryxdesign/interaction-harness'; +import {solveSpring, toSpring} from '../../motion/spring'; +import {list} from '../../motion/uikit/list'; +import {openStory} from './touchStory'; +import {expectReducedMotionCrossFade} from './reducedMotion'; +import {blockBehindBeacon, installBeacon, sampleVideoPoints} from './rowPixels'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--animated-changes'; +const SPRING = toSpring(list.update.tableSpring); +const progress = (t: number) => + solveSpring(SPRING, {from: 0, to: 1}).value(t / 1000); +const SETTLE_MS = + solveSpring(SPRING, {from: 0, to: 1}).settleTime(0.001) * 1000; + +// A row of the list, never a removed row's ghost (or the row inside it). +const row = (page: Page, label: string) => + page + .locator( + '#storybook-root li:not([data-astryx-leaving], [data-astryx-leaving] li)', + ) + .filter({hasText: label}) + .first(); + +const translateY = async (element: Locator) => + element.evaluate(el => { + const value = getComputedStyle(el).translate; + if (value === 'none' || value === '') { + return 0; + } + const [, y = '0px'] = value.split(' '); + return Number.parseFloat(y); + }); + +const opacity = async (element: Locator) => + element.evaluate(el => Number(getComputedStyle(el).opacity)); + +async function open(page: Page) { + await openStory(page, storybook(), STORY); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'list changes move under a finger only'); + await expect(row(page, 'Spam')).toBeVisible(); +} + +async function press(page: Page, name: string) { + await page.getByRole('button', {name}).click(); +} + +test('Android: a removal moves the rows the same way (one touch model)', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'Android is Chromium'); + await openStory(page, storybook(), STORY); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(true); + await expect(row(page, 'Spam')).toBeVisible(); + const drafts = row(page, 'Drafts'); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + // The row below starts where it was and springs home, as on iOS. + expect( + await drafts.evaluate(el => el.getAnimations().length), + ).toBeGreaterThan(0); + await expect.poll(async () => translateY(drafts)).toBe(0); +}); + +test('a mouse: a removal and an insert land in place with the commit', async ({ + browser, +}) => { + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 900, height: 900}, + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), STORY); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + await expect(row(page, 'Spam')).toBeVisible(); + const drafts = row(page, 'Drafts'); + const button = page.getByRole('button', {name: 'Remove the second row'}); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + // Nothing animates: the rows and the content below are already in place. + const motions = async (element: Locator) => + element.evaluate(el => el.getAnimations().length); + expect(await translateY(drafts)).toBe(0); + expect(await motions(drafts)).toBe(0); + expect(await translateY(button)).toBe(0); + expect(await motions(button)).toBe(0); + await press(page, 'Insert a row second'); + const inserted = page.locator('#storybook-root li').nth(1); + await expect(inserted).toBeVisible(); + expect(await opacity(inserted)).toBe(1); + expect(await motions(inserted)).toBe(0); + } finally { + await context.close(); + } +}); + +test('a removal: the rows below start where they were and slide up on the table spring', async ({ + page, +}, testInfo) => { + await open(page); + const drafts = row(page, 'Drafts'); + const layoutTop = async () => + drafts.evaluate(el => (el as HTMLElement).offsetTop); + const before = await layoutTop(); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + const after = await layoutTop(); + const gap = await drafts.evaluate(el => { + // The row above, never a removed row's ghost. + let previous = el.previousElementSibling as HTMLElement | null; + while (previous?.hasAttribute('data-astryx-leaving') === true) { + previous = previous.previousElementSibling as HTMLElement | null; + } + return previous == null + ? 0 + : (el as HTMLElement).offsetTop - previous.offsetTop; + }); + const samples: {t: number; value: number}[] = []; + for (const t of timeline(SETTLE_MS)) { + await seekAnimations(page, t); + samples.push({t, value: await translateY(drafts)}); + } + await releaseAnimations(page, {finish: true}); + const expected = (t: number) => gap * (1 - progress(t)); + const comparison = compareCurve(samples, expected, 0.5); + await writeEvidence( + 'curves/list-update-removal', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {spring: list.update.tableSpring, gap, samples, comparison}, + null, + 2, + ), + }, + testInfo, + ); + // On screen at its old place first: one row lower than its new layout. + expect(samples[0].value).toBeCloseTo(gap, 0); + // Layout moved it up by one row; the motion put it back on screen. + expect(before - after).toBeCloseTo(gap, 0); + expect(comparison.maxError, JSON.stringify(comparison.worst)).toBeLessThan( + 0.5, + ); + await expect.poll(async () => translateY(drafts)).toBe(0); +}); + +test("a removal: the removed row collapses in place, its bottom edge on the next row's top every frame, then goes", async ({ + page, +}) => { + await open(page); + const sent = row(page, 'Sent'); + const before = await sent.boundingBox(); + if (before == null) { + throw new Error('no row'); + } + await press(page, 'Remove the second row'); + await holdAnimations(page); + const ghost = page.locator('#storybook-root [data-astryx-leaving]'); + await expect(ghost).toHaveCount(1); + expect(await ghost.getAttribute('aria-hidden')).toBe('true'); + const inside = ghost.locator('li').filter({hasText: 'Sent'}); + const drafts = row(page, 'Drafts'); + const heights: number[] = []; + for (const t of [0, 40, 80, 120, 200, 300]) { + await seekAnimations(page, t); + const [clip, content, next] = await Promise.all([ + ghost.evaluate(el => el.getBoundingClientRect().toJSON() as DOMRect), + inside.boundingBox(), + drafts.boundingBox(), + ]); + if (content == null || next == null) { + throw new Error('no box'); + } + // Its content stays where it was while its bottom edge rises with the + // next row's top: one motion, as UIKit collapses a deleted cell. + expect(content.y, `t=${t}`).toBeCloseTo(before.y, 0); + expect(clip.bottom, `t=${t}`).toBeCloseTo(next.y, 0); + heights.push(clip.bottom - before.y); + } + expect(heights[0]).toBeCloseTo(before.height, 0); + for (let i = 1; i < heights.length; i++) { + expect(heights[i], JSON.stringify(heights)).toBeLessThan(heights[i - 1]); + } + await releaseAnimations(page, {finish: true}); + await expect(ghost).toHaveCount(0); +}); + +test('an insert: the rows below slide down, and the new row fades in once they have cleared its band', async ({ + page, +}) => { + await open(page); + await press(page, 'Insert a row second'); + const inserted = row(page, 'Folder 1'); + await expect(inserted).toBeVisible(); + await holdAnimations(page); + const sent = row(page, 'Sent'); + const height = await inserted.evaluate( + el => el.getBoundingClientRect().height, + ); + await seekAnimations(page, 0); + expect(await translateY(sent)).toBeLessThan(-1); + // While Sent's label is within half a row of the new row's (Sent starts + // in the new row's band), the new row shows nothing: rows have no + // background, and the two labels would overlap. Then it fades in. + let crossing = 0; + let previous = 0; + for (let t = 0; t <= SETTLE_MS; t += 10) { + await seekAnimations(page, t); + const y = await translateY(sent); + const shown = await opacity(inserted); + if (y < -height / 2 - 0.5) { + expect(shown, `t=${t}`).toBeCloseTo(0, 3); + crossing += 1; + } + expect(shown, `t=${t}`).toBeGreaterThanOrEqual(previous - 0.001); + previous = shown; + } + expect(crossing).toBeGreaterThan(2); + await seekAnimations(page, SETTLE_MS * 0.6); + expect(await opacity(inserted)).toBeGreaterThan(0.5); + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => opacity(inserted)).toBe(1); + await expect.poll(async () => translateY(sent)).toBe(0); +}); + +test('a reorder: each row slides from its old place to its new one', async ({ + page, +}) => { + await open(page); + const spam = row(page, 'Spam'); + const inbox = row(page, 'Inbox'); + await press(page, 'Move the last row first'); + await holdAnimations(page); + await seekAnimations(page, 0); + // Spam starts four rows down (where it was) and Inbox one row up. + expect(await translateY(spam)).toBeGreaterThan(1); + expect(await translateY(inbox)).toBeLessThan(-1); + // Spam crosses the rows moving down: it rides above them with the list's + // surface behind it, so their labels never show through each other. + const paint = async (element: Locator) => + element.evaluate(node => { + // The surface: an inset shadow across the row's padding box. + const shadow = getComputedStyle(node).boxShadow; + const probe = document.createElement('div'); + probe.style.backgroundColor = 'var(--color-background-surface)'; + node.parentElement?.append(probe); + const surface = getComputedStyle(probe).backgroundColor; + probe.remove(); + return { + zIndex: getComputedStyle(node).zIndex, + layer: + shadow === 'none' || !shadow.includes('inset') + ? null + : (/^rgba?\([^)]*\)/.exec(shadow)?.[0] ?? shadow), + surface, + }; + }); + await seekAnimations(page, SETTLE_MS / 4); + const travelling = await paint(spam); + expect(travelling.zIndex).toBe('1'); + expect(travelling.layer).toBe(travelling.surface); + expect((await paint(inbox)).layer).toBeNull(); + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => translateY(spam)).toBe(0); + await expect.poll(async () => translateY(inbox)).toBe(0); + // At rest it is a row like the others again. + await expect.poll(async () => (await paint(spam)).layer).toBeNull(); + expect((await paint(spam)).zIndex).toBe('auto'); +}); + +test('content after the list takes its place by layout at once, with no translate, and a fixed element inside it stays fixed', async ({ + page, +}) => { + await open(page); + const button = page.getByRole('button', {name: 'Insert a row second'}); + const spam = row(page, 'Spam'); + // More content after the list, holding a position: fixed element, which + // stays where the viewport puts it as long as nothing transforms its + // ancestors. + await button.evaluate(el => { + const after = document.createElement('div'); + after.style.height = '20px'; + const fixed = document.createElement('div'); + fixed.setAttribute('data-test-fixed', ''); + fixed.style.cssText = + 'position: fixed; top: 10px; left: 10px; width: 8px; height: 8px;'; + after.append(fixed); + el.insertAdjacentElement('afterend', after); + }); + const fixedTop = async () => + page + .locator('[data-test-fixed]') + .evaluate(el => el.getBoundingClientRect().top); + const rest = (await button.boundingBox())?.y ?? 0; + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + await seekAnimations(page, 0); + // Its new layout at once, a row higher, with nothing on it. + expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe( + 'none', + ); + expect(rest - ((await button.boundingBox())?.y ?? 0)).toBeGreaterThan(1); + expect(await fixedTop()).toBeCloseTo(10, 0); + // The rows inside the list still start where they were. + expect(await translateY(spam)).toBeGreaterThan(1); + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => translateY(spam)).toBe(0); + expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe( + 'none', + ); +}); + +test('after a removal the rows sliding up into the gap never paint over the content after the list', async ({ + page, +}) => { + await open(page); + const list = page.locator('#storybook-root ul').first(); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + await seekAnimations(page, 0); + // Just under the list's new bottom edge, where the content after it now + // sits, the last row, still a row lower on its way up, is clipped away. + const hitsRow = await list.evaluate(el => { + const box = el.getBoundingClientRect(); + const target = document.elementFromPoint( + box.left + box.width / 2, + box.bottom + 4, + ); + return target != null && el.contains(target); + }); + expect(hitsRow).toBe(false); + expect(await list.evaluate(el => getComputedStyle(el).overflowY)).toBe( + 'clip', + ); + await releaseAnimations(page, {finish: true}); + await expect + .poll(async () => list.evaluate(el => getComputedStyle(el).overflowY)) + .toBe('visible'); +}); + +test('a change while rows still move: no jump, they keep moving to their new places', async ({ + page, +}) => { + await open(page); + // Archive's on-screen top, every frame, from the first change to rest. + await page.evaluate(() => { + const target = [...document.querySelectorAll('#storybook-root li')].find( + li => li.textContent?.trim() === 'Archive', + ) as HTMLElement; + const tops: number[] = []; + (window as unknown as {__tops: number[]}).__tops = tops; + const tick = () => { + tops.push(target.getBoundingClientRect().top); + if (tops.length < 90) { + requestAnimationFrame(tick); + } + }; + requestAnimationFrame(tick); + }); + await press(page, 'Remove the second row'); + // A second removal while Archive is still sliding up from the first. + await page.waitForTimeout(90); + await press(page, 'Remove the second row'); + await page.waitForTimeout(1200); + const tops = await page.evaluate( + () => (window as unknown as {__tops: number[]}).__tops, + ); + const rowHeight = await row(page, 'Archive').evaluate(el => { + // The row above, never a removed row's ghost. + let previous = el.previousElementSibling as HTMLElement | null; + while (previous?.hasAttribute('data-astryx-leaving') === true) { + previous = previous.previousElementSibling as HTMLElement | null; + } + return previous == null + ? 0 + : (el as HTMLElement).offsetTop - previous.offsetTop; + }); + const steps = tops.slice(1).map((top, i) => top - tops[i]); + // Up two rows in all, never back down, and no frame jumps by a row. + expect(tops[0] - (tops.at(-1) ?? 0)).toBeCloseTo(2 * rowHeight, 0); + for (const step of steps) { + expect(step, JSON.stringify(tops)).toBeLessThanOrEqual(0.5); + expect(Math.abs(step), JSON.stringify(tops)).toBeLessThan(rowHeight / 2); + } + await expect.poll(async () => translateY(row(page, 'Archive'))).toBe(0); +}); + +test('the update keeps its own table spring, whatever a theme writes', async ({ + page, +}) => { + await open(page); + // The table spring is an internal constant: a variable written the way a + // theme would write one (0.9 s, no bounce, on the root) changes nothing. + await page.evaluate(() => + document.documentElement.style.setProperty( + '--motion-list-update-table-spring', + '0.9s 0', + ), + ); + const table = solveSpring(SPRING, {from: 0, to: 1}); + const drafts = row(page, 'Drafts'); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + const gap = await drafts.evaluate(el => { + // The row above, never a removed row's ghost. + let previous = el.previousElementSibling as HTMLElement | null; + while (previous?.hasAttribute('data-astryx-leaving') === true) { + previous = previous.previousElementSibling as HTMLElement | null; + } + return previous == null + ? 0 + : (el as HTMLElement).offsetTop - previous.offsetTop; + }); + for (const t of [SETTLE_MS / 2, SETTLE_MS]) { + await seekAnimations(page, t); + expect(await translateY(drafts)).toBeCloseTo( + gap * (1 - table.value(t / 1000)), + 0, + ); + } + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => translateY(drafts)).toBe(0); +}); + +test('a removed row whose parts run a compositor animation collapses as it was on screen', async ({ + page, +}) => { + await open(page); + const sent = row(page, 'Sent'); + await expect(sent).toBeVisible(); + // What a swipe leaves on screen: a running Web Animation of the row's + // content, here held halfway at 40 px to the left. + await sent.evaluate(el => { + const content = el.firstElementChild as HTMLElement; + content.setAttribute('data-test-swiped', ''); + const animation = content.animate( + [{translate: '0px'}, {translate: '-80px'}], + {duration: 1000, fill: 'forwards'}, + ); + animation.pause(); + animation.currentTime = 500; + }); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + await seekAnimations(page, 0); + // The collapse's first frame: the leaving row's content where it was. + const swiped = page.locator( + '#storybook-root [data-astryx-leaving] [data-test-swiped]', + ); + await expect(swiped).toHaveCount(1); + expect( + await swiped.evaluate(el => { + const value = getComputedStyle(el).translate; + return value === 'none' ? 0 : Number.parseFloat(value); + }), + ).toBeCloseTo(-40, 0); + await releaseAnimations(page, {finish: true}); +}); + +test('a removed row collapses as it was on screen even when its parts’ owner resets them as it unmounts', async ({ + page, +}) => { + await open(page); + const sent = row(page, 'Sent'); + await expect(sent).toBeVisible(); + await sent.evaluate(el => { + const content = el.firstElementChild as HTMLElement; + content.setAttribute('data-test-swiped', ''); + const animation = content.animate( + [{translate: '0px'}, {translate: '-80px'}], + {duration: 1000, fill: 'forwards'}, + ); + animation.pause(); + animation.currentTime = 500; + // The owner's own cleanup runs after the row's and before React removes + // the row (a swipe gives its row back its translation): it resets the + // style the row just wrote. + const list = el.parentElement as HTMLElement; + const removeChild = list.removeChild.bind(list); + list.removeChild = (child: T): T => { + if ((child as Node) === el) { + content.style.removeProperty('translate'); + } + return removeChild(child); + }; + }); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + await seekAnimations(page, 0); + const swiped = page.locator( + '#storybook-root [data-astryx-leaving] [data-test-swiped]', + ); + await expect(swiped).toHaveCount(1); + expect( + await swiped.evaluate(el => { + const value = getComputedStyle(el).translate; + return value === 'none' ? 0 : Number.parseFloat(value); + }), + ).toBeCloseTo(-40, 0); + await releaseAnimations(page, {finish: true}); +}); + +test('a removed row a swipe moved sideways on its own root keeps that offset through its collapse', async ({ + page, +}) => { + await open(page); + const sent = row(page, 'Sent'); + await expect(sent).toBeVisible(); + await sent.evaluate(el => { + // What a swipe that moves the row itself leaves on screen: the row + // translated sideways, which its owner gives back as the row unmounts. + (el as HTMLElement).style.translate = '-40px'; + el.setAttribute('data-test-swiped-row', ''); + const list = el.parentElement as HTMLElement; + const removeChild = list.removeChild.bind(list); + list.removeChild = (child: T): T => { + if ((child as Node) === el) { + (el as HTMLElement).style.removeProperty('translate'); + } + return removeChild(child); + }; + }); + await press(page, 'Remove the second row'); + await expect(row(page, 'Sent')).toHaveCount(0); + await holdAnimations(page); + await seekAnimations(page, 0); + const swiped = page.locator( + '#storybook-root [data-astryx-leaving] [data-test-swiped-row]', + ); + await expect(swiped).toHaveCount(1); + // The collapse moves it on y only: the sideways offset stays. + expect( + await swiped.evaluate(el => { + const value = getComputedStyle(el).translate; + return value === 'none' ? 0 : Number.parseFloat(value.split(' ')[0]); + }), + ).toBeCloseTo(-40, 0); + await releaseAnimations(page, {finish: true}); +}); + +test('under reduced motion a removal, an insert and a reorder cross-fade: opacity only, within 200 ms', async ({ + page, +}) => { + // design:reduced-motion DR1 and DR2, under a finger: no row travels or + // collapses; a removed row fades out where it is, a new one fades in. + await page.emulateMedia({reducedMotion: 'reduce'}); + for (const change of [ + 'Remove the second row', + 'Insert a row second', + 'Move the last row first', + ]) { + // Each change on a fresh list. + await open(page); + // The fades last 200 ms: wait for them in the page, frame by frame, + // then hold them before the animator retires them. + await page.evaluate(async name => { + [...document.querySelectorAll('button')] + .find(button => button.textContent?.trim() === name) + ?.click(); + for ( + let frame = 0; + frame < 60 && document.getAnimations().length === 0; + frame += 1 + ) { + await new Promise(resolve => requestAnimationFrame(resolve)); + } + }, change); + expectReducedMotionCrossFade(await holdAnimations(page)); + await releaseAnimations(page, {finish: true}); + } +}); + +test('a row swiped away with a removal action collapses in place: the rows below slide up into its gap', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + await openStory(page, storybook(), 'core-list--animated-changes-swipe'); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'list changes move under a finger only'); + const sent = row(page, 'Sent'); + const drafts = row(page, 'Drafts'); + await expect(sent).toBeVisible(); + const box = await sent.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const gap = await drafts.evaluate(el => { + // The row above, never a removed row's ghost. + let previous = el.previousElementSibling as HTMLElement | null; + while (previous?.hasAttribute('data-astryx-leaving') === true) { + previous = previous.previousElementSibling as HTMLElement | null; + } + return previous == null + ? 0 + : (el as HTMLElement).offsetTop - previous.offsetTop; + }); + // Drafts' translate every frame from the frame Sent leaves the page. + await page.evaluate(() => { + const rows = [...document.querySelectorAll('#storybook-root li')]; + // A row's own text: its swipe panels' action labels aside, since the + // panels may already be in the row. + const labelOf = (li: Element) => { + const copy = li.cloneNode(true) as Element; + for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { + panel.remove(); + } + return copy.textContent?.trim(); + }; + const sentRow = rows.find(li => labelOf(li) === 'Sent'); + const target = rows.find(li => labelOf(li) === 'Drafts') as HTMLElement; + const samples: number[] = []; + (window as unknown as {__ys: number[]}).__ys = samples; + const tick = () => { + // Sent leaves its place: gone, or collapsing in its ghost. + if ( + sentRow?.isConnected !== true || + sentRow.closest('[data-astryx-leaving]') != null + ) { + const value = getComputedStyle(target).translate; + const [, y = '0px'] = value.split(' '); + samples.push(value === 'none' ? 0 : Number.parseFloat(y)); + } + if (samples.length < 40) { + requestAnimationFrame(tick); + } + }; + requestAnimationFrame(tick); + }); + // The swipe panel is the sign the row can be dragged. + await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + // Toward the inline start, most of the row's width: the full swipe fires + // the outermost entry, Delete, whose removal holds the row out until the + // story removes it from the data. + const cdp = await page.context().newCDPSession(page); + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + const finger = async (x: number, type: 'touchStart' | 'touchMove') => + cdp.send('Input.dispatchTouchEvent', {touchPoints: [{x, y}], type}); + await finger(startX, 'touchStart'); + for (const fraction of [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.9]) { + await finger(startX - box.width * fraction, 'touchMove'); + await page.waitForTimeout(40); + } + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + await expect(sent).toHaveCount(0, {timeout: 5000}); + await expect + .poll(async () => + page.evaluate(() => (window as unknown as {__ys: number[]}).__ys.length), + ) + .toBeGreaterThan(10); + const ys = await page.evaluate( + () => (window as unknown as {__ys: number[]}).__ys, + ); + // Starts one row low (where it was) and slides up to its place. + expect(ys[0], JSON.stringify(ys)).toBeCloseTo(gap, 0); + for (let i = 1; i < ys.length; i++) { + expect(ys[i], JSON.stringify(ys)).toBeLessThanOrEqual(ys[i - 1] + 0.01); + } + await expect.poll(async () => translateY(drafts)).toBe(0); +}); + +test('the rows keep moving on every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright', + ); + await open(page); + const drafts = row(page, 'Drafts'); + const unmark = await markElement(drafts); + const cast = await startScreencast(page); + await page.waitForTimeout(100); + await press(page, 'Remove the second row'); + await waitForAnimation(drafts, {minProgressMs: 16}); + const block = await blockMainThread(page, 300); + await page.waitForTimeout(250); + const frames = await cast.stop(); + await unmark(); + const tracked = await trackMarker(page, frames); + const proof = busyWindowProof(tracked, block, {axis: 'y', settledWithin: 1}); + await writeEvidence( + 'busy-main-thread/list-update-removal', + {[`${testInfo.project.name}.json`]: JSON.stringify(proof, null, 1)}, + testInfo, + ); + expect(proof.changed, JSON.stringify(proof)).toBeGreaterThanOrEqual(3); + expect(proof.monotonic, JSON.stringify(proof)).toBe(true); + expect(proof.longestStallMs, JSON.stringify(proof)).toBeLessThan(40); +}); + +test('WebKit: the rows keep moving while the main thread is blocked (video)', async ({ + browser, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'webkit', + 'the Chromium screencast test covers Chromium', + ); + const size = {width: 402, height: 714}; + const context = await browser.newContext({ + viewport: size, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + recordVideo: {dir: testInfo.outputPath('video'), size}, + }); + const page = await context.newPage(); + await open(page); + const drafts = row(page, 'Drafts'); + const gap = await drafts.evaluate(el => { + // The row above, never a removed row's ghost. + let previous = el.previousElementSibling as HTMLElement | null; + while (previous?.hasAttribute('data-astryx-leaving') === true) { + previous = previous.previousElementSibling as HTMLElement | null; + } + return previous == null + ? 0 + : (el as HTMLElement).offsetTop - previous.offsetTop; + }); + await markElement(drafts); + const chip = await page.evaluate(() => { + const el = document.querySelector('[data-harness-marker-chip]'); + const box = el?.getBoundingClientRect(); + return box == null + ? null + : {x: box.x + box.width / 2, y: box.y + box.height / 2}; + }); + if (chip == null) { + throw new Error('no marker chip'); + } + // Probes every 4 px up the row's path: it slides up by one row. + const probes = Array.from({length: Math.floor(gap / 4) + 1}, (_, k) => ({ + x: Math.round(chip.x), + y: Math.round(chip.y - k * 4), + })); + await installBeacon(page); + await page.waitForTimeout(300); + await press(page, 'Remove the second row'); + await waitForAnimation(drafts, {minProgressMs: 1}); + await blockBehindBeacon(page, 300); + await page.waitForTimeout(400); + const video = page.video(); + await context.close(); + const path = await video?.path(); + expect(path).toBeTruthy(); + const samples = await sampleVideoPoints(path as string, probes, size); + const position = (marker: ReadonlyArray) => { + const hits = marker.flatMap((hit, k) => (hit ? [k] : [])); + return hits.length === 0 + ? null + : (hits.reduce((a, b) => a + b, 0) / hits.length) * 4; + }; + const blocked = samples + .filter(s => s.beacon === 'blocked') + .map(s => ({t: s.t, y: position(s.marker)})) + .filter((s): s is {t: number; y: number} => s.y != null); + const distinct = blocked + .map(s => Math.round(s.y)) + .filter((v, i, all) => i === 0 || v !== all[i - 1]); + await writeEvidence( + 'busy-main-thread/list-update-removal-webkit', + {'webkit.json': JSON.stringify({gap, blocked, distinct}, null, 1)}, + testInfo, + ); + // The row kept moving up while script could not run. + expect(distinct.length, JSON.stringify(distinct)).toBeGreaterThanOrEqual(3); + for (let i = 1; i < distinct.length; i++) { + expect(distinct[i]).toBeGreaterThan(distinct[i - 1]); + } +}); + +test('a removal does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + await open(page); + const drafts = row(page, 'Drafts'); + let window = {from: 0, to: 0}; + const trace = await traceRendering(page, async () => { + await press(page, 'Remove the second row'); + const [started] = await waitForAnimation(drafts); + window = {from: started.from, to: started.from + SETTLE_MS}; + await page.waitForTimeout(SETTLE_MS + 100); + }); + const during = countBetween(trace, window.from + 30, window.to - 30); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); +}); + +test( + 'storyboard: a row removed from a list on an iPhone', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + await open(page); + await press(page, 'Remove the second row'); + const {storyboard} = await animationStoryboard(page, { + name: 'list-update-removal', + clip: {x: 0, y: 0, width: 402, height: 420}, + times: [0, 33, 67, 100, 150, 200, 300, Math.round(SETTLE_MS)], + columns: 8, + cellScale: 0.45, + }); + await releaseAnimations(page, {finish: true}); + await storyboard.write(testInfo); + }, +); diff --git a/packages/core/src/List/__tests__/reducedMotion.ts b/packages/core/src/List/__tests__/reducedMotion.ts new file mode 100644 index 0000000000000..bf901dd6b5b5e --- /dev/null +++ b/packages/core/src/List/__tests__/reducedMotion.ts @@ -0,0 +1,102 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reducedMotion.ts + * @input The interaction harness's held animations + * @output `expectReducedMotionCrossFade`: the browser check of + * `design:reduced-motion` DR1 and DR2 over what a change started + * @position Shared by the List and TreeList interaction specs; each case runs + * under reduced motion with a coarse pointer (a finger) + */ + +import {expect} from '@playwright/test'; +import type {HeldAnimation} from '@astryxdesign/interaction-harness'; + +/** DR2's limit on a touch presentation's cross-fade. */ +export const REDUCED_MOTION_FADE_MS = 200; + +const TIMING_KEYS = new Set([ + 'offset', + 'computedOffset', + 'easing', + 'composite', +]); + +/** Properties that move, turn or scale an element. */ +const TRAVEL = new Set(['translate', 'rotate', 'scale', 'transform']); + +/** The properties an animation's keyframes change. */ +function animatedProperties(animation: HeldAnimation): string[] { + const properties = new Set(); + for (const frame of animation.keyframes) { + for (const key of Object.keys(frame)) { + if (!TIMING_KEYS.has(key)) { + properties.add(key); + } + } + } + return [...properties]; +} + +/** + * Whether the animation only lands `property` at a new value (a step: the + * value changes between keyframes at the same offset, or under a step + * easing) rather than moving it through the values between. + */ +function onlyLands(animation: HeldAnimation, property: string): boolean { + const frames = animation.keyframes.filter(frame => property in frame); + for (let index = 0; index + 1 < frames.length; index += 1) { + const from = frames[index]; + const to = frames[index + 1]; + if (String(from[property]) === String(to[property])) { + continue; + } + const sameOffset = + Number(from.computedOffset) === Number(to.computedOffset); + const easing = typeof from.easing === 'string' ? from.easing : ''; + const stepped = /^step|steps\(/.test(easing); + if (!sameOffset && !stepped) { + return false; + } + } + return true; +} + +/** + * `design:reduced-motion` DR1 and DR2, under a coarse pointer: the change + * cross-fades (at least one opacity animation runs, its curve ending within + * 200 ms), nothing travels, scales or resizes on the way (an element may + * land at its new place in one step, hidden by the fade), and nothing but + * opacity animates. `held` is what `holdAnimations` returned right after the + * change. + */ +export function expectReducedMotionCrossFade( + held: ReadonlyArray, +): void { + const summary = JSON.stringify( + held.map(animation => ({ + target: animation.target, + properties: animatedProperties(animation), + curveEndMs: animation.curveEndMs, + })), + ); + let fades = 0; + for (const animation of held) { + for (const property of animatedProperties(animation)) { + if (property === 'opacity') { + fades += 1; + expect(animation.curveEndMs, summary).toBeGreaterThan(0); + expect(animation.curveEndMs, summary).toBeLessThanOrEqual( + REDUCED_MOTION_FADE_MS + 1, + ); + } else if (TRAVEL.has(property)) { + expect(onlyLands(animation, property), `${property}: ${summary}`).toBe( + true, + ); + } else { + expect(property, summary).toBe('opacity'); + } + } + } + expect(fades, summary).toBeGreaterThan(0); +} diff --git a/packages/core/src/List/__tests__/reorderModel.test.ts b/packages/core/src/List/__tests__/reorderModel.test.ts new file mode 100644 index 0000000000000..297819ed293f3 --- /dev/null +++ b/packages/core/src/List/__tests__/reorderModel.test.ts @@ -0,0 +1,414 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorderModel.test.ts + * @input reorderModel.ts and the UIKit reorder values (motion/uikit/reorder.ts) + * @output Unit proofs of the reorder model against the UIKit lab measurements + * (iOS 26.2 simulator, a table of 44 pt rows with rows 6 and 9 at 88 pt): + * the drop positions of a measured drag, the movable range that only the + * fixed rows ending a list bound, the autoscroll steps and the tracking + * clamp + * @position Tests for List/reorderModel.ts + */ + +import {describe, expect, it} from 'vitest'; +import {reorder} from '../../motion/uikit/reorder'; +import { + autoscrollStep, + clampTop, + dropPosition, + movableRange, + nearestSlot, + type ReorderGeometry, + type ReorderRow, + slotLine, + slotsOf, + stepLine, +} from '../reorderModel'; + +function table( + heights: ReadonlyArray, + {gap = 0, fixed = []}: {gap?: number; fixed?: ReadonlyArray} = {}, +): ReorderGeometry { + let top = 0; + const rows: ReorderRow[] = heights.map((height, index) => { + const row = {top, height, isFixed: fixed.includes(index)}; + top += height + gap; + return row; + }); + return {rows, gap}; +} + +/** The measured table: 40 rows of 44 pt, rows 6 and 9 at 88 pt. */ +const MEASURED = table( + Array.from({length: 40}, (_, index) => + index === 6 || index === 9 ? 88 : 44, + ), +); + +describe('dropPosition', () => { + it('reproduces the measured drag of row 3 down over the 88 pt row and back', () => { + // Each proposal of the UIKit lab drag (table.proposed), with the dragged + // row's centre (list coordinates) on the frame before it. Down, the position + // moves once the centre is past the boundary; up, once it is back on it. + const measured: ReadonlyArray<[center: number, position: number]> = [ + [178, 4], + [221, 5], + [309, 6], + [354, 7], + [398, 8], + [396, 7], + [352, 6], + [306.8, 5], + ]; + for (const [center, position] of measured) { + expect(dropPosition(MEASURED, 3, center), `centre ${center}`).toBe( + position, + ); + } + }); + + it('swaps a 44 pt neighbour after half a row and the 88 pt row after its height', () => { + // Row 3's centre starts at 3 × 44 + 22 = 154. + expect(dropPosition(MEASURED, 3, 154)).toBe(3); + expect(dropPosition(MEASURED, 3, 154 + 22)).toBe(3); + expect(dropPosition(MEASURED, 3, 154 + 22.5)).toBe(4); + expect(dropPosition(MEASURED, 3, 154 - 22)).toBe(2); + // From position 5 (centre past 220) to position 6 takes the 88 pt row's height. + expect(dropPosition(MEASURED, 3, 221)).toBe(5); + expect(dropPosition(MEASURED, 3, 307)).toBe(5); + expect(dropPosition(MEASURED, 3, 309)).toBe(6); + }); + + it("moves a tall row past a short neighbour once its centre passes that row's near edge", () => { + // Row 1 (88 pt) rests with its centre at 88; the 44 pt row below starts at + // 132, so the centre travels half the tall row before they change places. + const geometry = table([44, 88, 44, 44]); + expect(dropPosition(geometry, 1, 88)).toBe(1); + expect(dropPosition(geometry, 1, 89)).toBe(1); + expect(dropPosition(geometry, 1, 132)).toBe(1); + expect(dropPosition(geometry, 1, 132.5)).toBe(2); + // Up: past the 44 pt row above once the centre passes its bottom (44). + expect(dropPosition(geometry, 1, 44.5)).toBe(1); + expect(dropPosition(geometry, 1, 44)).toBe(0); + }); + + it('never proposes a new position at rest, whatever the heights', () => { + // More than twice the row below: a 100 pt row over 44 pt rows. + const tall = table([44, 100, 44, 44]); + expect(dropPosition(tall, 1, 44 + 50)).toBe(1); + expect(dropPosition(tall, 1, 144)).toBe(1); + expect(dropPosition(tall, 1, 144.5)).toBe(2); + for (const heights of [ + [44, 100, 44, 44], + [30, 120, 30, 30, 30], + [88, 44, 88, 44], + [44, 44, 200, 44], + ]) { + const geometry = table(heights, {gap: 4}); + for (const [index, row] of geometry.rows.entries()) { + expect( + dropPosition(geometry, index, row.top + row.height / 2), + `${heights.join(',')} row ${index}`, + ).toBe(index); + } + } + }); + + it('moves a short row up past a tall row above as it moves down past one below', () => { + // The mirror of the measured drag over the 88 pt row: row 7 (44 pt) below + // row 6 (88 pt, 264–352) changes places once its centre is above + // 264 + 44 = 308, the tall row's height less half its own from rest (374). + expect(dropPosition(MEASURED, 7, 374)).toBe(7); + expect(dropPosition(MEASURED, 7, 309)).toBe(7); + expect(dropPosition(MEASURED, 7, 308)).toBe(6); + }); + + it('puts the boundary in the middle of the gap between rows', () => { + const geometry = table([40, 40, 40], {gap: 4}); + // Without row 0, row 1 sits at 0..40; its boundary is at 42. + expect(dropPosition(geometry, 0, 42)).toBe(0); + expect(dropPosition(geometry, 0, 42.5)).toBe(1); + }); + + it('stops at a fixed row that ends the list and passes one in the middle', () => { + // spec:AST-103 FR1, FR4: only a rejected row at either end bounds the + // drop range; one in the middle is passed over, as reorder mode's keys + // pass it. + const ends = table([44, 44, 44, 44, 44], {fixed: [0, 4]}); + expect(dropPosition(ends, 2, 1000)).toBe(3); + expect(dropPosition(ends, 2, -1000)).toBe(1); + const middle = table([44, 44, 44, 44, 44], {fixed: [2]}); + expect(dropPosition(middle, 0, 1000)).toBe(4); + expect(dropPosition(middle, 4, -1000)).toBe(0); + }); +}); + +describe('movableRange', () => { + it('is bounded only by the fixed rows that end the list', () => { + // Runs of fixed rows at either end bound the range. + const {rows} = table([44, 44, 44, 44, 44, 44], {fixed: [0, 1, 5]}); + expect(movableRange(rows, 3)).toEqual({start: 2, end: 4}); + // A fixed row in the middle is passed over (spec:AST-103 FR1, FR4). + const middle = table([44, 44, 44, 44, 44, 44], {fixed: [1, 4]}).rows; + expect(movableRange(middle, 2)).toEqual({start: 0, end: 5}); + expect(movableRange(middle, 0)).toEqual({start: 0, end: 5}); + expect(movableRange(middle, 5)).toEqual({start: 0, end: 5}); + expect(movableRange(table([44, 44, 44]).rows, 1)).toEqual({ + start: 0, + end: 2, + }); + }); +}); + +describe('autoscrollStep', () => { + it('follows the measured steps by edge depth', () => { + expect(autoscrollStep(-12)).toBe(0); + expect(autoscrollStep(-reorder.autoscroll.startInset - 0.5)).toBe(0); + expect(autoscrollStep(-reorder.autoscroll.startInset)).toBe(2); + expect(autoscrollStep(-3)).toBe(2); + expect(autoscrollStep(6)).toBe(2); + expect(autoscrollStep(8)).toBe(3); + expect(autoscrollStep(10)).toBe(3); + expect(autoscrollStep(12)).toBe(4); + expect(autoscrollStep(16)).toBe(6); + expect(autoscrollStep(20)).toBe(8); + expect(autoscrollStep(22)).toBe(10); + expect(autoscrollStep(40)).toBe(10); + }); + + it('interpolates whole points between samples', () => { + expect(autoscrollStep(14)).toBe(5); + expect(autoscrollStep(21)).toBe(9); + for (let depth = -8; depth <= 30; depth += 0.25) { + expect(Number.isInteger(autoscrollStep(depth))).toBe(true); + } + }); +}); + +describe('clampTop', () => { + it("stops the centre on the scroller's visible edges", () => { + // The measured top clamp: a 44 pt row on a table starting at 62 stops at + // a top of 40 (its centre on the edge). + const bounds = { + scrollTop: 62, + scrollBottom: 800, + listTop: 0, + listBottom: 2000, + }; + expect(clampTop(0, 44, bounds)).toBe(40); + expect(clampTop(100, 44, bounds)).toBe(100); + expect(clampTop(900, 44, bounds)).toBe(778); + }); + + it('stops the edges on the ends of a list inside the visible area', () => { + // A list from 300 to 564 in a scroller showing 0–800: the row stays in it. + const bounds = { + scrollTop: 0, + scrollBottom: 800, + listTop: 300, + listBottom: 564, + }; + expect(clampTop(100, 44, bounds)).toBe(300); + expect(clampTop(400, 44, bounds)).toBe(400); + expect(clampTop(700, 44, bounds)).toBe(520); + }); + + it('takes whichever edge comes first', () => { + // The list runs past the visible bottom: the scroll edge stops the centre. + const bounds = { + scrollTop: 0, + scrollBottom: 800, + listTop: 300, + listBottom: 2000, + }; + expect(clampTop(900, 44, bounds)).toBe(778); + }); +}); + +describe('slotsOf', () => { + const slots = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + {x: 200, y: 20}, + ]; + + it('takes positions() when it gives one slot per item (spec:AST-103 FR1)', () => { + expect(slotsOf(() => slots, 3)).toEqual(slots); + }); + + it('ignores positions() whose length differs from the item count, or none', () => { + expect(slotsOf(() => slots.slice(0, 2), 3)).toBeNull(); + expect(slotsOf(undefined, 3)).toBeNull(); + }); +}); + +describe('nearestSlot', () => { + // A 3 x 2 grid of 80 x 40 slots. + const grid = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + {x: 200, y: 20}, + {x: 40, y: 60}, + {x: 120, y: 60}, + {x: 200, y: 60}, + ]; + const free = grid.map(() => ({isFixed: false})); + + it("proposes the slot whose centre is nearest the dragged item's centre (spec:AST-103 FR1)", () => { + expect(nearestSlot(grid, free, 0, {x: 125, y: 58})).toBe(4); + expect(nearestSlot(grid, free, 0, {x: 190, y: 25})).toBe(2); + // Where it started. + expect(nearestSlot(grid, free, 4, {x: 118, y: 61})).toBe(4); + }); + + it('stays within the drop range that fixed items at either end bound, and passes one in the middle', () => { + const fixedEnds = free.map((item, index) => + index === 0 || index === 5 ? {isFixed: true} : item, + ); + // Over the fixed first slot: the nearest slot in range is the one below. + expect(nearestSlot(grid, fixedEnds, 2, {x: 41, y: 19})).toBe(3); + // Over the fixed last slot: the nearest in range is the one above. + expect(nearestSlot(grid, fixedEnds, 1, {x: 199, y: 61})).toBe(2); + const fixedMiddle = free.map((item, index) => + index === 3 ? {isFixed: true} : item, + ); + expect(nearestSlot(grid, fixedMiddle, 0, {x: 41, y: 59})).toBe(3); + }); +}); + +describe('slotLine', () => { + // A row of three 60 x 40 cards, 80 px apart. + const row = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + {x: 200, y: 20}, + ]; + const card = {width: 60, height: 40}; + + it("is a list's line turned across the step: between the target slot and the next one along the drag, as long as the item is across", () => { + // From the first slot to the second: between the second and the third. + expect(slotLine(row, 0, 1, card)).toEqual({ + x: 160, + y: 20, + length: 40, + angle: 90, + }); + // Back from the third to the second: between the second and the first. + expect(slotLine(row, 2, 1, card)).toEqual({ + x: 80, + y: 20, + length: 40, + angle: 90, + }); + }); + + it("past the last slot, half a step beyond it; none at the item's own place", () => { + expect(slotLine(row, 0, 2, card)).toEqual({ + x: 240, + y: 20, + length: 40, + angle: 90, + }); + expect(slotLine(row, 1, 1, card)).toBeNull(); + }); + + it("in a column it is the list's line, across the item's width", () => { + const column = [ + {x: 150, y: 22}, + {x: 150, y: 66}, + {x: 150, y: 110}, + ]; + expect(slotLine(column, 0, 1, {width: 300, height: 44})).toEqual({ + x: 150, + y: 88, + length: 300, + angle: 0, + }); + }); +}); + +describe('slotLine in a wrapping grid', () => { + // Three 60 x 40 cards a row, 80 px apart, rows 60 px apart. + const grid = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + {x: 200, y: 20}, + {x: 40, y: 80}, + {x: 120, y: 80}, + {x: 200, y: 80}, + ]; + const card = {width: 60, height: 40}; + + it("at a row's end, stands half a step beyond the last card of that row, not between the rows", () => { + // Onto the end of the first row: after C, at its right edge. + expect(slotLine(grid, 0, 2, card)).toEqual({ + x: 240, + y: 20, + length: 40, + angle: 90, + }); + // Back onto the start of the second row: before D, at its left edge. + expect(slotLine(grid, 5, 3, card)).toEqual({ + x: 0, + y: 80, + length: 40, + angle: 90, + }); + }); +}); + +describe('stepLine', () => { + it("marks the leading edge of a key move's new slot, across the move", () => { + const card = {width: 60, height: 40}; + const row = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + ]; + const column = [ + {x: 40, y: 20}, + {x: 40, y: 80}, + ]; + // Right by one slot: the edge to the right of the new slot. + expect(stepLine(row, 0, 1, card)).toEqual({ + x: 160, + y: 20, + length: 40, + angle: 90, + }); + // Down by one row: the edge below the new slot. + expect(stepLine(column, 0, 1, card)).toEqual({ + x: 40, + y: 110, + length: 60, + angle: 0, + }); + }); + + it('after a move that wraps rows, marks the new slot along its row, inside the grid', () => { + const card = {width: 60, height: 40}; + const grid = [ + {x: 40, y: 20}, + {x: 120, y: 20}, + {x: 200, y: 20}, + {x: 40, y: 80}, + {x: 120, y: 80}, + {x: 200, y: 80}, + ]; + // Right from the end of the first row to the start of the second: the + // edge between the new slot and the next one in its row. + expect(stepLine(grid, 2, 3, card)).toEqual({ + x: 80, + y: 80, + length: 40, + angle: 90, + }); + // Left from the start of the second row to the end of the first. + expect(stepLine(grid, 3, 2, card)).toEqual({ + x: 160, + y: 20, + length: 40, + angle: 90, + }); + }); +}); diff --git a/packages/core/src/List/__tests__/rowPixels.ts b/packages/core/src/List/__tests__/rowPixels.ts new file mode 100644 index 0000000000000..63df62af88fca --- /dev/null +++ b/packages/core/src/List/__tests__/rowPixels.ts @@ -0,0 +1,280 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file rowPixels.ts + * @input Playwright pages and screencast frames from the interaction harness + * @output `samplePixel` (one point's value in every screencast frame) and + * WebKit's video evidence: `installBeacon`, `blockBehindBeacon` (a main-thread + * beacon that marks the frames presented while script could not run) and + * `sampleVideo` + * @position Test helper for the List interaction proofs (row press release, + * selection hold), which read a row's press strength from pixels + */ + +import {readFile} from 'node:fs/promises'; +import {chromium, type Page} from '@playwright/test'; +import type {CastFrame} from '@astryxdesign/interaction-harness'; + +export interface PixelFrame { + readonly t: number; + /** Mean of the RGB channels at the probe point, 0–255. */ + readonly value: number; +} + +/** + * The probe point's value in every frame. Decoding runs in a scratch page of + * the same browser (no image decoder in Node), like the harness's own marker + * tracking. + */ +export async function samplePixel( + page: Page, + frames: ReadonlyArray, + probe: {x: number; y: number}, +): Promise { + const scratch = await page.context().newPage(); + try { + const out: PixelFrame[] = []; + for (let i = 0; i < frames.length; i += 12) { + const batch = frames.slice(i, i + 12); + const values = await scratch.evaluate( + async ({items, at}) => { + const results: number[] = []; + for (const item of items) { + const bitmap = await createImageBitmap( + await ( + await fetch(`data:image/${item.format};base64,${item.data}`) + ).blob(), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + if (context == null) { + throw new Error('no 2d context'); + } + context.drawImage(bitmap, 0, 0); + const scale = bitmap.width / item.viewportWidth; + const px = context.getImageData( + Math.round(at.x * scale), + Math.round(at.y * scale), + 1, + 1, + ).data; + results.push((px[0] + px[1] + px[2]) / 3); + } + return results; + }, + { + items: batch.map(f => ({ + data: f.data, + format: f.format, + viewportWidth: f.viewportWidth, + })), + at: probe, + }, + ); + values.forEach((value, k) => out.push({t: batch[k].t, value})); + } + return out; + } finally { + await scratch.close(); + } +} + +/** The beacon's size, CSS px, in the viewport's bottom-right corner. */ +const BEACON = 40; + +/** + * Adds the main-thread beacon: a corner square the page paints grey, blue + * while it is about to block, and green once script runs again. A recorded + * frame showing blue was presented while script could not run. + */ +export async function installBeacon(page: Page): Promise { + await page.evaluate(size => { + const beacon = document.createElement('div'); + beacon.id = 'beacon'; + Object.assign(beacon.style, { + position: 'fixed', + right: '0', + bottom: '0', + width: `${size}px`, + height: `${size}px`, + background: 'rgb(128, 128, 128)', + zIndex: '2147483647', + }); + document.body.append(beacon); + }, BEACON); +} + +/** + * Paints the beacon blue, lets two frames commit it, blocks the main thread + * for `ms`, then paints it green. + */ +export async function blockBehindBeacon(page: Page, ms: number): Promise { + await page.evaluate( + async duration => + new Promise(resolve => { + const beacon = document.getElementById('beacon') as HTMLElement; + beacon.style.background = 'rgb(0, 0, 255)'; + requestAnimationFrame(() => + requestAnimationFrame(() => { + const end = performance.now() + duration; + while (performance.now() < end) { + // blocked + } + beacon.style.background = 'rgb(0, 200, 0)'; + resolve(); + }), + ); + }), + ms, + ); +} + +/** + * Arms the same block in the page for the next `event` (e.g. the lift's + * `touchend`): beacon blue, two frames, the block, beacon green. Armed in + * the page, the block starts two frames after the event with no + * test-runner round trip in between, so a short motion cannot finish first. + */ +export async function blockBehindBeaconOn( + page: Page, + event: string, + ms: number, +): Promise { + await page.evaluate( + ({type, duration}) => { + addEventListener( + type, + () => { + const beacon = document.getElementById('beacon') as HTMLElement; + beacon.style.background = 'rgb(0, 0, 255)'; + requestAnimationFrame(() => + requestAnimationFrame(() => { + const end = performance.now() + duration; + while (performance.now() < end) { + // blocked + } + beacon.style.background = 'rgb(0, 200, 0)'; + }), + ); + }, + {once: true, passive: true, capture: true}, + ); + }, + {type: event, duration: ms}, + ); +} + +export interface VideoSample { + /** Video time, s. */ + readonly t: number; + /** Mean of the RGB channels at the probe point, 0–255. */ + readonly value: number; + readonly beacon: 'before' | 'blocked' | 'after'; +} + +/** + * The probe point's value and the beacon's state every 10 ms of a recorded + * video (Playwright's `recordVideo`, WebKit's frame evidence), decoded in a + * Chromium page. + */ +export async function sampleVideo( + videoPath: string, + probe: {x: number; y: number}, + viewport: {width: number; height: number}, +): Promise { + const frames = await sampleVideoPoints(videoPath, [probe], viewport); + return frames.map(({t, values, beacon}) => ({t, value: values[0], beacon})); +} + +export interface VideoPointsSample { + /** Video time, s. */ + readonly t: number; + /** Mean of the RGB channels at each probe, 0–255, in the probes' order. */ + readonly values: ReadonlyArray; + /** Whether each probe shows the harness marker colour (magenta). */ + readonly marker: ReadonlyArray; + readonly beacon: 'before' | 'blocked' | 'after'; +} + +/** + * Like `sampleVideo`, at several probe points per frame: a marker moving + * through them reads as the index of the probe it covers. + */ +export async function sampleVideoPoints( + videoPath: string, + probes: ReadonlyArray<{x: number; y: number}>, + viewport: {width: number; height: number}, +): Promise { + const webm = (await readFile(videoPath)).toString('base64'); + const decoder = await chromium.launch(); + try { + const player = await decoder.newPage(); + return await player.evaluate( + async ({points, data, beaconAt}) => { + const element = document.createElement('video'); + element.muted = true; + element.src = URL.createObjectURL( + new Blob([Uint8Array.from(atob(data), c => c.charCodeAt(0))], { + type: 'video/webm', + }), + ); + document.body.append(element); + if (element.readyState < 1) { + await new Promise(r => + element.addEventListener('loadedmetadata', r, {once: true}), + ); + } + element.pause(); + const canvas = document.createElement('canvas'); + canvas.width = element.videoWidth; + canvas.height = element.videoHeight; + const context2d = canvas.getContext('2d', { + willReadFrequently: true, + }) as CanvasRenderingContext2D; + const out: { + t: number; + values: number[]; + marker: boolean[]; + beacon: 'before' | 'blocked' | 'after'; + }[] = []; + const duration = Number.isFinite(element.duration) + ? element.duration + : 10; + for (let t = 0; t < duration; t += 0.01) { + element.currentTime = t; + await new Promise(r => + element.addEventListener('seeked', r, {once: true}), + ); + context2d.drawImage(element, 0, 0); + const pixels = points.map( + p => context2d.getImageData(p.x, p.y, 1, 1).data, + ); + const b = context2d.getImageData(beaconAt.x, beaconAt.y, 1, 1).data; + const beacon = + b[2] > 180 && b[0] < 80 + ? 'blocked' + : b[1] > 150 && b[2] < 80 + ? 'after' + : 'before'; + out.push({ + t, + values: pixels.map(px => (px[0] + px[1] + px[2]) / 3), + marker: pixels.map(px => px[0] > 200 && px[1] < 80 && px[2] > 200), + beacon, + }); + } + return out; + }, + { + points: probes, + data: webm, + beaconAt: { + x: viewport.width - BEACON / 2, + y: viewport.height - BEACON / 2, + }, + }, + ); + } finally { + await decoder.close(); + } +} diff --git a/packages/core/src/List/__tests__/touchStory.ts b/packages/core/src/List/__tests__/touchStory.ts new file mode 100644 index 0000000000000..e33cdd9f32111 --- /dev/null +++ b/packages/core/src/List/__tests__/touchStory.ts @@ -0,0 +1,44 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file touchStory.ts + * @input Playwright's Page and a built Storybook's origin + * @output `openStory(page, origin, storyId, options)`: opens a story and + * waits for its first rows, its fonts and two frames + * @position Shared helper for the list specs. Their behaviour is the one + * touch model under any finger (TOUCH_QUERY in utils/touchPresentation.ts): + * the projects' contexts already have the finger, and nothing is emulated, + * so Chromium shows it as Android's engine does and WebKit as Safari's. A + * mouse case opens its own context without touch. + * + * SYNC: When modified, update the specs that import it. + */ + +import type {Page} from '@playwright/test'; + +/** + * Opens a story and waits for its first rows, its fonts and two frames. + * `globals`: Storybook globals such as `direction:rtl`. + */ +export async function openStory( + page: Page, + origin: string, + storyId: string, + {globals}: {globals?: string} = {}, +): Promise { + const params = new URLSearchParams({id: storyId, viewMode: 'story'}); + if (globals != null) { + params.set('globals', globals); + } + await page.goto(`${origin}/iframe.html?${params.toString()}`); + await page + .locator('#storybook-root > *') + .first() + .waitFor({state: 'attached'}); + await page.evaluate(async () => { + await document.fonts.ready; + await new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + }); +} diff --git a/packages/core/src/List/listReorderAttach.tsx b/packages/core/src/List/listReorderAttach.tsx new file mode 100644 index 0000000000000..cad5377cf01b4 --- /dev/null +++ b/packages/core/src/List/listReorderAttach.tsx @@ -0,0 +1,531 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file listReorderAttach.tsx + * @input A reorderable object's options, a container of plain elements and + * its `items()`, and List's reorder machinery (List/listReorderEngine.tsx: + * the session, its strings and its hint) + * @output `attachReorder`, the work behind createReorderable's `attach`: the + * container's items reorder as a List's rows do, with no collection + * component (spec:AST-103 FR4b) + * @position List internals; reorderable/createReorderable.ts runs it. + * Nothing happens until it runs: creating or importing the object does no + * DOM work + * + * Each reorderable item's handle becomes reorder mode's toggle: a button + * named "Reorder" and the item's name (its element's accessible name, else + * its text), pressed while its item is in reorder mode, in the Tab order; a + * rejected or keyless item's handle is hidden (spec:AST-103 FR1, DEC-2). The + * container gets the drag and reorder mode of List's session, through + * listeners on the container, never on each handle (FR5). A move commits + * once `items()` reports the new order after `onReorder`: a change anywhere + * under the container, or the end of the task. Announcements go through the + * shared polite channel (hooks/useAnnounce.ts), inside the modal dialog that + * encloses the container when one does (`spec:AST-086` FR14), in the shipped + * English catalog (`architecture:internationalization` INV3). The pointers + * follow the primary pointer turning coarse or fine. `detach` ends a drag or + * reorder mode calling nothing, removes every listener, observer and element + * it added, and restores each handle's own attributes. + * + * Known limit: reorder mode's hint renders in a React root of its own, right + * after the container, so it takes the theme around the container but not + * the providers of an app's React tree, nor a theme set on the container + * itself. + * + * SYNC: When modified, update reorderable/createReorderable.ts and + * reorderable/createReorderable.doc.mjs. + */ + +import * as stylex from '@stylexjs/stylex'; +import type {Root} from 'react-dom/client'; +import { + announceInModal, + announceMessage, + enclosingModalDialog, + type AnnouncePoliteness, +} from '../hooks/useAnnounce'; +import {getResolve} from '../i18n/resolve'; +import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer'; +import {devWarn} from '../utils/devWarning'; +import {reorderLineElementStyle} from './ListReorderHandle'; +import {HANDLE_ATTRIBUTE, type ListReorderOptions} from './listReorderContext'; +import {GHOST_ATTRIBUTE} from './useListUpdateMotion'; +import { + LINE_ATTRIBUTE, + ListReorderController, + ListReorderModeHint, + messagesFrom, + mountSession, +} from './listReorderEngine'; + +/** One attached item: its key, its element, and the handle that moves it. */ +export interface AttachedItem { + /** The key its moves report; an item without one cannot move. */ + readonly key?: string | number | null; + readonly element: HTMLElement; + readonly handle: HTMLElement; +} + +/** The handle attributes attach writes, put back as they were by `detach`. */ +const HANDLE_ATTRIBUTES = [ + 'role', + 'aria-pressed', + 'aria-label', + 'aria-labelledby', + 'aria-describedby', + 'tabindex', + HANDLE_ATTRIBUTE, +] as const; + +let attachedCount = 0; + +/** + * What an attached item is called, in the accessible-name order: + * `aria-labelledby`, then `aria-label`, then `title`, then its text. + */ +function nameOf(element: HTMLElement): string { + const labelledBy = element.getAttribute('aria-labelledby'); + if (labelledBy != null) { + const text = labelledBy + .split(/\s+/) + .map(id => element.ownerDocument.getElementById(id)?.textContent ?? '') + .join(' ') + .trim(); + if (text !== '') { + return text; + } + } + for (const attribute of ['aria-label', 'title']) { + const value = element.getAttribute(attribute)?.trim(); + if (value != null && value !== '') { + return value; + } + } + return element.textContent?.trim() ?? ''; +} + +/** A native control activates on Enter and Space by itself. */ +function isNativeControl(element: HTMLElement): boolean { + return ( + element instanceof HTMLButtonElement || element instanceof HTMLInputElement + ); +} + +/** + * Attaches `options`' reorder to `container`'s items (spec:AST-103 FR4b); + * returns its `detach`. + */ +export function attachReorder( + options: ListReorderOptions, + container: HTMLElement, + items: () => ReadonlyArray, +): {detach: () => void} { + const doc = container.ownerDocument; + const translate = getResolve('en', {}); + // The app's items without the reorder's own copies: a query over the + // container also finds the drag's preview, a copy of an item, which holds + // no place in the order. + const ownItems = () => + items().filter( + item => item.element.closest(`[${GHOST_ATTRIBUTE}]`) == null, + ); + attachedCount += 1; + const hintId = `astryx-reorder-attached-${attachedCount}`; + const controller = new ListReorderController( + () => container, + hintId, + () => ownItems().map(item => item.element), + ); + // Right after the container, in its theme scope (and inside the modal + // dialog that encloses it): the handles' instructions and reorder mode's + // hint, as List renders them after its list. No layout box. Block + // elements, so the hint's layer renders in place rather than moving out of + // phrasing content to a safe host (Layer/layerHost.ts). + const hintHost = doc.createElement('div'); + hintHost.setAttribute('data-astryx-reorder-hint-host', ''); + hintHost.style.display = 'contents'; + const instructions = doc.createElement('span'); + instructions.id = hintId; + instructions.hidden = true; + instructions.textContent = translate('@astryx.list.reorderHint', undefined); + const hintRoot = doc.createElement('div'); + hintRoot.style.display = 'contents'; + hintHost.append(instructions, hintRoot); + if (container.parentNode != null) { + container.after(hintHost); + } else { + doc.body.append(hintHost); + } + // The shared polite channel, which joins a frame's messages and keeps a + // repeat once, inside the enclosing modal dialog when there is one + // (spec:AST-103 FR4, spec:AST-086 FR14). + const announce = ( + message: string, + politeness: AnnouncePoliteness = 'polite', + ) => { + const dialog = enclosingModalDialog(container); + if (dialog != null) { + announceInModal(dialog, message, politeness); + } else { + announceMessage(message, politeness); + } + }; + let commitQueued = false; + /** The move waiting for its commit, whose handle then takes the focus. */ + let moved: {key: string | number; to: number} | null = null; + let movedTimer: ReturnType | null = null; + // Once a move commits, the moved item's handle as items() now returns it + // takes the focus and scrolls into view, however the app moved or + // rendered the item (spec:AST-103 FR4b). + const focusMoved = () => { + if (moved == null) { + return; + } + const {key, to} = moved; + const current = ownItems(); + if (current.findIndex(item => item.key === key) !== to) { + return; + } + moved = null; + const {element, handle} = current[to]; + handle.focus({preventScroll: true}); + element.scrollIntoView?.({block: 'nearest', inline: 'nearest'}); + }; + // A move commits once items() reports the new order: right after + // onReorder returns, or when the container's children change. + const queueCommit = () => { + if (commitQueued) { + return; + } + commitQueued = true; + queueMicrotask(() => { + commitQueued = false; + if (!isAttached) { + return; + } + wire(); + controller.commit(); + focusMoved(); + }); + }; + const sessionOptions: ListReorderOptions = { + ...options, + onReorder: move => { + moved = {key: move.key as string | number, to: move.to}; + // A move not applied by the end of its task is refused (the + // controller announces it): its handle takes no focus later. + if (movedTimer != null) { + clearTimeout(movedTimer); + } + movedTimer = setTimeout(() => { + movedTimer = null; + moved = null; + }, 0); + options.onReorder(move); + queueCommit(); + }, + }; + let isCoarse = isCoarsePointer(doc.defaultView); + controller.refusal = 'not-moved'; + const configure = () => { + controller.configure({ + options: sessionOptions, + announce, + messages: messagesFrom(translate), + presentation: isCoarse ? 'uikit' : 'theme', + }); + }; + configure(); + + // --- Handles ----------------------------------------------------------- + + /** + * Each item that stays (rejected or keyless): its handle shows no grip + * (hidden, unless the handle is the item itself) and its name is + * registered for the announcements, such as a refusal past it. The release + * puts both back. + */ + const stillItems = new Map void>(); + const keepStill = (element: HTMLElement, handle: HTMLElement) => { + if (stillItems.has(element)) { + return; + } + const unregister = controller.registerName(element, nameOf(element)); + const hides = handle !== element && !handle.hidden; + if (hides) { + handle.hidden = true; + } + stillItems.set(element, () => { + unregister(); + if (hides) { + handle.hidden = false; + } + }); + }; + const releaseStill = (element: HTMLElement) => { + stillItems.get(element)?.(); + stillItems.delete(element); + }; + + /** Each wired handle: its item's key and element, and its unwiring. */ + const wired = new Map< + HTMLElement, + {key: string | number; element: HTMLElement; unwire: () => void} + >(); + let warnedUnnamed = false; + const wireHandle = ( + handle: HTMLElement, + key: string | number, + element: HTMLElement, + ) => { + const saved = HANDLE_ATTRIBUTES.map( + name => [name, handle.getAttribute(name)] as const, + ); + const savedTouchAction = handle.style.touchAction; + const name = nameOf(element); + if (name === '' && !warnedUnnamed) { + warnedUnnamed = true; + devWarn( + 'createReorderable', + '`attach`: an item has no accessible name and no text, so its ' + + 'handle and announcements cannot name it.', + ); + } + handle.setAttribute('role', 'button'); + handle.setAttribute('aria-pressed', String(controller.isInMode(handle))); + handle.setAttribute( + 'aria-label', + translate('@astryx.list.reorderHandle', {label: name}), + ); + handle.removeAttribute('aria-labelledby'); + handle.setAttribute('aria-describedby', hintId); + handle.setAttribute('tabindex', '0'); + handle.setAttribute(HANDLE_ATTRIBUTE, ''); + // Where the primary pointer is coarse the page keeps its pan until the + // hold claims the finger (a flick scrolls); where it is fine, no pan, so + // a pen drags the item at once (spec:AST-094 FR18, FR43). + handle.style.touchAction = isCoarse ? 'manipulation' : 'none'; + const unregister = controller.registerHandle(handle, key, name); + wired.set(handle, { + key, + element, + unwire: () => { + unregister(); + for (const [attribute, value] of saved) { + if (value == null) { + handle.removeAttribute(attribute); + } else { + handle.setAttribute(attribute, value); + } + } + handle.style.touchAction = savedTouchAction; + if (handle.getAttribute('style') === '') { + handle.removeAttribute('style'); + } + }, + }); + }; + // Wires each reorderable item's handle and unwires the handles of items + // that left or stopped being reorderable. An item the app rendered anew + // (its key on new elements) takes its old elements' place in the session + // first, so reorder mode and the focus follow it. + const wire = () => { + const kept = new Set(); + const still = new Set(); + const fresh: { + key: string | number; + element: HTMLElement; + handle: HTMLElement; + }[] = []; + for (const {key, element, handle} of ownItems()) { + if (key == null || sessionOptions.isReorderable?.(key) === false) { + keepStill(element, handle); + still.add(element); + continue; + } + releaseStill(element); + kept.add(handle); + if (!wired.has(handle)) { + wireHandle(handle, key, element); + fresh.push({key, element, handle}); + } + } + const gone = [...wired].filter(([handle]) => !kept.has(handle)); + if (fresh.length > 0 && gone.length > 0) { + const rows = new Map(); + const handles = new Map(); + for (const item of fresh) { + const old = gone.find(([, entry]) => entry.key === item.key); + if (old != null) { + rows.set(old[1].element, item.element); + handles.set(old[0], item.handle); + } + } + if (rows.size > 0) { + controller.adoptElements(rows, handles); + } + } + for (const [handle, entry] of gone) { + entry.unwire(); + wired.delete(handle); + } + for (const element of [...stillItems.keys()]) { + if (!still.has(element)) { + releaseStill(element); + } + } + }; + let isAttached = true; + wire(); + const unsubscribe = controller.subscribeMode(() => { + for (const handle of wired.keys()) { + handle.setAttribute('aria-pressed', String(controller.isInMode(handle))); + } + }); + + // --- Listeners, the hint, `start` ---------------------------------------- + + // Every pointer (spec:AST-094 FR43), following the primary pointer as it + // turns coarse or fine (a tablet docking a mouse): the session's pointer + // listeners, the handles' touch-action and the motion. + let detachPointers = controller.attachPointers(isCoarse); + const unwatchPointer = watchCoarsePointer(doc.defaultView, next => { + if (next === isCoarse) { + return; + } + isCoarse = next; + detachPointers(); + detachPointers = controller.attachPointers(isCoarse); + configure(); + for (const handle of wired.keys()) { + handle.style.touchAction = isCoarse ? 'manipulation' : 'none'; + } + }); + // A handle's click, key and focus leaving, delegated from the container + // (spec:AST-103 FR5, spec:AST-094 FR24). + const handleOf = (target: EventTarget | null): HTMLElement | null => { + if (!(target instanceof Element)) { + return null; + } + const handle = target.closest(`[${HANDLE_ATTRIBUTE}]`); + return handle != null && wired.has(handle) ? handle : null; + }; + const onClick = (event: MouseEvent) => { + const handle = handleOf(event.target); + if (handle != null && !controller.takeDrag(handle)) { + controller.toggleMode(handle); + } + }; + const onKeyDown = (event: KeyboardEvent) => { + const handle = handleOf(event.target); + if (handle == null) { + return; + } + // A button's Enter and Space, for a handle that is not one. + if ( + !isNativeControl(handle) && + (event.key === 'Enter' || event.key === ' ') && + !event.altKey && + !event.ctrlKey && + !event.metaKey + ) { + event.preventDefault(); + controller.toggleMode(handle); + return; + } + controller.keyDown(handle, event); + }; + const onFocusOut = (event: FocusEvent) => { + const handle = handleOf(event.target); + if (handle != null) { + controller.blur(handle, event.relatedTarget); + } + }; + container.addEventListener('click', onClick); + container.addEventListener('keydown', onKeyDown); + container.addEventListener('focusout', onFocusOut); + // `start(key)` reaches this container's items (FR4a), the latest attached. + const unmountSession = mountSession(options, controller); + // Anywhere under the container: items nested in a wrapper the app + // reorders count too. + const observer = new MutationObserver(queueCommit); + observer.observe(container, {childList: true, subtree: true}); + // The insertion line: a container of plain elements carries no List + // style, so attach draws the line as an element of its own, in the + // container while the line shows (the session marks the container), placed + // by the same custom properties as a List's. + const line = doc.createElement('span'); + line.setAttribute('aria-hidden', 'true'); + line.setAttribute(GHOST_ATTRIBUTE, ''); + line.setAttribute('data-astryx-reorder-line-element', ''); + line.inert = true; + line.className = stylex.props(reorderLineElementStyle).className ?? ''; + const syncLine = () => { + if (container.hasAttribute(LINE_ATTRIBUTE)) { + if (line.parentNode !== container) { + container.append(line); + } + } else { + line.remove(); + } + }; + const lineObserver = new MutationObserver(syncLine); + lineObserver.observe(container, { + attributes: true, + attributeFilter: [LINE_ATTRIBUTE], + }); + // Reorder mode's hint, rendered as a List's, in an element this attach + // owns right after the container. Its renderer loads when attach runs, not + // with the import: a page that never attaches never loads it, and a React + // page already has it. A mode that starts before it loads (a `start` right + // after attach) shows its hint once it has. + let root: Root | null = null; + void import('react-dom/client').then(({createRoot}) => { + if (!isAttached) { + return; + } + root = createRoot(hintRoot); + root.render(); + }); + + return { + detach: () => { + if (!isAttached) { + return; + } + isAttached = false; + controller.dispose(); + observer.disconnect(); + lineObserver.disconnect(); + line.remove(); + unsubscribe(); + unwatchPointer(); + detachPointers(); + container.removeEventListener('click', onClick); + container.removeEventListener('keydown', onKeyDown); + container.removeEventListener('focusout', onFocusOut); + unmountSession(); + for (const entry of wired.values()) { + entry.unwire(); + } + wired.clear(); + for (const element of [...stillItems.keys()]) { + releaseStill(element); + } + if (movedTimer != null) { + clearTimeout(movedTimer); + } + hintHost.remove(); + // After the current task's rendering: React reports an unmount run + // synchronously inside another root's effect cleanup, where an app + // usually calls detach. + const rendered = root; + root = null; + if (rendered != null) { + queueMicrotask(() => rendered.unmount()); + } + }, + }; +} diff --git a/packages/core/src/List/listReorderContext.ts b/packages/core/src/List/listReorderContext.ts new file mode 100644 index 0000000000000..e9e2219c38f53 --- /dev/null +++ b/packages/core/src/List/listReorderContext.ts @@ -0,0 +1,159 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file listReorderContext.ts + * @input Nothing at run time but a symbol + * @output `REORDER_ENGINE`, the key a reorderable object carries its + * machinery under, the attributes the machinery marks the DOM with, and + * the internal types between List, ListItem and that machinery (what a + * List hands its rows through ListContext's `reorder`) + * @position Internal to List. List imports only this module and the + * reorderable object's type, and ListItem only types, so a List without + * `reorderable` loads no reorder code (spec:AST-103 FR2): the machinery + * (List/listReorderEngine.tsx) ships with createReorderable + * (reorderable/createReorderable.ts), which puts it on the object. + * + * SYNC: When modified, update List/List.tsx, List/ListItem.tsx, + * List/ListContext.tsx, List/listReorderEngine.tsx and + * reorderable/createReorderable.ts. + */ + +import type {ItemAlign} from '../Item/Item'; +import type {ComponentType, Key, ReactNode, RefObject} from 'react'; +import type {StyleXStyles} from '@stylexjs/stylex'; +import type {reorderListStyle} from './ListReorderHandle'; + +/** + * The key a reorderable object carries its machinery under. No description: + * it would ship in every List (spec:AST-103 FR2). + */ +export const REORDER_ENGINE: unique symbol = Symbol(); + +/** On the list root while a drag session owns its rows. */ +export const REORDERING_ATTRIBUTE = 'data-astryx-reordering'; +/** On each row's reorder handle. */ +export const HANDLE_ATTRIBUTE = 'data-astryx-list-reorder'; + +/** What a List's reorder reports and asks, as createReorderable took them. */ +export interface ListReorderOptions { + /** Called once per committed move: the item's key and its index after it. */ + readonly onReorder: (move: {key: Key; to: number}) => void; + /** Whether the item with `key` moves; every item does without it. */ + readonly isReorderable?: (key: Key) => boolean; + /** + * Each item's slot centre, in px from the top-left of the container's + * padding box (spec:AST-103 FR1): a drag proposes the nearest slot. + */ + readonly positions?: () => ReadonlyArray<{ + readonly x: number; + readonly y: number; + }>; +} + +/** The handle a reorderable row ends with (List/ListReorderHandle.tsx). */ +export interface ListReorderHandleProps { + /** The row's label: its text names the handle. */ + readonly label: ReactNode; + /** The row's item key (ListItem `itemKey`), which its moves report. */ + readonly itemKey: Key; + /** + * The row's own accessible name, when its caller gave one (ListItem + * `aria-label`): the handle is "Reorder" followed by it. + */ + readonly rowLabel?: string; + /** + * The elements that name the row, when its caller gave them (ListItem + * `aria-labelledby`): the handle is "Reorder" followed by them. + */ + readonly rowLabelledBy?: string; + /** + * The row is disabled: the handle stays focusable with + * `aria-disabled="true"`, and no gesture or key moves the row + * (spec:AST-085). + */ + readonly isDisabled?: boolean; + /** + * The row's alignment (ListItem `align`) when the handle is the row's own + * child, after its label: a row without end content, which has no end slot + * to align it (spec:AST-103 FR5). Absent inside the end slot. + */ + readonly rowAlign?: ItemAlign; +} + +/** + * A reorderable List's row without a handle: its label names it in the + * announcements of the moves beside it (List/ListReorderHandle.tsx). + */ +export interface ListReorderRowNameProps { + /** The row's element. */ + readonly row: RefObject; + /** The row's label. */ + readonly label: ReactNode; +} + +/** The parts of a List's reorder session that its List and rows use. */ +export interface ListReorderSession { + /** + * After every List commit, after the List's update motion: a drop's new + * order is applied, so each row's old place is put back and its running + * spring continues to the new one. + */ + commit(): void; + /** + * Rendered by the List beside its rows while it reorders: keeps the + * session's callbacks, strings and listeners current, renders the handles' + * instructions, and disposes of the session when it goes. + */ + readonly Host: ComponentType<{reorder: ListReorderContextValue}>; + /** The handle each reorderable row ends with. */ + readonly Handle: ComponentType; + /** Names a row without a handle for the announcements; renders nothing. */ + readonly RowName: ComponentType; + /** A row with a handle: its focus ring stays off for the handle's own. */ + readonly rowStyle: StyleXStyles; + /** The list itself: its insertion line, a pseudo-element. */ + readonly listStyle: typeof reorderListStyle; +} + +/** The machinery a reorderable object carries. */ +export interface ListReorderEngine { + /** A List's reorder session over the rows of the element `getList` returns. */ + createSession( + getList: () => HTMLElement | null, + hintId: string, + ): ListReorderSession; + /** + * Reorder mode for the item with `key`, started from the app's own UI, in + * the collection the object with `options` is mounted on (the one mounted + * last, if several). + */ + start(options: ListReorderOptions, key: Key): void; +} + +/** What a reorderable object holds (reorderable/createReorderable.ts). */ +export interface ReorderableInternals { + readonly options: ListReorderOptions; + readonly [REORDER_ENGINE]: ListReorderEngine; + /** Reorder mode for the item with `key`, from the app's own UI. */ + start(key: Key): void; + /** The reorder on a container of plain elements (spec:AST-103 FR4b). */ + attach( + container: HTMLElement, + options: {readonly items: () => ReadonlyArray}, + ): {detach: () => void}; +} + +/** One plain element `attach` reorders: its key, element and handle. */ +export interface ReorderableAttachedItem { + readonly key?: string | number | null; + readonly element: HTMLElement; + readonly handle: HTMLElement; +} + +/** What a reorderable List hands its rows. */ +export interface ListReorderContextValue { + readonly session: ListReorderSession; + readonly options: ListReorderOptions; +} diff --git a/packages/core/src/List/listReorderEngine.tsx b/packages/core/src/List/listReorderEngine.tsx new file mode 100644 index 0000000000000..726d645ddf9e7 --- /dev/null +++ b/packages/core/src/List/listReorderEngine.tsx @@ -0,0 +1,2573 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file listReorderEngine.tsx + * @input A List's element and its reorderable object's options + * (reorderable/createReorderable.ts, through List/listReorderContext.ts), + * the reorder model (List/reorderModel.ts), the reorder's touch layer + * (List/ListReorderTouch.ts: the hold and UIKit's motion), the row moves + * of utils/rowMotion.ts, the shared edge autoscroll + * (utils/edgeAutoscroll.ts), the touch presentation + * (utils/touchPresentation.ts), the shared announcer, and the anchored hint + * Core's keyboard hints share (hooks/anchoredHint.tsx) + * @output `listReorderEngine`, the machinery a reorderable object carries: + * the reorder session of a List, its Host and its handle. A drag from a + * handle leaves the rows in place: the row dims where it is, a preview of + * it follows the pointer, an insertion line marks where it would land, and + * the list autoscrolls near the scroll edges; the drop reports the move + * once and the rows rearrange, the dragged one gliding from where its + * preview was. A cancelled drag restores everything at once. Activating a handle without + * a drag (a click, Space or Enter) turns on reorder mode for its row: each + * arrow moves it a place at once (one report each), announced with its + * place and neighbours, and Escape or another activation ends the mode, + * keeping the moves. While the mode is on, a hint anchored to the handle + * shows the moves and Done as buttons that do what the keys do + * @position Internal to the reorder (spec:AST-103): only createReorderable + * imports it, so a List without `reorderable` loads none of it (FR2); + * ListReorderHandle drives it from each row's handle + * + * The drag's look is design:ordered-collection-reordering's: the surrounding + * rows stay still until the drop, the source is dimmed in place, a preview + * follows the pointer one to one (its centre stopping at the scroll view's + * edges) and an accent insertion line, shared by pointer and keyboard, + * marks the candidate position. UIKit's edit-mode reorder (iOS 26.2, + * measured) supplies the clocks: the hold, the rows' glide to their new + * places on the table spring after the drop, and autoscroll, a 20 ms timer + * whose step grows with how far the preview's edge is past the scroll edge. + * With a mouse (the theme's presentation) or Reduce Motion the rows jump to + * their new places. + * + * HOW IT RUNS. Everything after the drag begins is imperative: no React + * render and no layout read until the drop. The begin reads each row's + * layout once; each move writes one `translate` on the preview (the shared + * per-element animator's `set`), and a position change writes one on the + * insertion line. The list root carries + * `data-astryx-reordering` from the begin until the commit that applies the + * drop, so the List's update motion (useListUpdateMotion) leaves that commit + * to the reorder: after it, each row's old layout place (the dragged row's, + * where its preview was dropped) is put back with an inverse offset that + * glides to 0. If `onReorder` does not commit a new order by the end of the + * task, nothing has moved and nothing does. Reorder mode (spec:AST-103 FR4) + * reports each key's move at once; once it commits, under a finger's + * presentation, the rows slide from their old places to their new ones. + * The listeners are the list's, not each row's (FR5): one pointerdown + * listener for a mouse and, where the primary pointer is coarse, one hold + * recognizer that receives only the touches that begin on this list's + * handles. A row moves when it holds a handle registered here (with its + * item key); the others keep their places, and those at either end bound + * the rest. What runs only on a touch screen (the hold, the springs) is in + * ListReorderTouch.ts, imported here alone. + * + * SYNC: When modified, update List/listReorderContext.ts, List/List.tsx, + * List/ListReorderHandle.tsx, List/ListReorderTouch.ts and + * List/__tests__/ListReorder.interaction.browser.spec.ts. + */ + +import { + useRef, + useSyncExternalStore, + type Key, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + useAnnounce, + type AnnounceFn, + type AnnouncePoliteness, +} from '../hooks/useAnnounce'; +import {useTranslator, type TranslatorFn} from '../i18n/useTranslator'; +import {useLayer} from '../Layer/useLayer'; +import {useLayerDismissal} from '../Layer/useLayerDismissal'; +import {Kbd} from '../Kbd'; +import {anchoredHintStyles, renderAnchoredHint} from '../hooks/anchoredHint'; +import {colorVars, fontWeightVars, spacingVars} from '../theme/tokens.stylex'; +import {focusOutlineProps} from '../utils/focusOutline.stylex'; +import type {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer'; +import {VelocityTracker} from '../gestures/VelocityTracker'; +import {reorder} from '../motion/uikit/reorder'; +import { + animatorFor, + isMoving, + motionNow, + motionOf, + releaseMotion, +} from '../utils/rowMotion'; +import {edgeAutoscroll, type EdgeAutoscroll} from '../utils/edgeAutoscroll'; +import {isPrimaryClick} from '../utils/primaryClick'; +import {useTouchPresentation} from '../utils/touchPresentation'; +import {watchHitArea, writeHitInsets} from '../utils/hitArea'; +import {devWarn} from '../utils/devWarning'; +import {GHOST_ATTRIBUTE} from './useListUpdateMotion'; +import { + INSERTION_LINE_THICKNESS, + ListReorderHandle, + ListReorderRowName, + reorderListStyle, + reorderRowStyle, +} from './ListReorderHandle'; +import {attachTouchHold, touchMotion} from './ListReorderTouch'; +import { + HANDLE_ATTRIBUTE, + REORDERING_ATTRIBUTE, + type ListReorderContextValue, + type ListReorderEngine, + type ListReorderOptions, + type ListReorderSession, +} from './listReorderContext'; +import { + arrowTarget, + autoscrollStep, + cellOf, + clampTop, + dropPosition, + gridOf, + nearestSlot, + type ReorderArrow, + type ReorderGeometry, + type ReorderLine, + type ReorderSlot, + slotLine, + slotsOf, + stepLine, +} from './reorderModel'; + +/** + * A mouse's travel, in px, before its press drags the row: below it the + * press stays a click. A mouse shifts a pixel or two under the press of the + * button itself. The date wheel's mouse drag uses the same value + * (DateInput/usePointerDragScroll.ts `DRAG_SLOP`); a test keeps them equal. + */ +export const MOUSE_DRAG_SLOP = 4; + +/** Moves under half a pixel are layout noise. */ +const MIN_MOVE_PX = 0.5; + +/** + * How long after `start` the handle takes back the focus the UI that + * started the mode hands back, in ms: a menu restores its trigger's focus + * as it closes, within a task or two; no person moves the focus that fast. + */ +const START_FOCUS_CLAIM_MS = 150; + +/** + * The sessions each reorderable object (by its options) is mounted on, in + * the order they mounted: `start` uses the last (spec:AST-103 FR1, FR4a). + */ +const sessionsByOptions = new WeakMap< + ListReorderOptions, + ListReorderController[] +>(); + +/** Records `controller` as mounted with `options`; returns the removal. */ +export function mountSession( + options: ListReorderOptions, + controller: ListReorderController, +): () => void { + const sessions = sessionsByOptions.get(options) ?? []; + sessionsByOptions.set(options, [ + ...sessions.filter(session => session !== controller), + controller, + ]); + return () => { + const rest = (sessionsByOptions.get(options) ?? []).filter( + session => session !== controller, + ); + if (rest.length > 0) { + sessionsByOptions.set(options, rest); + } else { + sessionsByOptions.delete(options); + } + }; +} + +/** + * Where a row's `y` is on screen at `at`: its shared animator's value, which + * the drag writes directly (`set`) as well as through springs. + */ +function shownY(element: HTMLElement, at: number): number { + return animatorFor(element).get('y', at); +} + +/** Its `x` on screen at `at`, which a `positions()` layout moves. */ +function shownX(element: HTMLElement, at: number): number { + return animatorFor(element).get('x', at); +} + +/** + * The list's rows: its element children, without the ghost of a removed row + * still collapsing (the update motion's, `GHOST_ATTRIBUTE`), which holds no + * place in the order. + */ +function rowsOf(list: HTMLElement): HTMLElement[] { + return Array.from(list.children).filter( + (child): child is HTMLElement => + child instanceof HTMLElement && !child.hasAttribute(GHOST_ATTRIBUTE), + ); +} + +/** + * Which rows bound the drop range: the rows that cannot move at either end + * of the list, each run of them. One in the middle is passed like any other + * row; it only has no handle. + */ +function boundsOf(movable: ReadonlyArray): boolean[] { + const bounds = movable.map(() => false); + for (let index = 0; index < movable.length && !movable[index]; index += 1) { + bounds[index] = true; + } + for ( + let index = movable.length - 1; + index >= 0 && !movable[index]; + index -= 1 + ) { + bounds[index] = true; + } + return bounds; +} + +/** Marks the dragged row, dimmed in its place while the drag runs. */ +export const SOURCE_ATTRIBUTE = 'data-astryx-reorder-source'; +/** Marks the preview of the dragged row that follows the pointer. */ +export const PREVIEW_ATTRIBUTE = 'data-astryx-reorder-preview'; +/** Marks the insertion line at the drop position. */ +export const LINE_ATTRIBUTE = 'data-astryx-reorder-line'; + +/** + * The temporary reduced emphasis the dragged row and its preview share + * (design:ordered-collection-reordering DR2): the same item, moving, and + * not raised. + */ +const MOVING_OPACITY = '0.6'; +/** The insertion line's thickness, px. */ + +/** + * An element the drag draws over the list: a ghost to the list's order and + * its update motion, inert and hidden from assistive technology. + */ +function overlay(element: HTMLElement, marker: string): HTMLElement { + element.setAttribute(marker, ''); + element.setAttribute(GHOST_ATTRIBUTE, ''); + element.setAttribute('aria-hidden', 'true'); + element.inert = true; + Object.assign(element.style, { + position: 'absolute', + margin: '0', + pointerEvents: 'none', + zIndex: '2', + translate: '0px 0px', + }); + return element; +} + +/** + * The preview: a copy of `row` at its place, with the same reduced emphasis + * as the row and no elevation (DR2). + */ +function previewOf(row: HTMLElement, top: number, background: string | null) { + const preview = row.cloneNode(true) as HTMLElement; + preview.removeAttribute('id'); + for (const element of preview.querySelectorAll('[id]')) { + element.removeAttribute('id'); + } + overlay(preview, PREVIEW_ATTRIBUTE); + Object.assign(preview.style, { + top: `${top}px`, + insetInlineStart: `${row.offsetLeft}px`, + inlineSize: `${row.offsetWidth}px`, + boxSizing: 'border-box', + boxShadow: 'none', + opacity: MOVING_OPACITY, + }); + if (background != null) { + preview.style.backgroundColor = background; + } + return preview; +} + +/** The list's custom properties that place its insertion line. */ +const LINE_Y = '--astryx-reorder-line-y'; +const LINE_START = '--astryx-reorder-line-start'; +const LINE_SIZE = '--astryx-reorder-line-size'; +const LINE_ANGLE = '--astryx-reorder-line-angle'; + +/** The list's box a line is placed in: its padding box's width and direction. */ +interface LineFrame { + readonly width: number; + readonly isRtl: boolean; +} + +function frameOf(list: HTMLElement): LineFrame { + return { + width: list.clientWidth, + isRtl: getComputedStyle(list).direction === 'rtl', + }; +} + +/** + * Shows the list's insertion line (its pseudo-element, reorderListStyle, or + * an attached container's line element): `line`, in px from the top-left of + * the list's padding box. Its inline start is logical, so it is measured + * from the right in right-to-left. + */ +function showLine( + list: HTMLElement, + line: ReorderLine, + frame: LineFrame, +): void { + const start = frame.isRtl + ? frame.width - (line.x + line.length / 2) + : line.x - line.length / 2; + list.style.setProperty(LINE_START, `${start}px`); + list.style.setProperty(LINE_SIZE, `${line.length}px`); + list.style.setProperty(LINE_Y, `${line.y - INSERTION_LINE_THICKNESS / 2}px`); + list.style.setProperty(LINE_ANGLE, `${line.angle}deg`); + list.setAttribute(LINE_ATTRIBUTE, ''); +} + +/** A list's line across `row`, centred on `center` (a list's own gap). */ +function rowLine(row: HTMLElement, center: number): ReorderLine { + return { + x: row.offsetLeft + row.offsetWidth / 2, + y: center, + length: row.offsetWidth, + angle: 0, + }; +} + +/** Hides the list's insertion line and clears what placed it. */ +function hideLine(list: HTMLElement): void { + list.removeAttribute(LINE_ATTRIBUTE); + for (const property of [LINE_Y, LINE_START, LINE_SIZE, LINE_ANGLE]) { + list.style.removeProperty(property); + } +} + +/** + * Where the insertion line's centre sits for the dragged row at `position`: + * in the gap before the row it would land above, or after the one it would + * land below. Null at its own place: nothing moves. + */ +function lineCenter( + geometry: ReorderGeometry, + dragged: number, + position: number, +): number | null { + if (position === dragged) { + return null; + } + const target = geometry.rows[position]; + return position < dragged + ? target.top - geometry.gap / 2 + : target.top + target.height + geometry.gap / 2; +} + +/** A row's layout top inside the list (transforms ignored). */ +function layoutTop(row: HTMLElement, list: HTMLElement): number { + return layoutOffset(row, list, 'offsetTop', 'clientTop'); +} + +function layoutLeft(row: HTMLElement, list: HTMLElement): number { + return layoutOffset(row, list, 'offsetLeft', 'clientLeft'); +} + +/** + * A row's layout offset inside the list (transforms ignored), through any + * positioned wrapper between them: an attached container's items may sit + * under wrappers of the app's. + */ +function layoutOffset( + row: HTMLElement, + list: HTMLElement, + offset: 'offsetTop' | 'offsetLeft', + border: 'clientTop' | 'clientLeft', +): number { + let total = row[offset]; + let parent = row.offsetParent; + while ( + parent instanceof HTMLElement && + parent !== list && + list.contains(parent) + ) { + total += parent[border] + parent[offset]; + parent = parent.offsetParent; + } + // Measured from an ancestor outside the list (the list is static): less + // the list's own offset from it. + return parent === list ? total : total - list[offset]; +} + +function isScrollContainer(element: HTMLElement): boolean { + const {overflowY} = getComputedStyle(element); + return ( + (overflowY === 'auto' || overflowY === 'scroll') && + element.scrollHeight > element.clientHeight + ); +} + +function isTransparent(color: string): boolean { + return ( + color === '' || + color === 'transparent' || + /^rgba\(.*,\s*0\)$/.test(color) || + /\/\s*0\)$/.test(color) + ); +} + +/** + * The background a row is drawn on: the nearest opaque background behind + * the list, else the page's canvas. + */ +function surfaceColor(list: HTMLElement): string { + for ( + let node: HTMLElement | null = list; + node != null; + node = node.parentElement + ) { + const color = getComputedStyle(node).backgroundColor; + if (!isTransparent(color)) { + return color; + } + } + return 'Canvas'; +} + +/** The element autoscroll writes to and its visible band in the viewport. */ +interface Scroller { + readonly element: Element; + readonly top: number; + readonly bottom: number; + readonly max: number; + position: number; +} + +function scrollerOf(list: HTMLElement): Scroller { + for ( + let node = list.parentElement; + node != null && node !== node.ownerDocument.body; + node = node.parentElement + ) { + if (isScrollContainer(node)) { + const rect = node.getBoundingClientRect(); + const top = rect.top + node.clientTop; + return { + element: node, + top, + bottom: top + node.clientHeight, + max: node.scrollHeight - node.clientHeight, + position: node.scrollTop, + }; + } + } + const doc = list.ownerDocument; + const element = doc.scrollingElement ?? doc.documentElement; + const view = doc.defaultView; + const height = view?.innerHeight ?? element.clientHeight; + return { + element, + top: 0, + bottom: height, + max: Math.max(0, element.scrollHeight - height), + position: element.scrollTop, + }; +} + +/** A drag in progress, from the pick-up to the drop. */ +interface DragSession { + readonly list: HTMLElement; + /** The rows in order at the begin. */ + readonly rows: ReadonlyArray; + /** Their layout tops at the begin, for the commit's rebase. */ + readonly tops: ReadonlyArray; + readonly geometry: ReorderGeometry; + readonly dragged: number; + position: number; + /** The offset each row is moving to. */ + readonly offsets: number[]; + /** The list's layout origin in the viewport at the begin. */ + readonly origin: number; + /** The finger's distance from the dragged row's top. */ + readonly grabOffset: number; + readonly scroller: Scroller; + /** How far autoscroll has moved the content since the begin. */ + scrolled: number; + lastY: number; + /** The edge autoscroll's timer, on UIKit's 20 ms clock. */ + readonly edge: EdgeAutoscroll; + /** + * The slots `positions()` gives (spec:AST-103 FR1), whose nearest centre a + * drag proposes; null in a measured layout. + */ + readonly slots: ReadonlyArray | null; + /** The container's padding box left in the viewport at the begin. */ + readonly originX: number; + /** The dragged item's layout left inside the container. */ + readonly left: number; + /** The pointer's distance from the dragged item's left. */ + readonly grabX: number; + lastX: number; + /** The rows' layout lefts at the begin, in a `positions()` layout. */ + readonly lefts: ReadonlyArray | null; + /** The list's box the insertion line is placed in. */ + readonly frame: LineFrame; + /** Points per tick of the running autoscroll; 0 when none. */ + step: number; + /** The dragged row's inline stacking before the drag. */ + readonly restore: RowRestore; + /** The copy of the dragged row that follows the pointer. */ + readonly preview: HTMLElement; +} + +/** The inline values a drag overrides until its rows rest. */ +interface RowRestore { + /** The dragged row's stacking and background. */ + readonly zIndex: string; + readonly backgroundColor: string; + /** The dragged row's opacity, dimmed while the drag runs. */ + readonly opacity: string; + /** + * The dragged row's counter increment, off while its preview counts for it + * (a numbered list's number). + */ + readonly counterIncrement: string; + /** The list's position, made a containing block for the overlays. */ + readonly listPosition: string; + /** The session's rows, whose identity offsets go once they rest. */ + readonly rows: ReadonlyArray; +} + +/** A drop reported through `onReorder`, waiting for its commit. */ +interface PendingDrop { + readonly list: HTMLElement; + readonly rows: ReadonlyArray; + readonly tops: ReadonlyArray; + readonly dragged: number; + /** Where the preview was at the drop: the dragged row glides from there. */ + readonly droppedTop: number; + /** + * The release's y velocity, px/s: the dragged row's glide starts at it + * (spec:AST-094 FR6, FR38). + */ + readonly velocity: number; + readonly restore: RowRestore; + /** + * In a `positions()` layout, the rows' layout lefts at the begin, the + * preview's at the drop, and the release's x velocity: the glides move on + * both axes. Null in a measured layout. + */ + readonly lefts: ReadonlyArray | null; + readonly droppedLeft: number; + readonly velocityX: number; +} + +/** A reorder mode move, reported and waiting for its commit. */ +interface PendingMove { + readonly list: HTMLElement; + readonly rows: ReadonlyArray; + /** The rows' layout tops before it, for the slide to their new places. */ + readonly tops: ReadonlyArray; +} + +/** + * What a move announces: `landed` once the consumer commits it (the row is at + * `to` in the DOM), `kept` if the consumer keeps the order instead. A screen + * reader never hears a move that did not happen. + */ +interface PendingAnnouncement { + readonly row: HTMLElement; + readonly to: number; + readonly landed: string; + readonly kept: string; + readonly politeness: AnnouncePoliteness | undefined; +} + +/** The strings the controller announces, from the translator. */ +interface ReorderMessages { + /** + * A row's place in reorder mode: its name, place and count, and the names + * of the rows before and after it (null at the top or the end). + */ + place: ( + label: string, + position: number, + total: number, + previous: string | null, + next: string | null, + ) => string; + /** A reorder mode move refused by the row that stays where it would go. */ + refused: (label: string) => string; + /** A row's name when it shows no text: its place. */ + itemAt: (position: number) => string; + /** Reorder mode ended: the row's name and its place. */ + modeDone: (label: string, position: number, total: number) => string; + /** A move the app did not apply, on an attached container (FR4b). */ + notMoved: (label: string) => string; + /** A move in a two-dimensional layout: the item's row and column too. */ + placeGrid: ( + label: string, + row: number, + column: number, + position: number, + total: number, + ) => string; + pickedUp: (position: number, total: number) => string; + dropped: (position: number, total: number) => string; + cancelled: (position: number, total: number) => string; +} + +export function messagesFrom(t: TranslatorFn): ReorderMessages { + return { + place: (label, position, total, previous, next) => + previous == null + ? t('@astryx.list.reorderPlaceTop', {label, position, total, next}) + : next == null + ? t('@astryx.list.reorderPlaceEnd', { + label, + position, + total, + previous, + }) + : t('@astryx.list.reorderPlace', { + label, + position, + total, + previous, + next, + }), + refused: label => t('@astryx.list.reorderRefused', {label}), + itemAt: position => t('@astryx.list.reorderItemAt', {position}), + modeDone: (label, position, total) => + t('@astryx.list.reorderModeDone', {label, position, total}), + notMoved: label => t('@astryx.list.reorderNotMoved', {label}), + placeGrid: (label, row, column, position, total) => + t('@astryx.list.reorderPlaceGrid', { + label, + row, + column, + position, + total, + }), + pickedUp: (position, total) => + t('@astryx.list.reorderPickedUp', {position, total}), + dropped: (position, total) => + t('@astryx.list.reorderDropped', {position, total}), + cancelled: (position, total) => + t('@astryx.list.reorderCancelled', {position, total}), + }; +} + +/** What a gesture listener hands the controller. */ +export interface ReorderGestureEvent { + readonly state: 'began' | 'changed' | 'ended' | 'cancelled'; + /** The finger's (or pointer's) y in the viewport. */ + readonly y: number; + /** Its x in the viewport, which a `positions()` layout follows. */ + readonly x?: number; + /** + * At a release, the finger's (or pointer's) y velocity in px/s, which the + * dropped row's glide starts at (spec:AST-094 FR6, FR38). + */ + readonly velocity?: number; + /** At a release, its x velocity in px/s, for a `positions()` layout. */ + readonly velocityX?: number; +} + +/** A long press's state as a reorder gesture's; null while it waits. */ +function gestureStateOf( + recognizer: LongPressGestureRecognizer, +): ReorderGestureEvent['state'] | null { + switch (recognizer.state) { + case 'began': + case 'changed': + case 'ended': + case 'cancelled': + return recognizer.state; + case 'failed': + return 'cancelled'; + case 'possible': + return null; + } +} + +/** + * The reorder session of one List. One instance per List; its listeners are + * on the list, and every handle in it reports its keys here. + */ +export class ListReorderController implements ListReorderSession { + readonly Host = ListReorderHost; + readonly Handle = ListReorderHandle; + readonly RowName = ListReorderRowName; + readonly rowStyle = reorderRowStyle; + readonly listStyle = reorderListStyle; + options: ListReorderOptions | null = null; + announce: AnnounceFn = () => {}; + messages: ReorderMessages | null = null; + /** Whether rows move on springs (`'uikit'`) or jump (`'theme'`). */ + presentation: 'uikit' | 'theme' = 'theme'; + /** Each of this list's handles, with its row's item key. */ + private readonly keys = new Map(); + /** + * The names the announcements give rows: each handle's (its row's label + * text) and each handle-less row's own. + */ + private readonly names = new Map(); + /** The handle whose row is in reorder mode, if any. */ + private modeHandle: HTMLElement | null = null; + private readonly modeListeners = new Set<() => void>(); + /** Reorder mode's hint, while it shows: focus in it keeps the mode. */ + private hintElement: HTMLElement | null = null; + /** The handle whose press became a drag, until its click is read. */ + private draggedHandle: Element | null = null; + /** A reorder mode move, whose rows slide once it commits (under a finger). */ + private committedMove: PendingMove | null = null; + private moveFallback: ReturnType | null = null; + /** + * A reorder mode move between its report and its commit: the commit may + * move the handle's element, and the blur that causes keeps the mode. + */ + private isMovingByKey = false; + /** + * Reorder mode's insertion line: after a key move it marks the edge the + * row came in through, at its new place, until the mode ends. + */ + private modeLine: {list: HTMLElement; listPosition: string} | null = null; + /** The direction of the last key move in reorder mode, for its line. */ + private lastStep: -1 | 1 | null = null; + /** The last key move's places, for its line in a slot layout. */ + private lastMove: {from: number; to: number} | null = null; + /** + * Until when the handle takes back the focus the UI that started the mode + * with `start` hands back (a menu that closes restores its trigger's). + */ + private claimFocusUntil = 0; + private session: DragSession | null = null; + private pending: PendingDrop | null = null; + private fallback: ReturnType | null = null; + /** The row whose handle keeps focus across a reorder mode move's commit. */ + private focusRow: HTMLElement | null = null; + /** A move's announcement, waiting for its commit. */ + private announcement: PendingAnnouncement | null = null; + private announcementFallback: ReturnType | null = null; + /** Ends the mouse press in progress, if any, without reporting it. */ + private endMouse: (() => void) | null = null; + /** Whether a list whose rows have no item key has been warned about. */ + private warnedUnkeyed = false; + /** + * What a move the caller did not apply announces: the place its row kept + * (a List), or that it cannot move (an attached container, spec:AST-103 + * FR4b). + */ + refusal: 'kept-place' | 'not-moved' = 'kept-place'; + + constructor( + private readonly getList: () => HTMLElement | null, + readonly hintId: string, + /** + * The items' elements in order, where they are not the list's own + * children (attach's `items()`, spec:AST-103 FR4b). + */ + private readonly itemElements?: () => HTMLElement[], + ) {} + + /** The rows of `list` in order: its children, or the attached items. */ + private rowsIn(list: HTMLElement): HTMLElement[] { + return this.itemElements?.() ?? rowsOf(list); + } + + /** The List's latest options, announcer, strings and presentation. */ + configure(options: { + options: ListReorderOptions; + announce: AnnounceFn; + messages: ReorderMessages; + presentation: 'uikit' | 'theme'; + }): void { + this.options = options.options; + this.announce = options.announce; + this.messages = options.messages; + this.presentation = options.presentation; + } + + private get animates(): boolean { + return this.presentation === 'uikit'; + } + + /** + * Records a row's handle, the row's item key (ListItem `itemKey`) and its + * name; returns the removal. A row moves only with a handle recorded here. + */ + registerHandle(handle: Element | null, key: Key, name: string): () => void { + if (handle == null) { + return () => {}; + } + this.keys.set(handle, key); + this.names.set(handle, name); + return () => { + if (this.keys.get(handle) === key) { + this.keys.delete(handle); + this.names.delete(handle); + if (this.modeHandle === handle) { + this.setMode(null); + } + } + }; + } + + /** + * An attached container's app rendered some items anew (the same keys, + * new elements): reorder mode, the focus to give back, and the move or + * drop waiting for its commit follow each item to its new element + * (spec:AST-103 FR4b). Called with the new handles registered and before + * the old ones go, so the mode does not end with its old handle. + */ + adoptElements( + rows: ReadonlyMap, + handles: ReadonlyMap, + ): void { + const row = (element: HTMLElement) => rows.get(element) ?? element; + if (this.focusRow != null) { + this.focusRow = row(this.focusRow); + } + if (this.announcement != null) { + this.announcement = { + ...this.announcement, + row: row(this.announcement.row), + }; + } + if (this.committedMove != null) { + this.committedMove = { + ...this.committedMove, + rows: this.committedMove.rows.map(row), + }; + } + if (this.pending != null) { + this.pending = {...this.pending, rows: this.pending.rows.map(row)}; + } + const handle = + this.modeHandle == null ? undefined : handles.get(this.modeHandle); + if (handle != null) { + // The same mode, on the item's new handle: its last move and line stay. + this.modeHandle = handle; + for (const listener of [...this.modeListeners]) { + listener(); + } + } + } + + /** Records the name of a row without a handle; returns the removal. */ + registerName(row: Element | null, name: string): () => void { + if (row == null) { + return () => {}; + } + this.names.set(row, name); + return () => { + if (this.names.get(row) === name) { + this.names.delete(row); + } + }; + } + + /** What the announcements call the row at `index`. */ + private nameOf(row: HTMLElement, index: number): string { + const handle = this.handleIn(row); + const name = + (handle == null ? null : this.names.get(handle)) ?? + this.names.get(row) ?? + ''; + return name !== '' ? name : (this.messages?.itemAt(index + 1) ?? ''); + } + + // --- Reorder mode ---------------------------------------------------- + + /** Whether `handle`'s row is in reorder mode: its `aria-pressed`. */ + isInMode(handle: Element | null): boolean { + return handle != null && this.modeHandle === handle; + } + + /** Calls `listener` when reorder mode starts, moves or ends. */ + subscribeMode = (listener: () => void): (() => void) => { + this.modeListeners.add(listener); + return () => { + this.modeListeners.delete(listener); + }; + }; + + /** The handle whose row is in reorder mode, if any. */ + get modeTarget(): HTMLElement | null { + return this.modeHandle; + } + + private setMode(handle: HTMLElement | null): void { + if (this.modeHandle === handle) { + return; + } + this.modeHandle = handle; + this.lastStep = null; + this.lastMove = null; + this.clearModeLine(); + for (const listener of [...this.modeListeners]) { + listener(); + } + } + + /** + * A handle was activated without a drag (a click, Space or Enter): its row + * enters reorder mode, or leaves it (spec:AST-103 FR4). + */ + toggleMode(handle: HTMLElement | null): void { + if (handle == null || this.session != null) { + return; + } + if (this.modeHandle === handle) { + this.endMode(); + return; + } + if (this.handleOf(handle) === handle) { + this.setMode(handle); + // The arrows go to the handle (a click does not focus a button in + // every browser). + if (handle.ownerDocument.activeElement !== handle) { + handle.focus({preventScroll: true}); + } + } + } + + /** + * Ends reorder mode, keeping its moves, and announces where the row is + * ("Done, Milk at position 3 of 5"): Escape, another activation of the + * handle, or the hint's Done. Focus that a screen reader moved into the + * hint goes back to the handle. A blur, a drag or the row leaving ends it + * without a word. + */ + endMode(): void { + const handle = this.modeHandle; + const list = this.getList(); + const row = this.rowOf(handle); + const active = handle?.ownerDocument.activeElement; + if ( + handle != null && + active != null && + this.hintElement?.contains(active) + ) { + handle.focus({preventScroll: true}); + } + this.setMode(null); + if (list == null || row == null) { + return; + } + const rows = this.rowsIn(list); + const index = rows.indexOf(row); + this.announce( + this.messages?.modeDone( + this.nameOf(row, index), + index + 1, + rows.length, + ) ?? '', + ); + } + + /** Records reorder mode's hint element (null once it goes). */ + setHintElement(element: HTMLElement | null): void { + this.hintElement = element; + } + + /** + * Reorder mode for the item with `key`, started from the app's own UI + * (spec:AST-103 FR4a): the focus moves to its handle, which scrolls into + * view, as activating it does. Returns whether an item with that key can + * move here. + */ + startByKey(key: Key): boolean { + if (this.session != null) { + return true; + } + for (const [handle, handleKey] of this.keys) { + if ( + handleKey === key && + handle instanceof HTMLElement && + this.handleOf(handle) === handle + ) { + this.setMode(handle); + handle.focus({preventScroll: true}); + this.rowOf(handle)?.scrollIntoView?.({ + block: 'nearest', + inline: 'nearest', + }); + this.claimFocusUntil = performance.now() + START_FOCUS_CLAIM_MS; + return true; + } + } + return false; + } + + /** + * Whether `handle`'s latest press dragged its row; reading it clears it. + * A press that dragged does not toggle reorder mode with its click. + */ + takeDrag(handle: Element | null): boolean { + const dragged = handle != null && this.draggedHandle === handle; + this.draggedHandle = null; + return dragged; + } + + /** This list's handle in `row`, if it has one: a nested list's are its own. */ + private handleIn(row: HTMLElement): Element | null { + for (const handle of row.querySelectorAll(`[${HANDLE_ATTRIBUTE}]`)) { + if (this.keys.has(handle)) { + return handle; + } + } + return null; + } + + /** The item key `row` reports its moves with; none for a row that stays. */ + private keyOf(row: HTMLElement): Key | undefined { + const handle = this.handleIn(row); + return handle == null ? undefined : this.keys.get(handle); + } + + // --- Listeners --------------------------------------------------------- + + /** + * The handle `target` is in, if it is one of this list's and takes + * gestures; a nested reorderable list's handles are that list's. + */ + private handleOf(target: unknown): HTMLElement | null { + const list = this.getList(); + if (list == null || !(target instanceof Element)) { + return null; + } + const handle = target.closest(`[${HANDLE_ATTRIBUTE}]`); + return handle != null && + this.keys.has(handle) && + list.contains(handle) && + handle.getAttribute('aria-disabled') !== 'true' + ? handle + : null; + } + + /** + * The list's pointer listeners for the primary pointer (spec:AST-094 + * FR43): a mouse, and a pen where the primary pointer is fine, drag at + * once; a finger, and a pen where it is coarse, hold first. List's host and + * createReorderable's attach both wire them here. Returns the detach. + */ + attachPointers(isCoarse: boolean): () => void { + const detachMouse = this.attachMouse(!isCoarse); + const detachTouch = this.attachTouch(isCoarse); + return () => { + detachMouse(); + detachTouch(); + }; + } + + /** + * Lets a mouse, and with `pens` a pen, drag rows by their handles at once, + * with no hold (spec:AST-094 FR43, spec:AST-103 FR3): one pointerdown + * listener on the list, and while a press is down its move and lift + * listeners there too. Only a primary click starts one: a right click, a + * pen's barrel button and a macOS ctrl-click open the row's menu instead. + * The press is the handle's until it lifts (pointer capture), and drags + * the row once it has moved MOUSE_DRAG_SLOP, from where it pressed. + * Returns the detach. + */ + attachMouse(pens: boolean): () => void { + const list = this.getList(); + if (list == null) { + return () => {}; + } + const onPointerDown = (event: PointerEvent) => { + const isPointer = + event.pointerType === 'mouse' || (pens && event.pointerType === 'pen'); + if (!isPointer || !isPrimaryClick(event)) { + return; + } + const handle = this.handleOf(event.target); + if (handle == null) { + return; + } + this.endMouse?.(); + this.draggedHandle = null; + const {pointerId, clientX: x, clientY: y} = event; + let isDragging = false; + // The pointer's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + velocity.add(x, y, event.timeStamp); + const end = () => { + list.removeEventListener('pointermove', onMove); + list.removeEventListener('pointerup', onUp); + list.removeEventListener('pointercancel', onCancel); + list.removeEventListener('lostpointercapture', onCancel); + if (handle.hasPointerCapture?.(pointerId)) { + handle.releasePointerCapture(pointerId); + } + if (this.endMouse === end) { + this.endMouse = null; + } + }; + const onMove = (move: PointerEvent) => { + if (move.pointerId !== pointerId) { + return; + } + velocity.add(move.clientX, move.clientY, move.timeStamp); + if (!isDragging) { + if ( + Math.hypot(move.clientX - x, move.clientY - y) < MOUSE_DRAG_SLOP + ) { + return; + } + isDragging = true; + this.draggedHandle = handle; + this.gesture(this.rowOf(handle), {state: 'began', y, x}); + } + this.gesture(null, { + state: 'changed', + y: move.clientY, + x: move.clientX, + }); + }; + const onUp = (up: PointerEvent) => { + if (up.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + velocity.add(up.clientX, up.clientY, up.timeStamp); + const release = velocity.velocity(up.timeStamp); + this.gesture(null, { + state: 'ended', + y: up.clientY, + x: up.clientX, + velocity: release.y, + velocityX: release.x, + }); + } + }; + const onCancel = (cancel: PointerEvent) => { + if (cancel.pointerId !== pointerId) { + return; + } + end(); + if (isDragging) { + this.gesture(null, {state: 'cancelled', y: cancel.clientY}); + } + }; + list.addEventListener('pointermove', onMove); + list.addEventListener('pointerup', onUp); + list.addEventListener('pointercancel', onCancel); + list.addEventListener('lostpointercapture', onCancel); + handle.setPointerCapture?.(pointerId); + this.endMouse = end; + }; + list.addEventListener('pointerdown', onPointerDown); + return () => { + this.endMouse?.(); + list.removeEventListener('pointerdown', onPointerDown); + }; + } + + /** + * Lets a finger held still on a handle pick up its row, and with `pens` a + * pen: one recognizer on the list, which receives only the touches that + * begin on its handles. Attached for every pointer (spec:AST-094 FR43, + * FR19). Returns the detach. + */ + attachTouch(pens: boolean): () => void { + const list = this.getList(); + if (list == null) { + return () => {}; + } + let held: HTMLElement | null = null; + // The finger's velocity, for the glide a release hands it to. + const velocity = new VelocityTracker(); + return attachTouchHold( + list, + target => { + const handle = this.handleOf(target); + if (handle != null) { + held = handle; + } + return handle != null; + }, + recognizer => { + const state = gestureStateOf(recognizer); + if (state === 'began') { + this.draggedHandle = held; + velocity.reset(); + } + // One sample per event, at the event's time. + const touch = recognizer.trackedTouches[0]; + if (touch != null && state != null && state !== 'cancelled') { + velocity.add(touch.x, touch.y, touch.time); + } + if (state != null) { + this.gesture(state === 'began' ? this.rowOf(held) : null, { + state, + y: recognizer.location().y, + x: recognizer.location().x, + velocity: + state === 'ended' && touch != null + ? velocity.velocity(touch.time).y + : undefined, + velocityX: + state === 'ended' && touch != null + ? velocity.velocity(touch.time).x + : undefined, + }); + } + }, + pens, + ); + } + + // --- Pointer drags --------------------------------------------------- + + /** A gesture from a handle: begin, track, drop or cancel the drag. */ + gesture(row: HTMLElement | null, event: ReorderGestureEvent): void { + switch (event.state) { + case 'began': + if (row != null) { + this.begin(row, event.y, event.x ?? 0); + } + break; + case 'changed': + this.track(event.y, event.x ?? this.session?.lastX ?? 0); + break; + case 'ended': + this.drop(event.velocity ?? 0, event.velocityX ?? 0); + break; + case 'cancelled': + this.cancel(); + break; + } + } + + /** + * The handle in `row` stopped taking gestures (its row disabled or no + * longer reorderable, the handle gone): a drag of that row goes home. The + * session owns that end, since a recognizer turned off mid-gesture reports + * nothing. + */ + release(row: HTMLElement | null): void { + const session = this.session; + if ( + session != null && + row != null && + session.rows[session.dragged] === row + ) { + this.endMouse?.(); + this.cancel(); + } + if (row != null && this.rowOf(this.modeHandle) === row) { + this.setMode(null); + } + } + + /** Picks up `row` under a pointer at `y`. Returns whether it did. */ + private begin(row: HTMLElement, y: number, x: number): boolean { + const list = this.getList(); + if (list == null || this.session != null) { + return false; + } + // A drag ends reorder mode, keeping its moves, and says so. + if (this.modeHandle != null) { + this.endMode(); + } + // A drop still waiting for its commit is settled where it is. + this.flushPending(); + const rows = this.rowsIn(list); + const dragged = rows.indexOf(row); + const movable = rows.map(element => this.handleIn(element) != null); + if (dragged < 0 || !movable[dragged]) { + return false; + } + const at = motionNow(); + const tops = rows.map(element => layoutTop(element, list)); + const heights = rows.map(element => element.offsetHeight); + const bounds = boundsOf(movable); + const geometry: ReorderGeometry = { + rows: rows.map((element, index) => ({ + top: tops[index], + height: heights[index], + isFixed: bounds[index], + })), + gap: rows.length > 1 ? Math.max(0, tops[1] - tops[0] - heights[0]) : 0, + }; + // The list's layout origin in the viewport, from the dragged row's box + // without the offset it may still be moving by. + const shown = shownY(row, at); + const origin = row.getBoundingClientRect().top - shown - tops[dragged]; + const scroller = scrollerOf(list); + // A positions() layout: the dragged item follows the pointer on both + // axes, and the nearest slot centre is its drop position. + const slots = this.slotsFor(list, rows); + const listBox = list.getBoundingClientRect(); + const originX = listBox.left + list.clientLeft; + const left = row.getBoundingClientRect().left - originX; + // Every row gets an identity offset for the session: a row's first offset + // would otherwise change how it paints in the middle of the drag (a + // layout and a paint); with one in place, neither a move nor a slide lays + // out or paints. (`will-change` would make each slide's start repaint its + // row.) The dragged row goes above its neighbours. + const restore: RowRestore = { + zIndex: row.style.zIndex, + backgroundColor: row.style.backgroundColor, + opacity: row.style.opacity, + counterIncrement: row.style.counterIncrement, + listPosition: list.style.position, + rows, + }; + // The rows stay where they are until the drop + // (design:ordered-collection-reordering): the dragged row is dimmed in + // its place, a preview of it follows the pointer, and an insertion line + // marks where it would land. The preview has a background, as the row + // does: a row without its own takes the surface's behind the list. + const background = isTransparent(getComputedStyle(row).backgroundColor) + ? surfaceColor(list) + : null; + for (const element of rows) { + if (element.style.translate === '') { + element.style.translate = '0px 0px'; + } + } + if (getComputedStyle(list).position === 'static') { + list.style.position = 'relative'; + } + const preview = previewOf(row, tops[dragged], background); + // Right before its source: the preview counts for it, so in a numbered + // list it reads the source's number, and every other row keeps its place + // among its siblings (the last row its :last-child). + row.before(preview); + row.style.counterIncrement = 'none'; + row.setAttribute(SOURCE_ATTRIBUTE, ''); + row.style.opacity = MOVING_OPACITY; + list.setAttribute(REORDERING_ATTRIBUTE, ''); + const session: DragSession = { + list, + rows, + tops, + geometry, + dragged, + position: dragged, + offsets: rows.map((element, index) => + index === dragged ? 0 : shownY(element, at), + ), + origin, + grabOffset: y - (origin + tops[dragged] + shown), + scroller, + scrolled: 0, + lastY: y, + edge: edgeAutoscroll({ + intervalMs: reorder.autoscroll.tickMs, + // UIKit's run-loop timer: a late fire (engines fire a 20 ms interval + // every 20 to 25 ms) catches up one tick, a longer stall is skipped. + catchUp: true, + now: motionNow, + step: () => this.edgeStep(session), + apply: delta => this.scrollBy(session, delta), + }), + step: 0, + restore, + preview, + slots, + originX, + left, + grabX: x - (originX + left), + lastX: x, + lefts: slots == null ? null : rows.map(item => layoutLeft(item, list)), + frame: frameOf(list), + }; + this.session = session; + // Rows still sliding from an earlier drag go to their places. + this.moveTo(dragged); + this.track(y, x); + this.announce( + this.messages?.pickedUp(dragged + 1, rows.length) ?? '', + 'polite', + ); + return true; + } + + /** The dragged row's top in the viewport for the finger at `y`. */ + private draggedTop(session: DragSession, y: number): number { + const {geometry, dragged, scroller} = session; + const row = geometry.rows[dragged]; + const first = geometry.rows[0]; + const last = geometry.rows[geometry.rows.length - 1]; + const origin = session.origin - session.scrolled; + return clampTop(y - session.grabOffset, row.height, { + scrollTop: scroller.top, + scrollBottom: scroller.bottom, + listTop: origin + first.top, + listBottom: origin + last.top + last.height, + }); + } + + private track(y: number, x: number): void { + const session = this.session; + if (session == null) { + return; + } + session.lastY = y; + session.lastX = x; + const {geometry, dragged, slots} = session; + const row = geometry.rows[dragged]; + const origin = session.origin - session.scrolled; + // In a positions() layout the item follows the pointer freely: the + // list's own ends bound a vertical list's rows, not a grid's or a fan's. + const top = + slots != null ? y - session.grabOffset : this.draggedTop(session, y); + const shiftY = top - (origin + row.top); + if (slots != null) { + // The preview follows the pointer on both axes; the drop position is + // the slot within the drag's range whose centre is nearest its own. + const shiftX = x - session.grabX - (session.originX + session.left); + animatorFor(session.preview).set({x: shiftX, y: shiftY}); + const width = session.rows[dragged].offsetWidth; + const nearest = nearestSlot(slots, geometry.rows, dragged, { + x: session.left + shiftX + width / 2, + y: row.top + shiftY + row.height / 2, + }); + if (nearest !== session.position) { + this.moveTo(nearest); + } + this.autoscroll(top, row.height); + return; + } + animatorFor(session.preview).set({y: shiftY}); + const position = dropPosition( + geometry, + dragged, + top + row.height / 2 - origin, + ); + if (position !== session.position) { + this.moveTo(position); + } + this.autoscroll(top, row.height); + } + + /** Puts the insertion line where the dragged row would land at `position`. */ + private moveTo(position: number): void { + const session = this.session; + if (session == null) { + return; + } + session.position = position; + const row = session.rows[session.dragged]; + let line: ReorderLine | null; + if (session.slots != null) { + line = slotLine(session.slots, session.dragged, position, { + width: row.offsetWidth, + height: row.offsetHeight, + }); + } else { + const center = lineCenter(session.geometry, session.dragged, position); + line = center == null ? null : rowLine(row, center); + } + if (line == null) { + hideLine(session.list); + } else { + showLine(session.list, line, session.frame); + } + // A pointer drag announces its pick-up and its drop, not each place it + // passes: announcing each crossed position is noisy. + } + + /** + * Points per tick for the dragged row at `top`: positive down, negative + * up, 0 when neither edge is near or the content cannot move that way. + */ + private stepFor(session: DragSession, top: number, height: number): number { + const {scroller} = session; + let step = 0; + if (scroller.position < scroller.max) { + step = autoscrollStep(top + height - scroller.bottom); + } + if (step === 0 && scroller.position > 0) { + step = -autoscrollStep(scroller.top - top); + } + return step; + } + + /** Starts or stops the edge autoscroll for the row at `top`. */ + private autoscroll(top: number, height: number): void { + const session = this.session; + if (session == null) { + return; + } + session.step = Math.abs(this.stepFor(session, top, height)); + session.edge.update(); + } + + /** The autoscroll's next step for the finger where it last was. */ + private edgeStep(session: DragSession): number { + if (this.session !== session) { + return 0; + } + const {geometry, dragged} = session; + const top = this.draggedTop(session, session.lastY); + return this.stepFor(session, top, geometry.rows[dragged].height); + } + + /** + * One autoscroll step: the content moves by `delta` (inside its range) and + * the row stays under the finger. Returns how far the content moved. + */ + private scrollBy(session: DragSession, delta: number): number { + if (this.session !== session) { + return 0; + } + const {scroller} = session; + const next = Math.min(scroller.max, Math.max(0, scroller.position + delta)); + const moved = next - scroller.position; + if (moved === 0) { + return 0; + } + scroller.element.scrollTop = next; + session.scrolled += moved; + scroller.position = next; + this.track(session.lastY, session.lastX); + return moved; + } + + private stopAutoscroll(session: DragSession): void { + session.edge.stop(); + session.step = 0; + } + + /** + * The drop: the move is reported, and on its commit the row glides into + * its place, starting at the release's y `velocity` in px/s. + */ + private drop(velocity: number, velocityX = 0): void { + const session = this.session; + if (session == null) { + return; + } + this.session = null; + this.stopAutoscroll(session); + const {geometry, dragged, position, rows, list} = session; + const element = rows[dragged]; + // Where the preview is now: on the commit the dragged row glides from + // there into its new place, and the rows it passed to theirs. + const droppedTop = + geometry.rows[dragged].top + shownY(session.preview, motionNow()); + const droppedLeft = + session.lefts == null + ? 0 + : session.lefts[dragged] + shownX(session.preview, motionNow()); + this.clearOverlays(session); + const dropped = this.messages?.dropped(position + 1, rows.length) ?? ''; + const key = this.keyOf(element); + const options = this.options; + if (position === dragged || options == null || key == null) { + if (position === dragged) { + this.announce(dropped, 'polite'); + list.removeAttribute(REORDERING_ATTRIBUTE); + this.restWhenDone(element, session.restore); + } else { + this.springBack(list, rows, dragged, session.restore); + } + return; + } + this.announceWhenCommitted({ + row: element, + to: position, + landed: dropped, + kept: + this.refusal === 'not-moved' + ? (this.messages?.notMoved(this.nameOf(element, dragged)) ?? '') + : (this.messages?.cancelled(dragged + 1, rows.length) ?? ''), + politeness: 'polite', + }); + this.pending = { + list, + rows, + tops: session.tops, + dragged, + droppedTop, + velocity, + restore: session.restore, + lefts: session.lefts, + droppedLeft, + velocityX, + }; + options.onReorder({key, to: position}); + // A consumer that does not apply the move by the end of the task gets + // its rows back where they were. + this.fallback = setTimeout(() => { + this.fallback = null; + this.refuse(); + }, 0); + } + + /** + * The drag ends where it started: the browser took the touch (a pinch, a + * scroll), or the handle left. Every row goes home and nothing is + * reported. + */ + cancel(): void { + const session = this.session; + if (session == null) { + return; + } + this.session = null; + this.stopAutoscroll(session); + // Nothing moved: the preview and the line go and the row is itself again + // at once (design:ordered-collection-reordering). + this.clearOverlays(session); + this.springBack( + session.list, + session.rows, + session.dragged, + session.restore, + ); + this.announce( + this.messages?.cancelled(session.dragged + 1, session.rows.length) ?? '', + ); + } + + /** Takes the preview and the line away and undims the dragged row. */ + private clearOverlays(session: DragSession): void { + session.preview.remove(); + hideLine(session.list); + const row = session.rows[session.dragged]; + row.removeAttribute(SOURCE_ATTRIBUTE); + row.style.opacity = session.restore.opacity; + row.style.counterIncrement = session.restore.counterIncrement; + session.list.style.position = session.restore.listPosition; + } + + private springBack( + list: HTMLElement, + rows: ReadonlyArray, + dragged: number, + restore: RowRestore, + ): void { + const at = motionNow(); + for (const element of rows) { + const value = shownY(element, at); + if (Math.abs(value) < MIN_MOVE_PX && !isMoving(element)) { + continue; + } + if (!this.animates) { + animatorFor(element).set({y: 0}); + releaseMotion(element, 'translate'); + continue; + } + // A row still gliding (a drop's or a key move's glide) goes on home on + // the shared settle role from where it is shown, at the speed it has + // (spec:AST-094 FR4, FR6). + touchMotion.home(element, touchMotion.glideBase(list), at, false); + } + list.removeAttribute(REORDERING_ATTRIBUTE); + this.restWhenDone(rows[dragged], restore); + } + + /** `onReorder` applied no new order: the rows return to their places. */ + private refuse(): void { + const pending = this.pending; + if (pending == null) { + return; + } + const current = this.rowsIn(pending.list); + if (!sameOrder(current, pending.rows)) { + // The commit came but its layout effect has not run yet. + return; + } + this.pending = null; + this.springBack( + pending.list, + pending.rows, + pending.dragged, + pending.restore, + ); + } + + /** Clears the dragged row's stacking once its motion has come to rest. */ + private restWhenDone(element: HTMLElement, restore: RowRestore): void { + const settle = () => { + if (this.session?.rows[this.session.dragged] === element) { + return; + } + const running = motionOf(element, 'y'); + if (running != null) { + // The drop's spring, or the rebase that continues it. + void running.handle.finished.then(settle); + return; + } + element.style.zIndex = restore.zIndex; + element.style.backgroundColor = restore.backgroundColor; + // Identity offsets go; a row still moving keeps its own. + for (const row of restore.rows) { + releaseMotion(row, 'translate'); + } + }; + settle(); + } + + private flushPending(): void { + if (this.pending == null) { + return; + } + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.refuse(); + this.pending = null; + } + + // --- Commits --------------------------------------------------------- + + commit(): void { + const list = this.getList(); + if (list == null) { + return; + } + if ( + !this.warnedUnkeyed && + this.keys.size === 0 && + this.options != null && + this.options.isReorderable == null && + list.children.length > 0 + ) { + this.warnedUnkeyed = true; + devWarn( + 'List', + '`reorderable` is set, but no ListItem has an `itemKey`: give each ' + + 'row the key its moves report.', + ); + } + const session = this.session; + if (session != null && !sameOrder(this.rowsIn(list), session.rows)) { + // The rows changed under the drag. + this.cancel(); + } + const pending = this.pending; + if (pending != null && !sameOrder(this.rowsIn(list), pending.rows)) { + this.pending = null; + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.rebase(pending); + } + const announcement = this.announcement; + if ( + announcement != null && + this.rowsIn(list).indexOf(announcement.row) === announcement.to + ) { + this.announcement = null; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + this.announcementFallback = null; + } + this.announce(announcement.landed, announcement.politeness); + } + const move = this.committedMove; + if (move != null && !sameOrder(this.rowsIn(list), move.rows)) { + this.committedMove = null; + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + this.moveFallback = null; + } + this.slideCommitted(move); + } + // A reorder mode move has landed (or nothing waits): its handle keeps + // the focus, and the insertion line marks the row's new place. + if (this.announcement == null) { + this.restoreFocus(); + this.placeModeLine(list); + } + } + + /** A reorder mode move landed: each row slides from its old place to its new one. */ + private slideCommitted(move: PendingMove): void { + const {list} = move; + const at = motionNow(); + for (const [index, element] of move.rows.entries()) { + if (element.parentElement !== list) { + continue; + } + const shift = move.tops[index] - layoutTop(element, list); + if (Math.abs(shift) < MIN_MOVE_PX) { + continue; + } + // A row still sliding from the previous move goes on from where it is + // shown, as a drop's rows do. + touchMotion.follow(element, shift, touchMotion.glideBase(list), at); + } + list.removeAttribute(REORDERING_ATTRIBUTE); + } + + private rebase(pending: PendingDrop): void { + const {list} = pending; + const at = motionNow(); + for (const [index, element] of pending.rows.entries()) { + if (element.parentElement !== list) { + continue; + } + // The dragged row glides from where its preview was dropped, the rows + // it passed from their old places. + const from = + index === pending.dragged ? pending.droppedTop : pending.tops[index]; + const shift = from - layoutTop(element, list); + // In a positions() layout the row moves on both axes. + const lefts = pending.lefts; + const shiftX = + lefts == null + ? 0 + : (index === pending.dragged ? pending.droppedLeft : lefts[index]) - + layoutLeft(element, list); + const value = shownY(element, at); + const valueX = lefts == null ? 0 : shownX(element, at); + const rest = lefts == null ? {y: 0} : {x: 0, y: 0}; + if ( + Math.abs(value + shift) < MIN_MOVE_PX && + Math.abs(valueX + shiftX) < MIN_MOVE_PX && + !isMoving(element) + ) { + animatorFor(element).set(rest); + releaseMotion(element, 'translate'); + continue; + } + if (Math.abs(shift) < MIN_MOVE_PX && Math.abs(shiftX) < MIN_MOVE_PX) { + continue; + } + const moved = lefts == null ? shift : {x: shiftX, y: shift}; + if (this.animates && index === pending.dragged) { + // The dragged row glides from where its preview was dropped into its + // new layout place, starting at the release's velocity + // (spec:AST-094 FR6, FR38). + touchMotion.glide( + element, + moved, + touchMotion.glideBase(list), + at, + lefts == null + ? pending.velocity + : {x: pending.velocityX, y: pending.velocity}, + ); + } else if (this.animates) { + // Every other row's place after the drop is its new layout place, so + // its running spring (a row's glide) goes on to 0 from the shifted + // value, or the glide starts from rest. + touchMotion.follow(element, moved, touchMotion.glideBase(list), at); + } else { + animatorFor(element).set(rest); + releaseMotion(element, 'translate'); + } + } + list.removeAttribute(REORDERING_ATTRIBUTE); + this.restWhenDone(pending.rows[pending.dragged], pending.restore); + } + + /** + * Reorder mode's insertion line, at the edge the mode's row came in + * through on its last key move (the gap above it after a move up, below + * it after a move down), shared with the pointer drag's + * (design:ordered-collection-reordering). None before a move. + */ + private placeModeLine(list: HTMLElement): void { + const row = this.rowOf(this.modeHandle); + if (row == null || this.lastStep == null) { + this.clearModeLine(); + return; + } + const rows = this.rowsIn(list); + const index = rows.indexOf(row); + // A slot layout: the leading edge of the item's new slot, across its + // last move. + const slots = this.slotsFor(list, rows); + if (slots != null && this.lastMove != null && this.lastMove.to === index) { + const line = stepLine(slots, this.lastMove.from, index, { + width: row.offsetWidth, + height: row.offsetHeight, + }); + this.holdModeLine(list); + if (line == null) { + hideLine(list); + } else { + showLine(list, line, frameOf(list)); + } + return; + } + const top = layoutTop(row, list); + const bottom = top + row.offsetHeight; + const neighbour = rows[index + this.lastStep]; + const gap = + neighbour == null + ? 0 + : this.lastStep < 0 + ? Math.max( + 0, + top - (layoutTop(neighbour, list) + neighbour.offsetHeight), + ) + : Math.max(0, layoutTop(neighbour, list) - bottom); + const center = this.lastStep < 0 ? top - gap / 2 : bottom + gap / 2; + this.holdModeLine(list); + showLine(list, rowLine(row, center), frameOf(list)); + } + + /** Reorder mode's line is `list`'s, which is its containing block. */ + private holdModeLine(list: HTMLElement): void { + if (this.modeLine?.list !== list) { + this.clearModeLine(); + const listPosition = list.style.position; + if (getComputedStyle(list).position === 'static') { + list.style.position = 'relative'; + } + this.modeLine = {list, listPosition}; + } + } + + /** + * The slots a drag and the arrows use: `positions()`, else an attached + * container's measured slots when its items are not one column; null for + * a column (a List's rows), whose drags follow UIKit's row model. + */ + private slotsFor( + list: HTMLElement, + rows: ReadonlyArray, + ): ReadonlyArray | null { + const given = slotsOf(this.options?.positions, rows.length); + if (given != null || this.itemElements == null || rows.length < 2) { + return given; + } + // Their layout places (transforms left out), from the container's + // padding box. + const measured = rows.map(element => ({ + x: layoutLeft(element, list) + element.offsetWidth / 2, + y: layoutTop(element, list) + element.offsetHeight / 2, + })); + const isColumn = measured.every( + slot => Math.abs(slot.x - measured[0].x) < 1, + ); + return isColumn ? null : measured; + } + + private clearModeLine(): void { + const modeLine = this.modeLine; + if (modeLine == null) { + return; + } + this.modeLine = null; + hideLine(modeLine.list); + modeLine.list.style.position = modeLine.listPosition; + } + + /** + * The row that holds `element` (a handle): the list's child that contains + * it, whatever its tag. Null outside the list. + */ + rowOf(element: Element | null): HTMLElement | null { + const list = this.getList(); + if (list != null && this.itemElements != null) { + // An attached container's items, which may sit under wrappers: the + // item that holds `element`. + const items = new Set(this.itemElements()); + let item = element; + while (item != null && item !== list) { + if (item instanceof HTMLElement && items.has(item)) { + return item; + } + item = item.parentElement; + } + return null; + } + let node = element; + while (node != null && node.parentElement !== list) { + node = node.parentElement; + } + return list != null && node instanceof HTMLElement ? node : null; + } + + /** The 1-based place of the row that holds `element`, or null. */ + positionOf(element: Element | null): number | null { + const list = this.getList(); + const row = this.rowOf(element); + return list == null || row == null + ? null + : this.rowsIn(list).indexOf(row) + 1; + } + + // --- Keys ------------------------------------------------------------ + + /** + * A handle's key in reorder mode (spec:AST-103 FR4): the arrows move its + * row a place at once, and Escape ends the mode, keeping the moves. Space + * and Enter toggle the mode through the handle's click. + */ + keyDown( + handle: HTMLElement | null, + event: Pick< + KeyboardEvent, + | 'key' + | 'altKey' + | 'ctrlKey' + | 'metaKey' + | 'preventDefault' + | 'stopPropagation' + >, + ): void { + // A modified key is a browser or assistive-technology shortcut. + if ( + handle == null || + handle !== this.modeHandle || + event.altKey || + event.ctrlKey || + event.metaKey + ) { + return; + } + switch (event.key) { + case 'Escape': + event.preventDefault(); + event.stopPropagation(); + this.endMode(); + return; + case 'ArrowUp': + case 'ArrowDown': + case 'ArrowLeft': + case 'ArrowRight': + if (this.moveByArrow(handle, event.key)) { + event.preventDefault(); + } + return; + default: + return; + } + } + + /** + * Reorder mode's move: the row whose handle is in the mode goes a place up + * (`-1`) or down (`1`) at once, with one report, announced with its place + * and neighbours once it lands. Under a finger's presentation the rows + * then slide to their new places, as a UIKit table moves a row. A move + * into a row that stays at either end is refused and announced; one past + * the list's end does nothing. + */ + step(handle: HTMLElement | null, delta: number): void { + const list = this.getList(); + const options = this.options; + const row = this.rowOf(handle); + const key = row == null ? undefined : this.keyOf(row); + if ( + list == null || + options == null || + row == null || + key == null || + handle !== this.modeHandle || + this.session != null + ) { + return; + } + const rows = this.rowsIn(list); + const index = rows.indexOf(row); + const to = index + delta; + if (to < 0 || to >= rows.length) { + return; + } + if (boundsOf(rows.map(element => this.handleIn(element) != null))[to]) { + this.announce(this.messages?.refused(this.nameOf(rows[to], to)) ?? ''); + return; + } + const order = rows.filter(element => element !== row); + order.splice(to, 0, row); + this.focusRow = row; + this.isMovingByKey = true; + this.lastStep = delta < 0 ? -1 : 1; + this.lastMove = {from: index, to}; + const grid = this.keyGrid(list, rows); + this.announceWhenCommitted({ + row, + to, + landed: this.placeIn(order, to, grid), + kept: + this.refusal === 'not-moved' + ? (this.messages?.notMoved(this.nameOf(row, index)) ?? '') + : this.placeIn(rows, index, grid), + politeness: undefined, + }); + if (this.animates) { + this.committedMove = { + list, + rows, + tops: rows.map(element => layoutTop(element, list)), + }; + // The List's update motion leaves this commit to the reorder. + list.setAttribute(REORDERING_ATTRIBUTE, ''); + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + } + // The caller kept the order: nothing slides. + this.moveFallback = setTimeout(() => { + this.moveFallback = null; + if (this.committedMove != null) { + this.committedMove = null; + if (this.session == null && this.pending == null) { + list.removeAttribute(REORDERING_ATTRIBUTE); + } + } + }, 0); + } + options.onReorder({key, to}); + } + + /** + * Reorder mode's move for `arrow`, along the layout's axis: a list's + * column, an attached row, or both axes in a grid (spec:AST-103 FR4). + * Returns whether the arrow moves along the layout. + */ + moveByArrow(handle: HTMLElement | null, arrow: ReorderArrow): boolean { + const list = this.getList(); + const row = this.rowOf(handle); + if (list == null || row == null) { + return false; + } + const rows = this.rowsIn(list); + const index = rows.indexOf(row); + const target = arrowTarget( + this.keyGrid(list, rows), + index, + arrow, + this.isRtl(list), + ); + if (target == null) { + return false; + } + this.step(handle, target - index); + return true; + } + + /** The arrows that move along the layout's axis, for reorder mode's hint. */ + arrowsFor(handle: HTMLElement | null): ReorderArrow[] { + const list = this.getList(); + if (list == null || handle == null) { + return ['ArrowUp', 'ArrowDown']; + } + const grid = this.keyGrid(list, this.rowsIn(list)); + const isColumn = grid.every(gridRow => gridRow.length <= 1); + const isRow = grid.length === 1 && grid[0].length > 1; + if (isColumn) { + return ['ArrowUp', 'ArrowDown']; + } + return isRow + ? ['ArrowLeft', 'ArrowRight'] + : ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']; + } + + /** + * The layout's rows in reading order, for reorder mode's arrows and its + * announcements: from `positions()`, else an attached container's measured + * items; a List's rows are one column. + */ + private keyGrid( + list: HTMLElement, + rows: ReadonlyArray, + ): number[][] { + const slots = this.slotsFor(list, rows); + if (slots == null) { + return rows.map((_, index) => [index]); + } + // Items whose centres are within half an item's height share a row (a + // fanned hand's slots are one row). + const tolerance = Math.max( + 1, + Math.min(...rows.map(element => element.offsetHeight)) / 2, + ); + return gridOf(slots, this.isRtl(list), tolerance); + } + + private isRtl(list: HTMLElement): boolean { + return getComputedStyle(list).direction === 'rtl'; + } + + /** What reorder mode announces for the row at `at` in `order`. */ + private placeIn( + order: ReadonlyArray, + at: number, + grid?: ReadonlyArray>, + ): string { + const name = (index: number) => this.nameOf(order[index], index); + // A two-dimensional layout names the item's row and column. + if ( + grid != null && + grid.length > 1 && + grid.some(gridRow => gridRow.length > 1) + ) { + const {row, column} = cellOf(grid, at); + return ( + this.messages?.placeGrid(name(at), row, column, at + 1, order.length) ?? + '' + ); + } + return ( + this.messages?.place( + name(at), + at + 1, + order.length, + at > 0 ? name(at - 1) : null, + at < order.length - 1 ? name(at + 1) : null, + ) ?? '' + ); + } + + /** + * Announces a move once it commits; if the consumer keeps the order by the + * end of the task, announces that the row stayed instead. + */ + private announceWhenCommitted(announcement: PendingAnnouncement): void { + this.announcement = announcement; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + } + this.announcementFallback = setTimeout(() => { + this.announcementFallback = null; + const pending = this.announcement; + if (pending != null) { + this.announcement = null; + this.announce(pending.kept, pending.politeness); + } + this.restoreFocus(); + }, 0); + } + + /** + * A handle lost focus to `next`: its row leaves reorder mode, keeping its + * moves, unless a move's commit is moving its element (focus going + * nowhere while it does). + */ + blur(handle: HTMLElement | null, next: EventTarget | null): void { + // Focus a screen reader moves into the mode's hint keeps the mode. + if (next instanceof Node && this.hintElement?.contains(next)) { + return; + } + // The UI that started the mode handing its focus back (a closing menu + // restoring its trigger's) at once: the handle takes it again. + if ( + handle != null && + handle === this.modeHandle && + performance.now() < this.claimFocusUntil + ) { + setTimeout(() => { + if (this.modeHandle === handle) { + handle.focus({preventScroll: true}); + } + }, 0); + return; + } + // Focus leaving the handle does not end reorder mode: its exits are + // Escape, Done, the handle again and its row going (spec:AST-103 FR4, + // FR4a). Back on the handle, its arrows move the row again. + } + + /** + * After a reorder mode move: the handle has the focus again (the commit + * may have moved its element) and its row scrolls into view. + */ + private restoreFocus(): void { + this.isMovingByKey = false; + const row = this.focusRow; + if (row == null) { + return; + } + this.focusRow = null; + const handle = this.handleIn(row); + const active = row.ownerDocument.activeElement; + // Focus that went elsewhere meanwhile stays there; focus in the hint + // (a screen reader's) goes back to the handle. + if ( + handle instanceof HTMLElement && + handle === this.modeHandle && + (active == null || + active === row.ownerDocument.body || + this.hintElement?.contains(active) === true) + ) { + handle.focus({preventScroll: true}); + } + if (handle === this.modeHandle) { + row.scrollIntoView?.({block: 'nearest', inline: 'nearest'}); + } + } + + dispose(): void { + this.endMouse?.(); + this.setMode(null); + // A drag in progress goes home. + this.cancel(); + if (this.moveFallback != null) { + clearTimeout(this.moveFallback); + this.moveFallback = null; + } + this.committedMove = null; + if (this.fallback != null) { + clearTimeout(this.fallback); + this.fallback = null; + } + this.pending = null; + if (this.announcementFallback != null) { + clearTimeout(this.announcementFallback); + this.announcementFallback = null; + } + this.announcement = null; + } +} + +function sameOrder( + a: ReadonlyArray, + b: ReadonlyArray, +): boolean { + return ( + a.length === b.length && a.every((element, index) => element === b[index]) + ); +} + +/** + * Beside a reorderable List's rows: keeps its session's options, strings + * and presentation current, attaches the list's listeners (the touch hold + * only where the primary pointer is coarse), and renders the handles' + * instructions. + */ +function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) { + const {options} = reorder; + const controller = reorder.session as ListReorderController; + const announce = useAnnounce(); + const t = useTranslator(); + // UIKit's motion under a finger (one touch model on every touch device); + // with a mouse, rows take their places at once. + const isTouch = useTouchPresentation().isTouch; + useIsomorphicLayoutEffect(() => { + controller.configure({ + options, + announce, + messages: messagesFrom(t), + presentation: isTouch ? 'uikit' : 'theme', + }); + }); + // Every pointer (spec:AST-094 FR43, FR18, FR19): a pen drags at once where + // the primary pointer is fine, as a mouse does, since the handle allows it + // no pan there; where it is coarse, the handle keeps the page's pan, so a + // pen holds as a finger does (an iPad Pencil's touches are claimable). The + // hold attaches for every pointer: a finger on a touch screen whose + // primary pointer is fine holds as it does on a phone; where the primary + // pointer is fine, the gesture host keeps one passive listener on the list + // until a press (FR24). Wired as createReorderable's attach wires them. + useIsomorphicLayoutEffect( + () => controller.attachPointers(isTouch), + [controller, isTouch], + ); + // Where the object's `start` finds this list. + useIsomorphicLayoutEffect( + () => mountSession(options, controller), + [options, controller], + ); + // The List stopped reordering, or unmounted: a drag goes home. + useIsomorphicLayoutEffect(() => () => controller.dispose(), [controller]); + return ( + <> + + + + ); +} + +const hintStyles = stylex.create({ + // A glyph or Done: the hint's text, with nothing of a button's own, the + // same size under every pointer. A finger's 44 px target is the invisible + // hit layer below, grown by the insets the hit area writes where the + // primary pointer is coarse, each side capped at half the gap to a + // neighbouring target (utils/hitArea.ts), so it never covers one. + button: { + position: 'relative', + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + margin: 0, + padding: 0, + borderWidth: 0, + borderRadius: 4, + backgroundColor: 'transparent', + color: 'inherit', + fontFamily: 'inherit', + fontSize: 'inherit', + lineHeight: 'inherit', + cursor: { + default: 'pointer', + ':is(:disabled,[aria-disabled="true"])': 'default', + }, + // SYNC: utils/hitArea.ts HIT_INSET_PROPERTIES (StyleX reads no + // imported value). + '::after': { + content: '""', + position: 'absolute', + inset: + 'calc(var(--astryx-hit-inset-top, 0px) * -1) calc(var(--astryx-hit-inset-right, 0px) * -1) calc(var(--astryx-hit-inset-bottom, 0px) * -1) calc(var(--astryx-hit-inset-left, 0px) * -1)', + }, + }, + done: { + paddingInline: spacingVars['--spacing-1'], + color: colorVars['--color-text-primary'], + fontWeight: fontWeightVars['--font-weight-semibold'], + }, +}); + +/** + * One of the hint's buttons: it never takes the focus from the handle (a + * press does not move it), and does what its key does. + */ +function HintButton({ + label, + onPress, + isText = false, + children, +}: { + label?: string; + onPress: () => void; + isText?: boolean; + children: ReactNode; +}) { + const ref = useRef(null); + // A finger's target: the hit area watches the button where the primary + // pointer is coarse and writes how far its hit layer may grow. + useIsomorphicLayoutEffect(() => { + const button = ref.current; + if (button == null) { + return undefined; + } + return watchHitArea(button, insets => writeHitInsets(button, insets)); + }, []); + return ( + + ); +} + +/** + * Reorder mode's hint (spec:AST-103 FR4): anchored below the start of the + * handle whose row is in the mode, in Core's keyboard hint's layer and + * theme roles, it shows the moves for the list's axis and Done until the + * mode ends. Each move is a button that does what its key does, with the + * same announcement and the focus left on the handle, and Done ends the + * mode as Escape does, so a pointer or a finger can reorder by tapping the + * handle, the moves, then Done. + */ +/** Each hint move: its label and its key's glyph (the key it does). */ +const HINT_MOVES = { + ArrowUp: {label: '@astryx.list.reorderMoveUp', keys: 'up'}, + ArrowDown: {label: '@astryx.list.reorderMoveDown', keys: 'down'}, + ArrowLeft: {label: '@astryx.list.reorderMoveLeft', keys: 'left'}, + ArrowRight: {label: '@astryx.list.reorderMoveRight', keys: 'right'}, +} as const; + +export function ListReorderModeHint({ + controller, +}: { + controller: ListReorderController; +}): ReactNode { + const t = useTranslator(); + const target = useSyncExternalStore( + controller.subscribeMode, + () => controller.modeTarget, + () => null, + ); + const layer = useLayer({mode: 'context'}); + const layerRef = useRef(layer); + const hintRef = useRef(null); + // No external system: keeps the latest layer handle for the effect below, + // which re-runs only when the mode's row changes. Idempotent. + useIsomorphicLayoutEffect(() => { + layerRef.current = layer; + }); + // External system: the hint's popover in the top layer (useLayer), + // anchored to the handle of the row in reorder mode. Shown while that row + // is in the mode; hidden and unanchored when the mode ends or moves on. + useIsomorphicLayoutEffect(() => { + if (target == null) { + return undefined; + } + const shown = layerRef.current; + shown.ref(target); + shown.show(); + return () => { + shown.hide(); + shown.ref(null); + }; + }, [target]); + // The shared dismissal stack (family:overlay-dismissal): while the hint is + // up, an Escape that reaches the stack, with the focus in the hint, ends + // reorder mode instead of closing a layer below it such as a Dialog. The + // handle claims its own Escape first. + useLayerDismissal({ + isActive: target != null, + onDismiss: () => controller.endMode(), + getContainer: () => hintRef.current, + }); + // No row in the mode: the layer stays, empty and hidden. + if (target === null) { + return renderAnchoredHint(layer, null, {isInteractive: true}); + } + return renderAnchoredHint( + layer, + { + hintRef.current = element; + controller.setHintElement(element); + }} + {...stylex.props(anchoredHintStyles.keys)}> + {controller.arrowsFor(target).map(arrow => ( + controller.moveByArrow(target, arrow)}> + + + ))} + controller.endMode()}> + {t('@astryx.list.reorderDone')} + + , + {isInteractive: true}, + ); +} + +/** The machinery a reorderable object carries (createReorderable). */ +export const listReorderEngine: ListReorderEngine = { + createSession: (getList, hintId) => + new ListReorderController(getList, hintId), + start: (options, key) => { + const sessions = sessionsByOptions.get(options) ?? []; + if (sessions.length > 1) { + devWarn( + 'createReorderable', + '`start` was called on an object passed to more than one ' + + 'collection: it starts reorder mode in the one mounted last.', + ); + } + const session = sessions.at(-1); + if (session == null || !session.startByKey(key)) { + devWarn( + 'createReorderable', + `\`start(${String(key)})\` found no mounted item with ` + + 'that key that can be reordered, so it did nothing.', + ); + } + }, +}; diff --git a/packages/core/src/List/ownRing.stylex.ts b/packages/core/src/List/ownRing.stylex.ts new file mode 100644 index 0000000000000..465097932272c --- /dev/null +++ b/packages/core/src/List/ownRing.stylex.ts @@ -0,0 +1,51 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ownRing.stylex.ts + * @input The focus tokens (theme/tokens.stylex.ts) + * @output ownRingContainerStyles: a reorderable List row's focus-within ring, + * which leaves a handle that rings itself alone + * @position Internal to the List reorder: ListReorderHandle reads it, and + * only createReorderable's engine imports that, so a List without + * `reorderable` carries none of it. Not part of the package's exports + * (utils/focusOutline.stylex.ts is). + * + * SYNC: When modified, keep the ring equal to utils/focusOutline.stylex.ts's + * focus outline. + */ + +import * as stylex from '@stylexjs/stylex'; +import {focusVars} from '../theme/tokens.stylex'; + +/** A focused descendant that is not a control ringing itself. */ +const OTHER_FOCUS = ':has(:focus-visible:not([data-astryx-own-ring]))'; + +/** + * A container that rings itself on focus within, except for a focused + * descendant marked `data-astryx-own-ring`: a control that rings itself, + * such as a List row's reorder handle. Without it the two rings stack for + * one tab stop, and an ancestor that clips its inline overflow (List) cuts + * the container's ring to two lines. Its own object, so the reorder that + * uses it (List/listReorderEngine.tsx, with createReorderable) carries it + * and a List without one does not. + */ +export const ownRingContainerStyles = stylex.create({ + focusWithin: { + outlineWidth: { + default: '0', + [OTHER_FOCUS]: focusVars['--focus-outline-width'], + }, + outlineStyle: { + default: 'none', + [OTHER_FOCUS]: focusVars['--focus-outline-style'], + }, + outlineColor: { + default: null, + [OTHER_FOCUS]: focusVars['--focus-outline-color'], + }, + outlineOffset: { + default: '0', + [OTHER_FOCUS]: focusVars['--focus-outline-offset'], + }, + }, +}); diff --git a/packages/core/src/List/reorderModel.ts b/packages/core/src/List/reorderModel.ts new file mode 100644 index 0000000000000..c7ddfac8129c6 --- /dev/null +++ b/packages/core/src/List/reorderModel.ts @@ -0,0 +1,412 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reorderModel.ts + * @input A list's row geometry (layout tops and heights inside the list) and + * the reorder values of the UIKit constants table (motion/uikit/reorder.ts) + * @output Pure functions of a reorder's drag: the position a dragged row proposes + * (where the insertion cue goes), from the measured rows or from the slots + * `positions()` gives, the movable range that a fixed row at either end of + * the list bounds, the autoscroll step and the tracking clamp + * @position List internals; List/listReorderEngine.tsx drives a drag with + * them. No DOM, no React: unit tested against the UIKit lab measurements + * + * The rows stay still during a drag while an insertion cue marks the + * drop position (design:ordered-collection-reordering DR3), so the model + * proposes drop positions and moves no row. The rule: a row below the dragged row + * changes places once the dragged row's centre passes that row's far edge less + * the dragged row's height, and never before that row's near edge; a row + * above mirrors it; boundaries sit in the middle of a gap, with no + * hysteresis. Measured on UIKit (iOS 26.2): a 44 pt row moving down past 44 + * and 88 pt rows and back over them. GUESS, until M-RO27 measures them + * (motion/MEASUREMENTS.md): a short row moving up past a taller row above + * its place, and a tall row moving past a shorter one. Autoscroll moves a + * whole number of points per tick, more the deeper the dragged row's edge is + * past the scroll view's edge (measured). + */ + +import {reorder} from '../motion/uikit/reorder'; + +/** One row: its layout top inside the list, its height, and whether it stays put. */ +export interface ReorderRow { + readonly top: number; + readonly height: number; + /** + * A row with no handle, so no drag starts from it: a run of them at either + * end of the list bounds a drag, and one in the middle is passed over + * (spec:AST-103 FR1). + */ + readonly isFixed: boolean; +} + +export interface ReorderGeometry { + readonly rows: ReadonlyArray; + /** The space between two consecutive rows. */ + readonly gap: number; +} + +/** + * The positions `dragged` can take: all of them but those of the fixed rows that + * end the list. A run of fixed rows at either end bounds the range; a fixed row + * in the middle is passed over, as reorder mode's keys pass it + * (spec:AST-103 FR1, FR4). + */ +export function movableRange( + rows: ReadonlyArray>, + dragged: number, +): {start: number; end: number} { + let start = 0; + while (start < dragged && rows[start].isFixed) { + start += 1; + } + let end = rows.length - 1; + while (end > dragged && rows[end].isFixed) { + end -= 1; + } + return {start, end}; +} + +/** + * The position the dragged row proposes for its centre, in list coordinates: where + * the insertion cue goes. A row below it changes places once the centre passes + * that row's far edge less the dragged row's height: for equal rows, the + * neighbour's near edge, half a row, and for a 44 pt row passing an 88 pt row + * below its place, that row's height (both measured). A row above mirrors it + * (GUESS for unequal rows, M-RO27). Either way the centre must first pass the + * neighbour's near edge, so a tall row never starts past a short neighbour + * (its centre travels at least half its own height; GUESS, M-RO27). + * Boundaries sit in the middle of a gap. + */ +export function dropPosition( + geometry: ReorderGeometry, + dragged: number, + center: number, +): number { + const {rows, gap} = geometry; + const height = rows[dragged].height; + let position = 0; + for (let index = 0; index < rows.length; index += 1) { + if (index === dragged) { + continue; + } + const {top, height: rowHeight} = rows[index]; + const boundary = + index < dragged + ? Math.min(top + height, top + rowHeight) + gap / 2 + : Math.max(top + rowHeight - height, top) - gap / 2; + if (boundary < center) { + position += 1; + } + } + const {start, end} = movableRange(rows, dragged); + return Math.min(end, Math.max(start, position)); +} + +/** A slot's centre: px from the top-left corner of the collection's container box. */ +export interface ReorderSlot { + readonly x: number; + readonly y: number; +} + +/** + * The slots `positions()` gives (spec:AST-103 FR1): null without it, or when + * it gives other than one per item, and drop positions then come from the + * measured layout. + */ +export function slotsOf( + positions: (() => ReadonlyArray) | undefined, + count: number, +): ReadonlyArray | null { + const slots = positions?.(); + return slots != null && slots.length === count ? slots : null; +} + +/** + * The drop position a dragged item proposes among `slots`: the slot within + * its movable range whose centre is nearest the item's centre (spec:AST-103 + * FR1); the first of equally near slots. + */ +export function nearestSlot( + slots: ReadonlyArray, + items: ReadonlyArray>, + dragged: number, + center: ReorderSlot, +): number { + const {start, end} = movableRange(items, dragged); + let nearest = start; + let nearestDistance = Infinity; + for (let index = start; index <= end; index += 1) { + const distance = Math.hypot( + slots[index].x - center.x, + slots[index].y - center.y, + ); + if (distance < nearestDistance) { + nearest = index; + nearestDistance = distance; + } + } + return nearest; +} + +/** An insertion cue: a line centred on `x, y`, `length` long, at `angle`°. */ +export interface ReorderLine { + readonly x: number; + readonly y: number; + readonly length: number; + /** Clockwise from the horizontal, within (-90, 90]. */ + readonly angle: number; +} + +/** The size of the item a cue marks the place of, unturned. */ +export interface ReorderSize { + readonly width: number; + readonly height: number; +} + +/** + * A line between slot centres `a` and `b`: through their midpoint, + * perpendicular to the step from one to the other, as long as `size` is + * across it. Null when they coincide. + */ +function lineAcross( + a: ReorderSlot, + b: ReorderSlot, + size: ReorderSize, +): ReorderLine | null { + const dx = b.x - a.x; + const dy = b.y - a.y; + const distance = Math.hypot(dx, dy); + if (distance === 0) { + return null; + } + // The line runs along (-dy, dx): perpendicular to the step. + const ux = -dy / distance; + const uy = dx / distance; + let angle = (Math.atan2(uy, ux) * 180) / Math.PI; + // A line has no direction. + if (angle > 90) { + angle -= 180; + } else if (angle <= -90) { + angle += 180; + } + return { + x: (a.x + b.x) / 2, + y: (a.y + b.y) / 2, + length: size.width * Math.abs(ux) + size.height * Math.abs(uy), + angle, + }; +} + +/** + * Whether slots `a` and `b` are neighbours along a row or a column for an + * item of `size`: a row's centres sit within half an item's height (a fanned + * hand's too), a column's within half its width. A step that wraps rows is + * neither. + */ +function isAdjacent( + a: ReorderSlot, + b: ReorderSlot, + size: ReorderSize, +): boolean { + return ( + Math.abs(a.y - b.y) < Math.max(1, size.height / 2) || + Math.abs(a.x - b.x) < Math.max(1, size.width / 2) + ); +} + +/** + * The insertion cue of a drag in a slot layout (`positions()`, or an + * attached container's measured slots): a list's line, turned to lie between + * the target slot and the next slot along the drag, which is where the item + * lands in the order. Where the next slot is on another row (a row's end in + * a wrapping grid) or there is none, half a step beyond the target slot + * along its own row or column. None at the item's own place. (Proposed for + * design:ordered-collection-reordering OQ2.) + */ +export function slotLine( + slots: ReadonlyArray, + dragged: number, + position: number, + size: ReorderSize, +): ReorderLine | null { + if (position === dragged) { + return null; + } + const forward = position > dragged; + const at = slots[position]; + const next = slots[forward ? position + 1 : position - 1]; + if (next != null && isAdjacent(at, next, size)) { + return lineAcross(at, next, size); + } + const back = slots[forward ? position - 1 : position + 1]; + if (back != null && isAdjacent(at, back, size)) { + return lineAcross(at, {x: 2 * at.x - back.x, y: 2 * at.y - back.y}, size); + } + // Alone on its row and column: at its edge along the reading order. + const side = forward ? size.width : -size.width; + return lineAcross(at, {x: at.x + side, y: at.y}, size); +} + +/** + * Reorder mode's cue after a key move from slot `from` to slot `to`: the + * leading edge of the new slot along the move, half a step beyond it, as a + * list's line marks the edge its row came in through. A move that wraps rows + * is marked along the new slot's row, as a drag's cue is, so the line stays + * inside the layout. + */ +export function stepLine( + slots: ReadonlyArray, + from: number, + to: number, + size: ReorderSize, +): ReorderLine | null { + const a = slots[from]; + const b = slots[to]; + if (a == null || b == null) { + return null; + } + if (!isAdjacent(a, b, size)) { + return slotLine(slots, from, to, size); + } + return lineAcross(b, {x: 2 * b.x - a.x, y: 2 * b.y - a.y}, size); +} + +/** + * A layout's rows in reading order, from its slots: each row lists its + * items' indices from the reading start (the left, or the right in + * right-to-left). Slots whose centres are within `tolerance` px vertically + * share a row. + */ +export function gridOf( + slots: ReadonlyArray, + isRtl: boolean, + tolerance = 1, +): number[][] { + const byY = slots + .map((slot, index) => ({slot, index})) + .sort((a, b) => a.slot.y - b.slot.y || a.index - b.index); + const rows: {slot: ReorderSlot; index: number}[][] = []; + for (const item of byY) { + const row = rows[rows.length - 1]; + if (row != null && Math.abs(item.slot.y - row[0].slot.y) <= tolerance) { + row.push(item); + } else { + rows.push([item]); + } + } + return rows.map(row => + row + .sort((a, b) => (isRtl ? b.slot.x - a.slot.x : a.slot.x - b.slot.x)) + .map(({index}) => index), + ); +} + +/** An arrow key reorder mode reads (spec:AST-103 FR4). */ +export type ReorderArrow = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight'; + +/** + * Where an arrow moves the item at `index` in a layout of `rows` (gridOf's), + * as an index in the order; null when the arrow does not move along the + * layout's axis or leaves it. A column moves with Up and Down, a row with + * Left and Right (mirrored in right-to-left), and a grid with all four: Left + * and Right to the previous and next position in reading order, Up and Down + * to the same column in the previous or next row, or that row's last + * position when it is shorter. + */ +export function arrowTarget( + rows: ReadonlyArray>, + index: number, + arrow: ReorderArrow, + isRtl: boolean, +): number | null { + const count = rows.reduce((sum, row) => sum + row.length, 0); + const isColumn = rows.every(row => row.length === 1); + const isRow = rows.length === 1; + const along = (delta: number) => { + const to = index + delta; + return to < 0 || to >= count ? null : to; + }; + if (arrow === 'ArrowUp' || arrow === 'ArrowDown') { + if (isRow) { + return null; + } + if (isColumn) { + return along(arrow === 'ArrowUp' ? -1 : 1); + } + const r = rows.findIndex(row => row.includes(index)); + const c = rows[r].indexOf(index); + const next = rows[r + (arrow === 'ArrowUp' ? -1 : 1)]; + return next == null ? null : next[Math.min(c, next.length - 1)]; + } + if (isColumn) { + return null; + } + const forward = (arrow === 'ArrowRight') !== isRtl; + return along(forward ? 1 : -1); +} + +/** The 1-based row and column of the slot at `index` in `rows`. */ +export function cellOf( + rows: ReadonlyArray>, + index: number, +): {row: number; column: number} { + const r = rows.findIndex(row => row.includes(index)); + return {row: r + 1, column: rows[r].indexOf(index) + 1}; +} + +/** + * Points per autoscroll tick with the dragged row's edge `depth` points past + * the scroll edge (negative inside): none further inside than the start + * inset, then UIKit's measured steps, interpolated and rounded. + */ +export function autoscrollStep(depth: number): number { + const {depths, stepsPt, startInset} = reorder.autoscroll; + if (depth < -startInset) { + return 0; + } + if (depth <= depths[0]) { + return stepsPt[0]; + } + const last = depths.length - 1; + if (depth >= depths[last]) { + return stepsPt[last]; + } + let index = 1; + while (depths[index] < depth) { + index += 1; + } + const d0 = depths[index - 1]; + const d1 = depths[index]; + const s0 = stepsPt[index - 1]; + const s1 = stepsPt[index]; + return Math.round(s0 + ((s1 - s0) * (depth - d0)) / (d1 - d0)); +} + +/** Where a dragged row may go: the scroller's visible edges and the list's ends. */ +export interface ReorderBounds { + /** The scroller's visible top and bottom. */ + readonly scrollTop: number; + readonly scrollBottom: number; + /** The list's first row top and last row bottom. */ + readonly listTop: number; + readonly listBottom: number; +} + +/** + * The dragged row's top. At the scroller's visible edge the row stops with its + * centre on the edge, as UIKit stops a row on the table's edge; at the list's + * own end it stops with its edge there, so a row never hangs over the content + * after an embedded list (a TransferList's next panel, a page footer). + */ +export function clampTop( + top: number, + height: number, + bounds: ReorderBounds, +): number { + const min = Math.max(bounds.scrollTop - height / 2, bounds.listTop); + const max = Math.min( + bounds.scrollBottom - height / 2, + bounds.listBottom - height, + ); + return Math.min(max, Math.max(min, top)); +} diff --git a/packages/core/src/List/useListUpdateMotion.test.tsx b/packages/core/src/List/useListUpdateMotion.test.tsx new file mode 100644 index 0000000000000..c4903506b0a3f --- /dev/null +++ b/packages/core/src/List/useListUpdateMotion.test.tsx @@ -0,0 +1,437 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useListUpdateMotion.test.tsx + * @input vitest, List with `hasAnimatedChanges`, a stubbed pointer (a finger, + * iOS and Android alike, or a mouse) and stubbed row positions + * (jsdom lays nothing out) + * @output Unit tests for when List's update motion moves rows: survivors whose + * place changed get a motion under any finger; a removed row collapses in + * place as a ghost, the row below glued to its edge; a new row shows nothing + * until the row it displaced has cleared its band; a row crossing rows + * that move the other way rides above them; nothing moves with a mouse, + * without `hasAnimatedChanges`, + * on the first render, or + * while a reorder session owns the list; content after the list is never + * moved, and a list that got shorter clips its rows to its box while they + * move; with + * motion off nothing is read; a resize of the list between commits + * refreshes where its rows are + * @position Beside List/useListUpdateMotion.ts; the motion itself is proven + * in a real engine by List/__tests__/ListUpdates.interaction.browser.spec.ts + */ + +import {act, render, screen, waitFor} from '@testing-library/react'; +import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest'; +import {List} from './List'; +import {ListItem} from './ListItem'; +import { + motionNow, + motionOf, + presentation, + type RowMotion, +} from '../utils/rowMotion'; + +const ROW = 40; +/** Each row's height as the stubbed layout reports it. */ +let rowHeight = ROW; + +beforeAll(() => { + // jsdom lays nothing out: place each list row by its index. + Object.defineProperty(HTMLElement.prototype, 'offsetTop', { + configurable: true, + get(this: HTMLElement) { + // Content below the list sits under its rows; a pinned footer never + // moves. + if (this.hasAttribute('data-pinned')) { + return 500; + } + if (this.dataset.testid === 'below') { + return ( + document.querySelectorAll('ul > li:not([data-astryx-leaving])') + .length * rowHeight + ); + } + const parent = this.parentElement; + if (this.tagName !== 'LI' || parent == null) { + return 0; + } + // A removed row's ghost is out of flow: it takes no place. + return ( + Array.from(parent.children) + .filter(child => !child.hasAttribute('data-astryx-leaving')) + .indexOf(this) * rowHeight + ); + }, + }); + Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { + configurable: true, + get(this: HTMLElement) { + return this.tagName === 'LI' ? rowHeight : 0; + }, + }); +}); + +/** + * The page under a finger (a coarse primary pointer: one touch model, iOS + * and Android alike) or a mouse. + */ +function stubPointer(pointer: 'touch' | 'mouse') { + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: pointer === 'touch' && query.includes('pointer: coarse'), + media: query, + onchange: null, + addEventListener: () => undefined, + removeEventListener: () => undefined, + addListener: () => undefined, + removeListener: () => undefined, + dispatchEvent: () => false, + })), + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); + rowHeight = ROW; +}); + +function Rows({ + labels, + hasAnimatedChanges = true, +}: { + labels: string[]; + hasAnimatedChanges?: boolean; +}) { + return ( +
    + + {labels.map(label => ( + + ))} + +

    Below the list

    +

    + A footer layout does not move +

    +
    + ); +} + +const rowOf = (label: string) => + Array.from(document.querySelectorAll('li')).find( + li => li.textContent === label, + ) as HTMLElement; + +describe('List update motion', () => { + it('under a finger, rows that change place move and new rows fade in', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + expect(motionOf(rowOf('C'))).toBeUndefined(); + // Remove B: C moves up one row; A stays. + rerender(); + expect(motionOf(rowOf('C'))).toBeDefined(); + expect(motionOf(rowOf('A'))).toBeUndefined(); + // Insert D first: everything below moves down, D fades in. + rerender(); + expect(motionOf(rowOf('D'), 'opacity')).toBeDefined(); + expect(motionOf(rowOf('A'))).toBeDefined(); + }); + + it('a new row shows nothing while the row it displaced still crosses its band, then fades in, arriving with it', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + // Insert B second: C slides down out of B's band. + rerender(); + const inserted = rowOf('B'); + const displaced = rowOf('C'); + expect(motionOf(inserted, 'opacity')).toBeDefined(); + // Sampled from the one start the browser gives the commit's motions + // (calls from rest start when it commits them), never from a clock read + // after the rerender, which a busy runner moves. + const at = await (motionOf(displaced, 'y') as RowMotion).handle.started; + let crossing = 0; + let previous = 0; + for (let t = 0; t <= 600; t += 5) { + const y = presentation(displaced, 'y', at + t); + const shown = presentation(inserted, 'opacity', at + t); + // C's label within half a row of B's: B shows nothing (the labels + // would overlap; rows have no background to hide one). + if (y < -ROW / 2 - 0.01) { + expect(shown, `t=${t}`).toBe(0); + crossing += 1; + } + expect(shown, `t=${t}`).toBeGreaterThanOrEqual(previous); + previous = shown; + } + expect(crossing).toBeGreaterThan(3); + expect(presentation(inserted, 'opacity', at + 600)).toBe(1); + }); + + it('a removed row collapses in place, the row below glued to its bottom edge, then goes', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + const removed = rowOf('B'); + // One instant for the whole commit, as a browser's frame gives every + // motion started in it (here each would start when it is created). + const at = motionNow(); + const clock = vi.spyOn(performance, 'now').mockReturnValue(at); + rerender(); + clock.mockRestore(); + // B is back for its exit, in a ghost hidden from assistive tech, at its + // old place. + expect(removed.isConnected).toBe(true); + const ghost = removed.parentElement as HTMLElement; + expect(ghost.hasAttribute('data-astryx-leaving')).toBe(true); + expect(ghost.getAttribute('aria-hidden')).toBe('true'); + expect(ghost.inert).toBe(true); + expect(ghost.nextElementSibling).toBe(rowOf('C')); + const next = rowOf('C'); + for (let t = 0; t <= 600; t += 10) { + const ghostY = presentation(ghost, 'y', at + t); + // B's content stays where it was while the clip closes over it. + expect(ghostY + presentation(removed, 'y', at + t), `t=${t}`).toBeCloseTo( + 0, + 6, + ); + // The clip's bottom edge (B's old top + its height + the ghost's + // offset) is C's top (its new place + its offset), every frame. + expect(ROW + ROW + ghostY, `t=${t}`).toBeCloseTo( + ROW + presentation(next, 'y', at + t), + 6, + ); + } + expect(presentation(ghost, 'y', at + 600)).toBeCloseTo(-ROW, 1); + // Gone once it rests. + await vi.waitFor(() => expect(ghost.isConnected).toBe(false), { + timeout: 3000, + }); + }); + + it('a removed row collapses on the table spring and stays exactly as long as its collapse, whatever a theme writes', async () => { + stubPointer('touch'); + // The table spring is an internal constant: a variable written the way a + // theme would write one (1.5 s, on the root, which a theme switch brings + // in) changes nothing. + document.documentElement.style.setProperty( + '--motion-list-update-table-spring', + '1.5s 0', + ); + document.documentElement.setAttribute('data-theme', 'slow-table'); + try { + const {rerender} = render(); + await act(async () => undefined); + const removed = rowOf('B'); + const at = motionNow(); + const clock = vi.spyOn(performance, 'now').mockReturnValue(at); + rerender(); + clock.mockRestore(); + const ghost = removed.parentElement as HTMLElement; + expect(ghost.hasAttribute('data-astryx-leaving')).toBe(true); + const collapse = motionOf(ghost, 'y') as RowMotion; + expect(collapse).toBeDefined(); + // Closed where the table's spring arrives, where the theme's 1.5 s + // spring would still be on its way. + expect(presentation(ghost, 'y', at + 600)).toBeCloseTo(-ROW, 1); + // Gone when the collapse ends, with nothing left behind. + await collapse.handle.finished; + await Promise.resolve(); + expect(ghost.isConnected).toBe(false); + } finally { + document.documentElement.style.removeProperty( + '--motion-list-update-table-spring', + ); + document.documentElement.removeAttribute('data-theme'); + } + }); + + it('a removed row leaves in the same commit that turns the motion off', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + const removed = rowOf('B'); + rerender(); + const ghost = removed.parentElement as HTMLElement; + expect(ghost.hasAttribute('data-astryx-leaving')).toBe(true); + rerender(); + expect(ghost.isConnected).toBe(false); + expect(motionOf(ghost, 'y')).toBeUndefined(); + }); + + it('on the default table spring a removed row leaves within a second (INV7)', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + const removed = rowOf('B'); + rerender(); + const ghost = removed.parentElement as HTMLElement; + expect(ghost.hasAttribute('data-astryx-leaving')).toBe(true); + await vi.waitFor(() => expect(ghost.isConnected).toBe(false), { + timeout: 1000, + }); + }); + + it('a row that slides across rows moving the other way rides above them for its slide', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + const rides = (label: string) => + rowOf(label).hasAttribute('data-astryx-travelling'); + // D moves first: it crosses A, B and C, which each move down one row. + rerender(); + expect(rides('D')).toBe(true); + expect(['A', 'B', 'C'].filter(rides)).toEqual([]); + // Once its slide rests, it rides with the others again. + await vi.waitFor(() => expect(motionOf(rowOf('D'))).toBeUndefined(), { + timeout: 3000, + }); + expect(rides('D')).toBe(false); + // A removal moves every row the same way: nothing crosses, nothing rides. + rerender(); + expect(motionOf(rowOf('B'))).toBeDefined(); + expect(['D', 'B', 'C'].filter(rides)).toEqual([]); + }); + + it('reads no layout at all without hasAnimatedChanges', async () => { + stubPointer('touch'); + const reads = vi.fn(); + const top = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + 'offsetTop', + ); + Object.defineProperty(HTMLElement.prototype, 'offsetTop', { + configurable: true, + get(this: HTMLElement) { + reads(); + return top?.get?.call(this) as number; + }, + }); + const off = render( + , + ); + await act(async () => undefined); + off.rerender(); + expect(reads).not.toHaveBeenCalled(); + if (top != null) { + Object.defineProperty(HTMLElement.prototype, 'offsetTop', top); + } + }); + + it('never moves the content after the list: it takes its place by layout', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + rerender(); + const below = screen.getByTestId('below'); + expect(motionOf(below)).toBeUndefined(); + expect(below.style.translate).toBe(''); + // The rows inside the list still move. + expect(motionOf(rowOf('C'))).toBeDefined(); + }); + + it('moves nothing with a mouse, or without hasAnimatedChanges', async () => { + stubPointer('mouse'); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + const first = render(); + await act(async () => undefined); + first.rerender(); + expect(motionOf(rowOf('C'))).toBeUndefined(); + first.rerender(); + expect(motionOf(rowOf('D'), 'opacity')).toBeUndefined(); + expect(motionOf(screen.getByTestId('below'))).toBeUndefined(); + first.unmount(); + + stubPointer('touch'); + const second = render( + , + ); + await act(async () => undefined); + second.rerender(); + expect(motionOf(rowOf('C'))).toBeUndefined(); + }); + + it('clips its rows to its box while they move after it gets shorter, and only then', async () => { + stubPointer('touch'); + // jsdom lays nothing out: the list is as tall as its rows. + const height = vi + .spyOn(HTMLElement.prototype, 'offsetHeight', 'get') + .mockImplementation(function (this: HTMLElement) { + if (this.tagName === 'UL') { + return ( + this.querySelectorAll(':scope > li:not([data-astryx-leaving])') + .length * ROW + ); + } + return this.tagName === 'LI' ? ROW : 0; + }); + const {rerender} = render(); + await act(async () => undefined); + const list = document.querySelector('ul') as HTMLElement; + // Taller: nothing to clip. + rerender(); + expect(list.style.overflowY).toBe(''); + // Shorter: its rows are clipped to its box while they move, not after. + rerender(); + expect(list.style.overflowY).toBe('clip'); + await waitFor(() => expect(list.style.overflowY).toBe(''), { + timeout: 3000, + }); + height.mockRestore(); + }); + + it('reads the rows again when the list resizes between commits, so an update starts each row where it was', async () => { + // The browser's resize notifications, delivered when the test says. + let notify = () => {}; + vi.stubGlobal( + 'ResizeObserver', + class { + targets: Element[] = []; + constructor(callback: ResizeObserverCallback) { + notify = () => + callback( + this.targets.map(target => ({target}) as ResizeObserverEntry), + this, + ); + } + observe(target: Element) { + this.targets.push(target); + } + unobserve(target: Element) { + this.targets = this.targets.filter(other => other !== target); + } + disconnect() { + this.targets = []; + } + }, + ); + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + // Every row grows with no commit (a stylesheet, a web font): the list + // resizes. + rowHeight = 52; + notify(); + // Read at the commit's own instant (the removal's exit takes a moment). + const now = motionNow(); + const clock = vi.spyOn(performance, 'now').mockReturnValue(now); + rerender(); + // C sat two 52 px rows down and now sits one down: it starts 52 px below + // its new place, not the 28 px the first commit's layout would say. + expect(presentation(rowOf('C'), 'y', now)).toBeCloseTo(52, 0); + clock.mockRestore(); + }); + + it('leaves a list a reorder session owns to the reorder', async () => { + stubPointer('touch'); + const {rerender} = render(); + await act(async () => undefined); + document.querySelector('ul')?.setAttribute('data-astryx-reordering', ''); + rerender(); + expect(motionOf(rowOf('C'))).toBeUndefined(); + expect(motionOf(rowOf('A'))).toBeUndefined(); + }); +}); diff --git a/packages/core/src/List/useListUpdateMotion.ts b/packages/core/src/List/useListUpdateMotion.ts new file mode 100644 index 0000000000000..2052b1e2f4c14 --- /dev/null +++ b/packages/core/src/List/useListUpdateMotion.ts @@ -0,0 +1,579 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useListUpdateMotion.ts + * @input A List's element, whether it animates its changes, the touch + * presentation (utils/touchPresentation.ts), the row moves of + * utils/rowMotion.ts and the table spring (motion/uikit/list.ts, an + * internal constant) + * @output `useListUpdateMotion`: after every commit that inserts, removes or + * reorders rows, the rows that stay slide from where they were to where + * they are, and inserted rows fade in once the rows crossing them have + * cleared and removed rows collapse in place, the way a UIKit table + * animates its updates; a row crossing rows that move the other way + * carries `TRAVELLING_ATTRIBUTE` for its slide + * @position Internal interaction utility for any list root whose direct + * children are its rows; List calls it with `hasAnimatedChanges` + * + * UIKit's reference (iOS 26.2): a table's insert, delete, move and reload + * animations and its batch updates all run on one critically damped spring + * (`list.update.tableSpring`, response 0.3 s). A deleted cell collapses: its + * height (content, separator and, after a swipe, its action) shrinks to 0 + * from the bottom while the rows below slide up on the same spring, the next + * row's top edge always on its bottom edge. + * + * HOW IT RUNS, compositor only. After each commit the rows' layout positions + * are read once (`offsetTop` inside the list, which ignores transforms) and + * compared with the previous commit's (read again whenever the list's box + * resizes in between, so a layout change no commit made never leaves them + * stale): a row that moved is put back with an + * inverse `translate` in the same frame and springs home; a row that is new + * fades in on the same spring's clock (UIKit's `.fade` row animation). A + * UIKit cell is opaque: a cell sliding over an inserted one hides it, and a + * moved cell passes over its neighbours. Rows here have no background, so a + * new row shows nothing until the rows crossing its band have carried their + * labels half a row past its own, then fades in, arriving with them; and a + * row sliding across rows that move the other way (the less common way, up + * on a tie) rides above them for its slide with the list's surface behind it + * (List/ListItem.tsx paints it). A removed row comes back for its exit as + * a ghost (`GHOST_ATTRIBUTE`, inert and hidden from assistive tech) at its + * place: a clipping box the row's old size whose bottom edge rises with the + * next row's top. The box translates up by the row's height while the row + * inside translates down by as much, so the content stays put and the clip + * closes, compositor only; a ghost below another removed row rides up with + * it. The ghost goes when its collapse ends, and at once, its motion + * stopped, when the motion stops owning the list (hasAnimatedChanges off, a + * mouse, an unmount): the layer's one transient exit copy + * (`architecture:component-style-authoring` INV7), gone within a second on + * the table spring. A row moved again mid-motion + * keeps its velocity, and its curve: a layout shift never changes a running + * motion's spring (a reorder's drop settles on its own), so the table spring + * applies to rows at rest. Page content after the list is not the list's to move: + * the list's height changes by layout at the commit (`spec:AST-094` FR5 + * forbids animating layout), so content after it takes its new place at + * once, with no transient translate on it. A list that got shorter clips + * its rows to its box (`overflow-y: clip`) while they move, so the rows + * sliding up into the gap never paint over that content; a removed last + * row's copy, outside the new box, is clipped with them. With motion off, nothing is read. + * + * Under reduced motion nothing travels (`design:reduced-motion`): every row + * motion takes the animator's own Reduced Motion handling, so a removed row + * fades out where it is, a new row fades in where it lands, and the rows + * that move cross-fade into place. + * + * It runs under any finger (useTouchPresentation: a coarse primary pointer, + * iOS and Android alike; one touch model). With a mouse (the theme's + * presentation) nothing moves. A list root that + * carries `data-astryx-reordering` (a drag session in progress) is left to + * the reorder: its rows' places are remembered, nothing is moved. + * + * SYNC: When modified, update List/List.tsx and + * List/__tests__/ListUpdates.interaction.browser.spec.ts. + */ + +import {useRef, type RefObject} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import {animatorFor, type MotionCurve} from '../motion/animator'; +import {solveSpring, toSpring, type SpringCurve} from '../motion/spring'; +import {list} from '../motion/uikit/list'; +import { + animateRow, + motionNow, + motionOf, + playRow, + presentation, + releaseMotion, + springHome, + stopRow, +} from '../utils/rowMotion'; +import {observeResize} from '../utils/sharedResizeObserver'; +import {useTouchPresentation} from '../utils/touchPresentation'; + +const SPRING = list.update.tableSpring; + +/** Moves under half a pixel are layout noise, not updates. */ +const MIN_MOVE_PX = 0.5; + +/** + * Written on a row that slides across rows moving the other way, for the + * length of its slide: it rides above them with the list's surface behind it + * (List/ListItem.tsx), as a UIKit cell, opaque and on top, passes over its + * neighbours. Rows here have no background of their own. + */ +export const TRAVELLING_ATTRIBUTE = 'data-astryx-travelling'; + +/** + * Marks a removed row's ghost: the clipping box its exit collapses in. Not a + * row: the rows a commit compares never include it. + */ +export const GHOST_ATTRIBUTE = 'data-astryx-leaving'; + +const ghostStyles = stylex.create({ + ghost: { + position: 'absolute', + boxSizing: 'border-box', + margin: 0, + padding: 0, + listStyle: 'none', + overflow: 'hidden', + pointerEvents: 'none', + }, + // Its inline position is its static one (the list's content box, in + // either direction); its block position, the row's old place. + box: (top: string, inlineSize: string, blockSize: string) => ({ + insetBlockStart: top, + inlineSize, + blockSize, + }), +}); + +/** A row's place after a commit: its top inside the list and its height. */ +interface Box { + readonly top: number; + readonly height: number; +} + +/** The rows after a commit, in order, with their boxes and the list's height. */ +interface Layout { + readonly rows: ReadonlyArray; + readonly boxes: ReadonlyMap; + readonly height: number; +} + +/** + * Writes what the Web Animations running on `row` and its parts present + * (a swipe's travel, on the compositor) as inline styles. A removed row is + * detached from the document, which drops those animations, and the + * removal's collapse re-inserts it: without this it would show its resting + * state for the length of the collapse. Animations on pseudo-elements, or + * that cannot write their values, are left alone. + */ +export function keepPresentation(row: HTMLElement): void { + if (typeof row.getAnimations !== 'function') { + return; + } + for (const animation of row.getAnimations({subtree: true})) { + try { + animation.commitStyles(); + } catch { + // A pseudo-element's or an unrendered target's animation: nothing to + // keep. + } + } + // The parts' owners clean up after the row does, before React removes it, + // and may reset what was just written (a swipe gives its row back its own + // translation): keep it, for `ghostOf` to put back. + const styled: (readonly [HTMLElement | SVGElement, string])[] = []; + for (const part of [ + row, + ...row.querySelectorAll('*'), + ]) { + if (part.style.length > 0) { + styled.push([part, part.style.cssText]); + } + } + keptStyles.set(row, styled); +} + +/** + * The inline styles of a leaving row and its parts as `keepPresentation` + * left them, until the removal's exit puts the row back. + */ +const keptStyles = new WeakMap< + HTMLElement, + ReadonlyArray +>(); + +/** + * Puts a removed row back for its exit: inside a clipping box at its old + * place (`box`, inside the list) spanning the list's content box, so the row + * lays out inside it as it did in the list, before `next` (the first row that + * followed it and is still there) so the rows around it keep their places in + * the list's order. The box is inert and hidden from assistive tech. + */ +function ghostOf( + element: HTMLElement, + row: HTMLElement, + box: Box, + next: HTMLElement | null, + wasLast: boolean, +): HTMLElement { + const doc = element.ownerDocument; + const ghost = doc.createElement( + element.tagName === 'UL' || element.tagName === 'OL' ? 'li' : 'div', + ); + ghost.setAttribute(GHOST_ATTRIBUTE, ''); + ghost.setAttribute('aria-hidden', 'true'); + ghost.inert = true; + // Its containing block is the list when the list is positioned, else the + // rows' offset parent above it. + const style = getComputedStyle(element); + const listed = row.offsetParent === element || style.position !== 'static'; + const top = box.top + (listed ? 0 : element.offsetTop); + const width = + element.clientWidth - + (Number.parseFloat(style.paddingInlineStart) || 0) - + (Number.parseFloat(style.paddingInlineEnd) || 0); + const props = stylex.props( + ghostStyles.ghost, + ghostStyles.box(`${top}px`, `${width}px`, `${box.height}px`), + ); + ghost.className = props.className ?? ''; + for (const [name, value] of Object.entries(props.style ?? {})) { + ghost.style.setProperty(name, String(value)); + } + ghost.append(row); + if (!wasLast) { + // The row keeps the divider a row that is not the last draws. + const tail = doc.createElement('span'); + tail.hidden = true; + ghost.append(tail); + } + element.insertBefore(ghost, next?.parentElement === element ? next : null); + // The row's parts show what `keepPresentation` wrote as it left. Any + // animation they still carry applies again now that they are back in the + // document (a detached element reports none), and would fight that: stop + // it. + if (typeof row.getAnimations === 'function') { + for (const animation of row.getAnimations({subtree: true})) { + animation.cancel(); + } + } + // What an owner's cleanup reset after `keepPresentation` comes back: the + // row shows what was on screen when it left. + for (const [part, cssText] of keptStyles.get(row) ?? []) { + part.style.cssText = cssText; + } + keptStyles.delete(row); + return ghost; +} + +/** + * The sideways offset a row's own inline `translate` carries (a swipe that + * moves the row itself, as `keepPresentation` kept it), in px, or 0. + */ +function sidewaysOffset(row: HTMLElement): number { + const [x = ''] = row.style.translate.trim().split(/\s+/); + const value = Number.parseFloat(x); + return Number.isFinite(value) ? value : 0; +} + +/** One row's slide in a commit: where its box was and is, inside the list. */ +interface Slide { + readonly row: HTMLElement; + readonly from: number; + readonly to: number; + readonly height: number; +} + +/** + * The progress of the update spring (0 → 1) at which a row that just + * appeared at `top` may start to fade in: once every row sliding across its + * band has carried its label more than half a row past the new row's label, + * so the two labels never overlap. (A UIKit cell sliding over an inserted + * one hides it with its opaque background; rows here have none.) + */ +function clearedAt( + top: number, + height: number, + slides: ReadonlyArray, +): number { + const center = top + height / 2; + let cleared = 0; + for (const slide of slides) { + const distance = slide.to - slide.from; + const start = slide.from + slide.height / 2; + // Label centers half a row apart: the labels no longer overlap. + const apart = (height + slide.height) / 4; + const [enters, leaves] = + distance > 0 + ? [ + (center - apart - start) / distance, + (center + apart - start) / distance, + ] + : [ + (start - center - apart) / -distance, + (start - center + apart) / -distance, + ]; + if (enters < 1 && leaves > 0) { + cleared = Math.max(cleared, Math.min(1, leaves)); + } + } + return cleared; +} + +/** + * A new row's fade on the update spring's clock: it holds `from` until the + * spring's progress reaches `after` (the rows crossing its band have cleared + * it), then follows the progress to 1, arriving with the rows around it. + */ +function fadeIn( + from: number, + progress: SpringCurve, + duration: number, + after: number, +): MotionCurve { + // Always leave the fade a tenth of the way to run. + const begin = Math.min(after, 0.9); + const at = (t: number) => { + if (t >= duration) { + return 1; + } + const p = progress.value(Math.max(0, t)); + return ( + from + (1 - from) * Math.min(1, Math.max(0, (p - begin) / (1 - begin))) + ); + }; + return { + duration, + at, + velocity: t => { + const step = 1e-3; + const t0 = Math.max(0, t - step); + return (at(t + step) - at(t0)) / (t + step - t0); + }, + }; +} + +function rowsOf(element: HTMLElement): HTMLElement[] { + return Array.from(element.children).filter( + (child): child is HTMLElement => + child instanceof HTMLElement && !child.hasAttribute(GHOST_ATTRIBUTE), + ); +} + +/** The rows, each row's layout box inside the list, and the list's height. */ +function readLayout(element: HTMLElement): Layout { + const rows = rowsOf(element); + const boxes = new Map(); + for (const row of rows) { + // Inside the list: content above it changing size moves no row. + const base = row.offsetParent === element ? 0 : element.offsetTop; + boxes.set(row, {top: row.offsetTop - base, height: row.offsetHeight}); + } + return {rows, boxes, height: element.offsetHeight}; +} + +export function useListUpdateMotion( + listRef: RefObject, + enabled: boolean, +): void { + const animates = useTouchPresentation().isTouch && enabled; + /** + * The rows and their layout boxes after the previous commit, or after the + * last resize of the list since. + */ + const layoutRef = useRef(null); + /** The removed rows' copies still collapsing, each with its row. */ + const ghostsRef = useRef(new Map()); + /** The commit whose motions hold the list's clip; a newer one takes it. */ + const clipRef = useRef(0); + + // External system (`architecture:react-component-runtime` INV3): the rows' + // shared motion animators (utils/rowMotion.ts), the list's clip, and the + // removed rows' copies this effect adds to the list. Each commit reads the + // rows' layout and moves them from where they were; the unmount cleanup + // below stops them and removes the copies. + useIsomorphicLayoutEffect(() => { + const element = listRef.current; + // Motion off (no `hasAnimatedChanges`, or a mouse): read + // nothing at all. The first commit after it turns on only records. + if (element == null || !animates) { + layoutRef.current = null; + return; + } + const layout = readLayout(element); + const {rows, boxes} = layout; + const before = layoutRef.current; + layoutRef.current = layout; + // The first commit, or a reorder session that owns the rows: remember + // where rows are, move nothing. + if (before == null || element.hasAttribute('data-astryx-reordering')) { + return; + } + const at = motionNow(); + const motions: Promise[] = []; + const slides: Slide[] = []; + const entering: HTMLElement[] = []; + for (const row of rows) { + const now = boxes.get(row)?.top ?? 0; + const was = before.boxes.get(row)?.top; + if (was == null) { + entering.push(row); + } else if (Math.abs(was - now) >= MIN_MOVE_PX) { + slides.push({row, from: was, to: now, height: row.offsetHeight}); + } + } + // Rows sliding both ways cross each other: the rows moving the less + // common way (up, on a tie) ride above the rest for their slide. + const up = slides.filter(slide => slide.to < slide.from); + const down = slides.filter(slide => slide.to > slide.from); + const travelling = new Set( + up.length > 0 && down.length > 0 + ? up.length <= down.length + ? up + : down + : [], + ); + for (const slide of slides) { + const {row} = slide; + const rides = travelling.has(slide); + if (rides) { + row.setAttribute(TRAVELLING_ATTRIBUTE, ''); + } + const slid = springHome(row, 'y', slide.from - slide.to, SPRING, at).then( + arrived => { + if (arrived) { + releaseMotion(row, 'translate'); + } + if (rides && motionOf(row, 'y') == null) { + row.removeAttribute(TRAVELLING_ATTRIBUTE); + } + }, + ); + motions.push(slid); + } + if (entering.length > 0) { + // The spring the slides run: new rows time their fade on its + // progress. + const progress = solveSpring(toSpring(SPRING), { + from: 0, + to: 1, + }); + const duration = progress.settleTime(0.001); + for (const row of entering) { + // New: from the opacity it has (0 when new), once the rows crossing + // its band have cleared it. + const from = presentation(row, 'opacity', at); + const start = from >= 1 ? 0 : from; + const after = clearedAt( + boxes.get(row)?.top ?? 0, + row.offsetHeight, + slides, + ); + // From rest it starts with the slides, when the browser commits + // them; a fade already running continues from the frame on screen. + const fade = playRow( + row, + 'opacity', + fadeIn(start, progress, duration, after), + SPRING, + motionOf(row, 'opacity') == null ? undefined : at, + ).finished.then(arrived => { + if (arrived) { + releaseMotion(row, 'opacity'); + } + }); + motions.push(fade); + } + } + // Removed rows collapse in place on the slides' spring, the row below + // each glued to its bottom edge (UIKit's deleteRows). + let removedAbove = 0; + const ghosts = ghostsRef.current; + for (const [index, row] of before.rows.entries()) { + const box = before.boxes.get(row); + if (row.isConnected || box == null) { + continue; + } + const next = + before.rows.slice(index + 1).find(later => later.isConnected) ?? null; + const ghost = ghostOf( + element, + row, + box, + next, + index === before.rows.length - 1, + ); + const lift = removedAbove; + removedAbove += box.height; + // From rest, like the slides (springHome): the browser's commit sets + // the start of all of them, so the edges meet on every frame. Under + // reduced motion the removed row fades out where it is instead. + // A row a swipe moved sideways on itself keeps that offset: the + // removal's y joins it on the row's one animator, so the collapse + // moves it down only. + const across = sidewaysOffset(row); + if (across !== 0) { + animatorFor(row).set({x: across}); + } + motions.push( + animateRow(row, {y: box.height}, SPRING, {crossfadeAs: 'exit'}) + .finished, + ); + // The copy leaves when its collapse ends (arrival or interruption). + ghosts.set(ghost, row); + motions.push( + animateRow(ghost, {y: -(box.height + lift)}, SPRING, { + crossfadeAs: 'exit', + }).finished.then(() => { + ghosts.delete(ghost); + ghost.remove(); + }), + ); + } + // Content after the list took its new place by layout at this commit. + // A list that got shorter clips its rows to its box until they rest, so + // the rows sliding up into the gap never paint over that content; a clip + // still held by a running motion stays with this commit's motions. + if ( + motions.length > 0 && + (layout.height < before.height - MIN_MOVE_PX || + element.style.getPropertyValue('overflow-y') === 'clip') + ) { + const mine = ++clipRef.current; + element.style.setProperty('overflow-y', 'clip'); + void Promise.all(motions).then(() => { + if (clipRef.current === mine) { + element.style.removeProperty('overflow-y'); + } + }); + } + }); + + // External system (`architecture:react-component-runtime` INV3): the + // removed rows' copies this hook put in the list, DOM outside React, and + // the list's clip. When the motion stops owning the list (hasAnimatedChanges + // off, a mouse, an unmount), each copy leaves at once with its motion + // stopped, and the clip goes. + useIsomorphicLayoutEffect(() => { + if (!animates) { + return; + } + const ghosts = ghostsRef.current; + const element = listRef.current; + return () => { + clipRef.current += 1; + element?.style.removeProperty('overflow-y'); + for (const [ghost, row] of ghosts) { + stopRow(row, 'translate'); + stopRow(ghost, 'translate', 'opacity'); + ghost.remove(); + } + ghosts.clear(); + }; + }, [listRef, animates]); + + // Layout that changes with no commit (a web font arriving, a rotation that + // rewraps rows, a stylesheet or theme changing row heights, a row resizing + // itself) would leave the places above stale, and the next update would + // start its rows from where they no longer were: read them again whenever + // the list's box changes size. External system + // (`architecture:react-component-runtime` INV3): a resize observation of the + // list's box, released by the cleanup. + useIsomorphicLayoutEffect(() => { + const element = listRef.current; + if (element == null || !animates) { + return; + } + return observeResize(element, () => { + if (layoutRef.current == null) { + return; + } + layoutRef.current = readLayout(element); + }); + }, [listRef, animates]); +} diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsx index 683f7dbee9280..d701adf00b727 100644 --- a/packages/core/src/RadioList/RadioListItem.tsx +++ b/packages/core/src/RadioList/RadioListItem.tsx @@ -31,6 +31,7 @@ import {usePressFeedback} from '../hooks/usePressFeedback'; import {useIndicator} from '../Indicator'; import {Item, type ItemAlign} from '../Item'; import {themeProps} from '../utils/themeProps'; +import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; // The touch press's paint, declared by the shared overlay styles on the // element the controller writes to (`pressedAlpha`) at the press's strength, @@ -148,6 +149,10 @@ const rowStyles = stylex.create({ // strength still lands on the row, which is where the layer over the // circle reads it. backgroundImage: 'none', + // ...and the row's touch press layer (Item's `cell`): no box. + '::before': { + content: 'none', + }, }, // The mouse press (a finger's lives on `data-astryx-press`): the row is // pressed, but not through a nested link or button, which keep their own @@ -395,6 +400,10 @@ export function RadioListItem({ // the painting row element (Item), the same element that carries the // theme target, so a theme's hover styling stays in step with the tint. !isDisabled && indicatorScope, + // The row owns the strength the circle's layer reads, and its + // release (Item's touch layer drops the row's own under a finger: + // this row has no layer of its own, so it keeps the release). + !isDisabled && interactionOverlayStyles.pressedAlpha, // Restore the bare default look: zero Item's padding/radius and its // interactive hover/press background. Applied after Item's own base // styles so it wins within the base layer; a `radio-list-item` theme diff --git a/packages/core/src/TreeList/TreeList.doc.mjs b/packages/core/src/TreeList/TreeList.doc.mjs index 7251c7c53fbca..75058c1156850 100644 --- a/packages/core/src/TreeList/TreeList.doc.mjs +++ b/packages/core/src/TreeList/TreeList.doc.mjs @@ -137,7 +137,7 @@ export const docs = { usage: { anatomy, description: - 'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships.', + 'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships. Under a finger, a row\'s children slide out from under it as it expands, and back under it as it collapses, as in an iOS outline list.', bestPractices: [ {guidance: true, description: 'Provide meaningful labels and icons for each node to make the hierarchy easy to scan.'}, {guidance: true, description: 'Pre-expand important branches so users see key content immediately.'}, diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsx index dca4724b7eff1..801564b3641c7 100644 --- a/packages/core/src/TreeList/TreeList.tsx +++ b/packages/core/src/TreeList/TreeList.tsx @@ -264,6 +264,9 @@ export function TreeList({ onToggleExpand: handleToggle, onActivate: activateItem, hasRovingTabIndex: true, + // Rows still sliding away after a collapse sit in an inert group + // (useTreeExpansionMotion): arrow keys skip them, as if already gone. + itemSelector: '[role="treeitem"]:not([inert] *)', // Rows are named by their label (AR1); typeahead matches that label, not // the chevron toggle, start content or description. matchLabelledBy: true, @@ -316,14 +319,16 @@ export function TreeList({ ? [...ancestorsIsLast, isLast] : ancestorsIsLast; - const renderedChildren = - isExpanded && hasChildren - ? renderItems( + // Rendered by the row when it shows them: while expanded, and while + // they slide away after a collapse (useTreeExpansionMotion). + const renderChildren = hasChildren + ? (): ReactNode => + renderItems( item.children ?? [], nestedLevel + 1, ancestorsIsLastForChildren, ) - : undefined; + : undefined; return ( ReactNode; /** 1-based position of this item among its siblings (aria-posinset). */ posInSet: number; /** Number of siblings at this level (aria-setsize). */ @@ -400,12 +412,14 @@ export function TreeListItem({ onToggle, density, variant, - renderedChildren, + renderChildren, posInSet, setSize, isTabbable, }: TreeListItemInternalProps) { const pressable = usePressFeedback(); + const {showsChildren, groupRef} = useTreeExpansionMotion(isExpanded); + const renderedChildren = showsChildren ? renderChildren?.() : undefined; const t = useTranslator(); const labelId = useId(); const descriptionId = useId(); @@ -532,6 +546,8 @@ export function TreeListItem({ // The button/container owns the chevron color (--color-icon-secondary); // inheriting keeps that as the single source. color="inherit" + // The touch presentation turns the glyph with the expansion's spring. + data-tree-chevron="" xstyle={[ styles.chevronSvg, isExpanded ? styles.chevronExpanded : styles.chevronCollapsed, @@ -679,6 +695,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, @@ -703,8 +723,13 @@ export function TreeListItem({
    {innerContent}
    - {isExpanded && renderedChildren != null && ( -
      + {renderedChildren != null && ( +
        {renderedChildren}
      )} diff --git a/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts new file mode 100644 index 0000000000000..1e086300354b1 --- /dev/null +++ b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts @@ -0,0 +1,738 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TreeListExpand.interaction.browser.spec.ts + * @input The built TreeList story, real touch input (Chromium CDP / WebKit's + * input command), the interaction harness, and the outline spring from the + * UIKit constants table (motion/uikit/list.ts) + * @output Interaction and animation proofs for a TreeList row's expand and + * collapse under a finger: the children slide out from under the parent + * as one block inside the group's clip, the rows below move with them and + * the chevron turns, all on the outline spring, sampled frame by frame; a + * collapse slides them back and removes them with no jump, no child + * showing outside the group up to the frame it leaves; the rows below + * keep moving while the main thread is blocked, with no Layout or Paint; + * under reduced motion an expand and a collapse cross-fade, opacity only, + * within 200 ms (`design:reduced-motion`); right to left mirrors the + * chevron's turn; a theme's outline spring times it; content after the + * tree takes its new place by layout at once, with no translate on it and + * a fixed element inside it staying fixed; a storyboard of the expand + * @position Interaction evidence for TreeList/useTreeExpansionMotion.ts + * under a finger (List/__tests__/touchStory.ts), with an Android case that + * moves the same way and a mouse case where the children come and go in + * one frame + */ + +import {expect, test, type Locator, type Page} from '@playwright/test'; +import { + animationStoryboard, + blockMainThread, + busyWindowProof, + compareCurve, + countBetween, + holdAnimations, + markElement, + releaseAnimations, + seekAnimations, + startScreencast, + timeline, + touchDriver, + trackMarker, + traceRendering, + waitForAnimation, + withStorybook, + writeEvidence, +} from '@astryxdesign/interaction-harness'; +import {openStory} from '../../List/__tests__/touchStory'; +import {expectReducedMotionCrossFade} from '../../List/__tests__/reducedMotion'; +import { + blockBehindBeacon, + installBeacon, + sampleVideoPoints, +} from '../../List/__tests__/rowPixels'; +import {solveSpring, toSpring} from '../../motion/spring'; +import {list} from '../../motion/uikit/list'; + +const storybook = withStorybook(test); + +const STORY = 'core-treelist--basic'; +const SPRING = toSpring(list.update.outlineSpring); +/** The spring's progress (0 → 1) t ms after it starts. */ +const progress = (t: number) => + solveSpring(SPRING, {from: 0, to: 1}).value(t / 1000); +/** Where it settles: every sampled curve is judged up to here. */ +const SETTLE_MS = + solveSpring(SPRING, {from: 0, to: 1}).settleTime(0.001) * 1000; + +/** A tree row by its item id (an ancestor row contains its label too). */ +const treeItem = (page: Page, id: string) => + page.locator(`[role="treeitem"][data-tree-id="${id}"]`); + +/** The toggle of the "components" folder, its group, a child and a row below. */ +function parts(page: Page) { + const parent = treeItem(page, 'components'); + return { + parent, + // Its own toggle, group and chevron: not a descendant row's. + toggle: parent.locator(':scope > :not([role="group"]) [data-tree-toggle]'), + group: parent.locator(':scope > [role="group"]'), + chevron: parent.locator( + ':scope > :not([role="group"]) [data-tree-chevron]', + ), + child: treeItem(page, 'button'), + below: treeItem(page, 'app'), + }; +} + +/** How many tree rows and chevron parts show at less than full opacity. */ +const hiddenParts = async (page: Page) => + page.evaluate( + () => + [ + ...document.querySelectorAll( + '[role="treeitem"], [data-tree-chevron], [data-tree-chevron] *', + ), + ].filter(element => getComputedStyle(element).opacity !== '1').length, + ); + +/** The `y` of an element's `translate`, as the engine presents it. */ +const translateY = async (element: Locator) => + element.evaluate(el => { + const value = getComputedStyle(el).translate; + if (value === 'none' || value === '') { + return 0; + } + const [, y = '0px'] = value.split(' '); + return Number.parseFloat(y); + }); + +/** The additive `rotate` on the chevron, degrees. */ +const rotation = async (element: Locator) => + element.evaluate(el => { + const value = getComputedStyle(el).rotate; + return value === 'none' || value === '' ? 0 : Number.parseFloat(value); + }); + +async function tapToggle(page: Page) { + const {toggle} = parts(page); + const box = await toggle.boundingBox(); + if (box == null) { + throw new Error('no toggle'); + } + const driver = await touchDriver(page); + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); +} + +async function open(page: Page) { + await openStory(page, storybook(), STORY); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the expansion moves under a finger only'); + await expect(parts(page).below).toBeVisible(); +} + +test('a busy first frame delays the expand instead of skipping into it', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'WebKit starts an animation created just before a block at its last frame time (motion/animator.ts, known limits)', + ); + await open(page); + const {toggle, below} = parts(page); + await expect(below).toBeVisible(); + // The toggle's handler commits the expand and starts its motions; 150 ms + // of script then hold the main thread before the first frame. The motions + // start when the browser commits them, so the first frame due after the + // block shows the row below at most one frame from where it was, a group's + // height up from its new place. + const result = await below.evaluate( + async (row, toggleButton) => + new Promise<{ + first: number; + pending: boolean; + startedAfterBlock: boolean; + }>(resolve => { + // The expand's commit inserts the group; this observer runs right + // after it, in the same task, before any frame. + const observer = new MutationObserver(() => { + observer.disconnect(); + // The product's part: the motions it just started carry no start + // of their own; the browser sets it when it commits them. + const motions = row.getAnimations(); + const pending = + motions.length > 0 && + motions.every(animation => animation.startTime == null); + const until = performance.now() + 150; + while (performance.now() < until) { + // Busy: the main thread is held. + } + // The first frame due after the block: a frame scheduled before + // it runs with that earlier time. + const read = () => { + if ((document.timeline.currentTime as number) < until) { + requestAnimationFrame(read); + return; + } + const value = getComputedStyle(row).translate; + const [, y = '0px'] = + value === 'none' || value === '' ? ['0px'] : value.split(' '); + resolve({ + first: Number.parseFloat(y), + pending, + // Where the browser put the start: after the block, or (a + // frame stamped when it was due, motion/animator.ts, known + // limits) inside it. + startedAfterBlock: motions.every( + animation => Number(animation.startTime) >= until - 1, + ), + }); + }; + requestAnimationFrame(read); + }); + const tree = row.closest('[role="tree"]'); + if (tree != null) { + observer.observe(tree, {childList: true, subtree: true}); + } + (toggleButton as HTMLElement).click(); + }), + await toggle.elementHandle(), + ); + const height = await parts(page).group.evaluate( + el => el.getBoundingClientRect().height, + ); + expect(result.pending).toBe(true); + if (result.startedAfterBlock) { + // At most one frame into the outline spring (about 93% of the way + // left); a start pinned before the block would show it more than half + // done. + expect(result.first).toBeLessThan(-0.85 * height); + } else { + // This browser stamped the frame that started the motions with a time + // inside the block, so no first frame can show the start the commit + // would set; what the component controls is asserted above. + testInfo.annotations.push({ + type: 'start stamped inside the block', + description: `first frame at ${result.first.toFixed(1)} px of ${(-height).toFixed(1)} px`, + }); + } + await expect.poll(async () => translateY(below)).toBe(0); +}); + +test('Android: a tap expands with the same motion (one touch model)', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'Android is Chromium'); + await openStory(page, storybook(), STORY); + const {child, below} = parts(page); + await expect(below).toBeVisible(); + await tapToggle(page); + await expect(child).toBeVisible(); + // The row below starts where it was and springs home, as on iOS. + expect(await below.evaluate(el => el.getAnimations().length)).toBeGreaterThan( + 0, + ); + await expect.poll(async () => translateY(below)).toBe(0); +}); + +test('a mouse: a click expands and collapses in one frame, as before', async ({ + browser, +}) => { + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 900, height: 700}, + }); + const page = await context.newPage(); + try { + await openStory(page, storybook(), STORY); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const {group, child, below, toggle} = parts(page); + await expect(below).toBeVisible(); + await toggle.click(); + await expect(child).toBeVisible(); + // No motion: the row below is already in place, nothing animating it. + expect(await translateY(below)).toBe(0); + expect(await below.evaluate(el => el.getAnimations().length)).toBe(0); + await toggle.click(); + // The children leave with the click's own commit. + await page.evaluate( + async () => + new Promise(resolve => requestAnimationFrame(() => resolve())), + ); + expect(await group.count()).toBe(0); + expect(await translateY(below)).toBe(0); + } finally { + await context.close(); + } +}); + +test('the expansion keeps its own outline spring, whatever a theme writes', async ({ + page, +}) => { + await open(page); + // The outline spring is an internal constant: a variable written the way a + // theme would write one (0.8 s, no bounce, on the root) changes nothing. + await page.evaluate(() => + document.documentElement.style.setProperty( + '--motion-list-update-outline-spring', + '0.8s 0', + ), + ); + const table = solveSpring(SPRING, {from: 0, to: 1}); + const {group, child, below} = parts(page); + await tapToggle(page); + await expect(child).toBeVisible(); + await holdAnimations(page); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + for (const t of [SETTLE_MS / 2, SETTLE_MS]) { + await seekAnimations(page, t); + const expected = -height * (1 - table.value(t / 1000)); + expect(await translateY(child)).toBeCloseTo(expected, 0); + expect(await translateY(below)).toBeCloseTo(expected, 0); + } + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => translateY(below)).toBe(0); +}); + +test('under reduced motion an expand and a collapse cross-fade: opacity only, within 200 ms', async ({ + page, +}) => { + // design:reduced-motion DR1 and DR2, under a finger: nothing travels or + // turns; the children fade in where they land and out where they are. + await page.emulateMedia({reducedMotion: 'reduce'}); + await open(page); + const {child} = parts(page); + await tapToggle(page); + await expect(child).toBeVisible(); + expectReducedMotionCrossFade(await holdAnimations(page)); + // The held fades play out: a row or chevron that travels dips (it fades + // out, lands while invisible, then fades back in once its fade out has + // ended). The collapse starts when the expand has settled, everything + // showing again. + await releaseAnimations(page); + await expect.poll(async () => translateY(child)).toBe(0); + await expect.poll(async () => hiddenParts(page)).toBe(0); + await tapToggle(page); + expectReducedMotionCrossFade(await holdAnimations(page)); + await releaseAnimations(page, {finish: true}); + await expect(child).toHaveCount(0); +}); + +test("right to left: the chevron's quarter turn mirrors, and the children slide the same way", async ({ + page, +}) => { + await openStory(page, storybook(), STORY, { + globals: 'direction:rtl', + }); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the expansion moves under a finger only'); + const {group, child, chevron} = parts(page); + await expect(parts(page).below).toBeVisible(); + expect(await chevron.evaluate(el => getComputedStyle(el).direction)).toBe( + 'rtl', + ); + await tapToggle(page); + await expect(child).toBeVisible(); + await holdAnimations(page); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + for (const t of [0, SETTLE_MS / 4, SETTLE_MS / 2]) { + await seekAnimations(page, t); + // LTR starts the additive turn at −90°; right to left at +90°. + expect(await rotation(chevron)).toBeCloseTo(90 * (1 - progress(t)), 0); + expect(await translateY(child)).toBeCloseTo(-height * (1 - progress(t)), 0); + } + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => rotation(chevron)).toBe(0); +}); + +test('expand: the children slide out from under the parent, the rows below move with them, the chevron turns, on the outline spring', async ({ + page, +}, testInfo) => { + await open(page); + const {group, child, below, chevron} = parts(page); + const belowBefore = (await below.boundingBox())?.y ?? 0; + await tapToggle(page); + await expect(child).toBeVisible(); + const held = await holdAnimations(page); + expect(held.length, JSON.stringify(held)).toBeGreaterThan(0); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + expect(await group.evaluate(el => getComputedStyle(el).overflow)).toBe( + 'clip', + ); + const samples: {t: number; child: number; below: number; chevron: number}[] = + []; + for (const t of timeline(SETTLE_MS)) { + await seekAnimations(page, t); + samples.push({ + t, + child: await translateY(child), + below: await translateY(below), + chevron: await rotation(chevron), + }); + } + await releaseAnimations(page, {finish: true}); + // The block and the rows below travel the group's height together; the + // chevron turns the quarter turn; one spring for all three. + const offset = (t: number) => -height * (1 - progress(t)); + const turn = (t: number) => -90 * (1 - progress(t)); + const childCurve = compareCurve( + samples.map(s => ({t: s.t, value: s.child})), + offset, + 0.5, + ); + const belowCurve = compareCurve( + samples.map(s => ({t: s.t, value: s.below})), + offset, + 0.5, + ); + const chevronCurve = compareCurve( + samples.map(s => ({t: s.t, value: s.chevron})), + turn, + 0.5, + ); + await writeEvidence( + 'curves/tree-list-expand', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + { + spring: list.update.outlineSpring, + height, + samples, + childCurve, + belowCurve, + chevronCurve, + }, + null, + 2, + ), + }, + testInfo, + ); + expect(samples[0].child).toBeCloseTo(-height, 0); + expect(childCurve.maxError, JSON.stringify(childCurve.worst)).toBeLessThan( + 0.5, + ); + expect(belowCurve.maxError, JSON.stringify(belowCurve.worst)).toBeLessThan( + 0.5, + ); + expect( + chevronCurve.maxError, + JSON.stringify(chevronCurve.worst), + ).toBeLessThan(0.5); + // At rest: the clip is gone, nothing is translated, the row below sits a + // group's height lower than before. + await expect + .poll(async () => group.evaluate(el => getComputedStyle(el).overflow)) + .not.toBe('clip'); + expect(await translateY(below)).toBe(0); + expect(((await below.boundingBox())?.y ?? 0) - belowBefore).toBeCloseTo( + height, + 0, + ); +}); + +test('collapse: the children slide back under the parent, then leave, with no jump', async ({ + page, +}) => { + await open(page); + const {group, child, below} = parts(page); + const belowCollapsed = (await below.boundingBox())?.y ?? 0; + await tapToggle(page); + await expect(child).toBeVisible(); + await expect.poll(async () => translateY(below)).toBe(0); + await expect + .poll(async () => group.evaluate(el => getComputedStyle(el).overflow)) + .not.toBe('clip'); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + + await tapToggle(page); + // Still rendered while it slides away, but out of reach. + await expect(group).toHaveAttribute('inert', ''); + await holdAnimations(page); + await seekAnimations(page, SETTLE_MS / 3); + const midway = await translateY(below); + expect(midway).toBeLessThan(-1); + expect(midway).toBeGreaterThan(-height + 1); + await releaseAnimations(page, {finish: true}); + // Gone, and the row below sits where it sat before the expand: the commit + // that removed the children took the translate back with it. + await expect(group).toHaveCount(0); + expect(await translateY(below)).toBe(0); + expect((await below.boundingBox())?.y ?? 0).toBeCloseTo(belowCollapsed, 0); +}); + +test('the end of a collapse shows no child outside the group, up to the frame the group leaves', async ({ + page, +}) => { + await open(page); + const {child} = parts(page); + await tapToggle(page); + await expect(child).toBeVisible(); + await expect + .poll(async () => + parts(page).group.evaluate(el => getComputedStyle(el).overflow), + ) + .not.toBe('clip'); + // Every frame from the collapse's tap until the group is gone: a child + // painted above the group's top edge with no clip shows over the parent + // row. + await page.evaluate(() => { + const w = window as unknown as {__frames: string[]; __stop: boolean}; + w.__frames = []; + w.__stop = false; + const parent = document.querySelector('[data-tree-id="components"]'); + const frame = () => { + const group = parent?.querySelector( + ':scope > [role="group"]', + ); + if (group != null && getComputedStyle(group).overflow !== 'clip') { + const top = group.getBoundingClientRect().top; + for (const item of group.children) { + const box = item.getBoundingClientRect(); + if (box.height > 0 && box.top < top - 0.5) { + w.__frames.push( + `${(item.textContent ?? '').slice(0, 12)} at ${box.top} above ${top}`, + ); + } + } + } + if (!w.__stop) { + requestAnimationFrame(frame); + } + }; + requestAnimationFrame(frame); + }); + await tapToggle(page); + await expect(parts(page).group).toHaveCount(0, {timeout: 3000}); + await page.waitForTimeout(50); + const outside = await page.evaluate(() => { + const w = window as unknown as {__frames: string[]; __stop: boolean}; + w.__stop = true; + return w.__frames; + }); + expect(outside).toEqual([]); +}); + +test('content after the tree takes its place by layout at once, with no translate, and a fixed element inside it stays fixed', async ({ + page, +}) => { + await openStory(page, storybook(), 'core-treelist--with-content-below'); + const touch = await page.evaluate( + () => matchMedia('(pointer: coarse)').matches, + ); + test.skip(!touch, 'the expansion moves under a finger only'); + const button = page.getByRole('button', {name: 'Open folder'}); + const {group, below} = parts(page); + await expect(button).toBeVisible(); + // More content after the tree, holding a position: fixed element, which + // stays where the viewport puts it as long as nothing transforms its + // ancestors. + await button.evaluate(el => { + const after = document.createElement('div'); + after.style.height = '20px'; + const fixed = document.createElement('div'); + fixed.setAttribute('data-test-fixed', ''); + fixed.style.cssText = + 'position: fixed; top: 10px; left: 10px; width: 8px; height: 8px;'; + after.append(fixed); + el.insertAdjacentElement('afterend', after); + }); + const fixedTop = async () => + page + .locator('[data-test-fixed]') + .evaluate(el => el.getBoundingClientRect().top); + const rest = (await button.boundingBox())?.y ?? 0; + + await tapToggle(page); + await holdAnimations(page); + await seekAnimations(page, 0); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + // Its new layout at once, one group height down, with nothing on it. + expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe( + 'none', + ); + expect(((await button.boundingBox())?.y ?? 0) - rest).toBeCloseTo(height, 0); + expect(await fixedTop()).toBeCloseTo(10, 0); + // The rows inside the tree still spring from where they were. + expect(await translateY(below)).toBeCloseTo(-height, 0); + await releaseAnimations(page, {finish: true}); + await expect.poll(async () => translateY(below)).toBe(0); + + // A collapse: it stays where it is while the rows slide back, then takes + // its place when the group leaves, never translated. + await tapToggle(page); + await holdAnimations(page); + await seekAnimations(page, SETTLE_MS / 3); + expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe( + 'none', + ); + expect(await fixedTop()).toBeCloseTo(10, 0); + await releaseAnimations(page, {finish: true}); + await expect(group).toHaveCount(0); + expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe( + 'none', + ); + expect((await button.boundingBox())?.y ?? 0).toBeCloseTo(rest, 0); +}); + +test('the rows below keep moving on every frame while the main thread is blocked', async ({ + page, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'chromium', + 'screencast frame evidence is Chromium-only in Playwright', + ); + await open(page); + const {below} = parts(page); + const unmark = await markElement(below); + const cast = await startScreencast(page); + await page.waitForTimeout(100); + await tapToggle(page); + await waitForAnimation(below, {minProgressMs: 16}); + const block = await blockMainThread(page, 300); + await page.waitForTimeout(200); + const frames = await cast.stop(); + await unmark(); + const tracked = await trackMarker(page, frames); + const proof = busyWindowProof(tracked, block, { + axis: 'y', + settledWithin: 1, + }); + await writeEvidence( + 'busy-main-thread/tree-list-expand', + {[`${testInfo.project.name}.json`]: JSON.stringify(proof, null, 1)}, + testInfo, + ); + // Frames kept coming through the block, each one further down. + expect(proof.changed, JSON.stringify(proof)).toBeGreaterThanOrEqual(3); + expect(proof.monotonic, JSON.stringify(proof)).toBe(true); + expect(proof.longestStallMs, JSON.stringify(proof)).toBeLessThan(40); +}); + +test('WebKit: the rows below keep moving while the main thread is blocked (video)', async ({ + browser, + browserName, +}, testInfo) => { + test.skip( + browserName !== 'webkit', + 'the Chromium screencast test covers Chromium', + ); + const size = {width: 402, height: 714}; + const context = await browser.newContext({ + viewport: size, + deviceScaleFactor: 1, + isMobile: true, + hasTouch: true, + recordVideo: {dir: testInfo.outputPath('video'), size}, + }); + const page = await context.newPage(); + await open(page); + const {group, below} = parts(page); + // The height the rows below travel: expand once, read it, collapse again. + await tapToggle(page); + await expect.poll(async () => translateY(below)).toBe(0); + const height = await group.evaluate(el => (el as HTMLElement).offsetHeight); + await tapToggle(page); + await expect(group).toHaveCount(0); + // The row below carries a marker chip; probes every 4 px along its path + // read where the chip is in each recorded frame. + await markElement(below); + const chip = await page.evaluate(() => { + const el = document.querySelector('[data-harness-marker-chip]'); + const box = el?.getBoundingClientRect(); + return box == null + ? null + : {x: box.x + box.width / 2, y: box.y + box.height / 2}; + }); + if (chip == null) { + throw new Error('no marker chip'); + } + const probes = Array.from({length: Math.floor(height / 4) + 1}, (_, k) => ({ + x: Math.round(chip.x), + y: Math.round(chip.y + k * 4), + })); + await installBeacon(page); + await page.waitForTimeout(300); + await tapToggle(page); + await waitForAnimation(below, {minProgressMs: 1}); + await blockBehindBeacon(page, 300); + await page.waitForTimeout(400); + const video = page.video(); + await context.close(); + const path = await video?.path(); + expect(path).toBeTruthy(); + const samples = await sampleVideoPoints(path as string, probes, size); + /** Where the chip is: the mean probe index it covers, in px down its path. */ + const position = (marker: ReadonlyArray) => { + const hits = marker.flatMap((hit, k) => (hit ? [k] : [])); + return hits.length === 0 + ? null + : (hits.reduce((a, b) => a + b, 0) / hits.length) * 4; + }; + const blocked = samples + .filter(s => s.beacon === 'blocked') + .map(s => ({t: s.t, y: position(s.marker)})) + .filter((s): s is {t: number; y: number} => s.y != null); + const distinct = blocked + .map(s => Math.round(s.y)) + .filter((v, i, all) => i === 0 || v !== all[i - 1]); + await writeEvidence( + 'busy-main-thread/tree-list-expand-webkit', + {'webkit.json': JSON.stringify({height, blocked, distinct}, null, 1)}, + testInfo, + ); + // The row kept moving down while script could not run. + expect(distinct.length, JSON.stringify(distinct)).toBeGreaterThanOrEqual(3); + for (let i = 1; i < distinct.length; i++) { + expect(distinct[i]).toBeGreaterThan(distinct[i - 1]); + } +}); + +test('the expand does no Layout or Paint per frame', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + await open(page); + const {parent, below} = parts(page); + // Expanded from the keyboard (an iPad's): the same motion, with no press + // feedback of the toggle's own in the trace. + await parent.focus(); + let window = {from: 0, to: 0}; + const trace = await traceRendering(page, async () => { + await page.keyboard.press('ArrowRight'); + const [started] = await waitForAnimation(below); + window = {from: started.from, to: started.from + SETTLE_MS}; + await page.waitForTimeout(SETTLE_MS + 100); + }); + const during = countBetween(trace, window.from + 30, window.to - 30); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); +}); + +test( + 'storyboard: a TreeList row expanding on iOS under a finger', + {tag: '@storyboard'}, + async ({page}, testInfo) => { + await open(page); + await tapToggle(page); + const {storyboard} = await animationStoryboard(page, { + name: 'tree-list-expand', + clip: {x: 0, y: 0, width: 402, height: 340}, + times: [0, 33, 67, 100, 150, 200, 267, Math.round(SETTLE_MS)], + columns: 8, + cellScale: 0.45, + }); + await releaseAnimations(page, {finish: true}); + await storyboard.write(testInfo); + }, +); diff --git a/packages/core/src/TreeList/useTreeExpansionMotion.test.tsx b/packages/core/src/TreeList/useTreeExpansionMotion.test.tsx new file mode 100644 index 0000000000000..a4e5a6ac0adc1 --- /dev/null +++ b/packages/core/src/TreeList/useTreeExpansionMotion.test.tsx @@ -0,0 +1,253 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useTreeExpansionMotion.test.tsx + * @input vitest, TreeList, a stubbed pointer (a finger, iOS and Android + * alike, or a mouse) + * @output Unit tests for the expansion's presence rules: with a mouse a + * collapse removes the children at once; under any finger (iOS and Android + * alike) they stay, inert and out of the arrow keys' reach, until they have + * slid away, and an expand that interrupts the collapse keeps them; page + * content after the tree is never moved (it takes its place by layout), the + * rows inside the tree release their translate at their own arrival and are + * left at rest when the tree unmounts mid-collapse + * @position Beside TreeList/useTreeExpansionMotion.ts; the motion itself is + * proven in a real engine by + * TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts + */ + +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {TreeList} from './TreeList'; +import type {TreeListItemData} from './TreeListTypes'; +import {motionOf} from '../utils/rowMotion'; + +/** Each group's height in the stubbed layout. */ +const GROUP_HEIGHT = 40; + +/** + * jsdom lays nothing out: an element sits one group's height lower for each + * laid-out group before it in the document (`pinned` elements never move, + * like a footer held at the bottom of its column). + */ +function stubLayout() { + vi.spyOn(HTMLElement.prototype, 'offsetTop', 'get').mockImplementation( + function (this: HTMLElement) { + if (this.hasAttribute('data-pinned')) { + return 500; + } + let top = 0; + for (const laid of document.querySelectorAll( + '[role="group"]', + )) { + if ( + laid.style.display !== 'none' && + !laid.contains(this) && + (laid.compareDocumentPosition(this) & + Node.DOCUMENT_POSITION_FOLLOWING) !== + 0 + ) { + top += GROUP_HEIGHT; + } + } + return top; + }, + ); + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation( + function (this: HTMLElement) { + return this.getAttribute('role') === 'group' ? GROUP_HEIGHT : 0; + }, + ); +} + +const items: TreeListItemData[] = [ + { + id: 'components', + label: 'components', + isExpanded: true, + children: [ + {id: 'button', label: 'Button.tsx'}, + {id: 'card', label: 'Card.tsx'}, + ], + }, + {id: 'app', label: 'App.tsx'}, +]; + +/** + * The page under a finger (a coarse primary pointer: one touch model, iOS + * and Android alike) or a mouse. + */ +function stubPointer(pointer: 'touch' | 'mouse') { + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: pointer === 'touch' && query.includes('pointer: coarse'), + media: query, + onchange: null, + addEventListener: () => undefined, + removeEventListener: () => undefined, + addListener: () => undefined, + removeListener: () => undefined, + dispatchEvent: () => false, + })), + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const row = (id: string) => + document.querySelector(`[data-tree-id="${id}"]`); +const group = () => + row('components')?.querySelector(':scope > [role="group"]') ?? + null; +const toggle = () => + row('components')?.querySelector( + ':scope > :not([role="group"]) [data-tree-toggle]', + ) ?? null; + +describe('TreeList expansion presence', () => { + it('with a mouse, a collapse removes the children at once', () => { + stubPointer('mouse'); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + render(); + expect(group()).not.toBeNull(); + fireEvent.click(toggle() as HTMLElement); + expect(group()).toBeNull(); + }); + + it('under a finger, the children stay, inert and skipped by the arrow keys, until they have slid away', async () => { + stubPointer('touch'); + render(); + // Let the touch presentation settle after mount. + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + expect(row('components')).toHaveAttribute('aria-expanded', 'false'); + // Still rendered while it slides away, but inert. + expect(group()).not.toBeNull(); + expect(group()).toHaveAttribute('inert'); + // The arrow keys roam as if the children were already gone. + const components = row('components') as HTMLElement; + components.focus(); + fireEvent.keyDown(components, {key: 'ArrowDown'}); + expect(document.activeElement).toBe(row('app')); + // Gone once the motion settles. + await waitFor(() => expect(group()).toBeNull(), {timeout: 2000}); + }); + + it('under a finger, an expand that interrupts the collapse keeps the children', async () => { + stubPointer('touch'); + render(); + await act(async () => undefined); + const before = group(); + fireEvent.click(toggle() as HTMLElement); + fireEvent.click(toggle() as HTMLElement); + expect(row('components')).toHaveAttribute('aria-expanded', 'true'); + // The same group, never removed, and in reach again. + expect(group()).toBe(before); + expect(group()).not.toHaveAttribute('inert'); + await new Promise(resolve => setTimeout(resolve, 800)); + expect(group()).toBe(before); + expect(screen.getByText('Card.tsx')).toBeInTheDocument(); + }); +}); + +describe('content after the tree', () => { + const collapsed: TreeListItemData[] = [ + { + id: 'components', + label: 'components', + children: [{id: 'button', label: 'Button.tsx'}], + }, + {id: 'app', label: 'App.tsx'}, + ]; + + function Page() { + return ( +
      + +

      Below the tree

      +
      + ); + } + + it('is never moved by an expansion: it takes its place by layout', async () => { + stubPointer('touch'); + stubLayout(); + render(); + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + const below = screen.getByTestId('below'); + expect(motionOf(below)).toBeUndefined(); + expect(below.style.translate).toBe(''); + // The rows inside the tree still move. + expect(motionOf(row('app') as HTMLElement)).toBeDefined(); + }); + + it('is never moved by a collapse either', async () => { + stubPointer('touch'); + stubLayout(); + render(); + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + await waitFor( + () => expect(motionOf(row('app') as HTMLElement)).toBeUndefined(), + {timeout: 3000}, + ); + fireEvent.click(toggle() as HTMLElement); + const below = screen.getByTestId('below'); + expect(motionOf(row('app') as HTMLElement)).toBeDefined(); + expect(motionOf(below)).toBeUndefined(); + expect(below.style.translate).toBe(''); + }); + + it("releases each moved row's translate when its own spring arrives", async () => { + stubPointer('touch'); + stubLayout(); + render(); + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + const app = row('app') as HTMLElement; + // Moved: its spring starts when the browser commits it. + expect(motionOf(app)).toBeDefined(); + await waitFor(() => expect(app.style.translate).toBe(''), { + timeout: 3000, + }); + }); + + it('leaves nothing moved when the tree unmounts mid-collapse', async () => { + stubPointer('touch'); + stubLayout(); + const {rerender} = render(); + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + await waitFor( + () => expect(motionOf(row('app') as HTMLElement)).toBeUndefined(), + {timeout: 3000}, + ); + // Collapse, and take the tree away while it runs. + fireEvent.click(toggle() as HTMLElement); + const app = row('app') as HTMLElement; + expect(motionOf(app)).toBeDefined(); + rerender( +
      +

      Below the tree

      +
      , + ); + expect(app.style.translate).toBe(''); + expect(motionOf(app)).toBeUndefined(); + }); + + it('stays still with a mouse, where nothing moves', async () => { + stubPointer('mouse'); + expect(matchMedia('(pointer: coarse)').matches).toBe(false); + stubLayout(); + render(); + await act(async () => undefined); + fireEvent.click(toggle() as HTMLElement); + expect(motionOf(screen.getByTestId('below'))).toBeUndefined(); + expect(motionOf(row('app') as HTMLElement)).toBeUndefined(); + }); +}); diff --git a/packages/core/src/TreeList/useTreeExpansionMotion.ts b/packages/core/src/TreeList/useTreeExpansionMotion.ts new file mode 100644 index 0000000000000..1fbee5d0ece85 --- /dev/null +++ b/packages/core/src/TreeList/useTreeExpansionMotion.ts @@ -0,0 +1,281 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useTreeExpansionMotion.ts + * @input A tree row's expanded state, the touch presentation + * (utils/touchPresentation.ts), the motion foundation's animator and the + * outline spring from the UIKit constants table (motion/uikit/list.ts) + * @output `useTreeExpansionMotion`: whether a row renders its children, the + * ref its group attaches, and the expand and collapse played the way a UIKit + * outline list plays them, under any finger (useTouchPresentation: a + * coarse primary pointer, iOS and Android alike); with a mouse the + * children come and go in one frame, as before + * @position TreeList internals; TreeListItem calls it for every row with + * children + * + * UIKit's reference (iOS 26.2, a UICollectionView list with outline + * disclosure): on expand, the children slide down out from under the parent + * as one block, inside a clip that grows with them; the rows below move down + * with them; the disclosure chevron turns 90°; all on one critically damped + * spring (`list.update.outlineSpring`, an internal constant), with no fade. + * Collapse runs the same motion back: the children slide up under the parent + * and leave when it ends. + * + * HOW IT RUNS, compositor only. The group keeps its final layout; it clips its + * own box for the length of the motion, so its top edge (the parent row's + * bottom) is the clip's edge, and its children translate as one block from + * the group's height above it. Every row after the group in the tree + * translates by how far the group's layout moves it (read once with the + * group laid out and once without, utils/rowMotion.ts `layoutShifts`), the + * group's height for rows in the tree's flow, so the rows below always meet + * the block's bottom edge: the clip never has to move. Each element releases + * its inline `translate` when its own spring arrives. The chevron turns by an additive + * `rotate` over its final CSS transform. All of it is `translate` and + * `rotate` played by the animator on the compositor, retargeted from the + * value on screen when the row is toggled again mid-motion. A collapse keeps + * the children rendered until the block has slid away; the commit that + * removes them shifts the rows below back by the same amounts, so nothing + * jumps. Page content after the tree is not the tree's to move: the tree's + * height changes by layout at the commit that inserts or removes a group + * (`spec:AST-094` FR5 forbids animating layout), so content after it takes + * its new place at once, with no transient translate on it; only the tree's + * own rows animate, inside its box. An unmount mid-motion leaves nothing + * moved. + * + * Under reduced motion nothing travels (`design:reduced-motion`): every part + * takes the animator's own Reduced Motion handling, so the children fade in + * where they land and fade out where they are, and the rows below and + * the chevron cross-fade into place. + * + * One touch model: an Android finger gets the same motion as an iOS one. + * With a mouse (the theme's presentation) nothing moves: the children appear + * and leave at once, as before. Leaving children are inert while they slide + * away: focus, arrow keys and assistive technology skip them. + * + * SYNC: When modified, update: + * - /packages/core/src/TreeList/TreeListItem.tsx + * - /packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts + */ + +import {useCallback, useRef, useState} from 'react'; +import {isRtlElement} from '../hooks/isRtlElement'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import {list} from '../motion/uikit/list'; +import { + layoutShifts, + motionNow, + releaseMotion, + springHome, + springTo, + stopRow, +} from '../utils/rowMotion'; +import {useTouchPresentation} from '../utils/touchPresentation'; + +const SPRING = list.update.outlineSpring; +/** The chevron turns a quarter turn between collapsed and expanded. */ +const QUARTER_TURN = 90; + +/** Every row after `group` in its tree, at each level up to the tree. */ +function rowsAfter(group: HTMLElement): HTMLElement[] { + const rows: HTMLElement[] = []; + const tree = group.closest('[role="tree"]'); + let item = group.parentElement?.closest('li') ?? null; + while (item != null && tree?.contains(item) === true) { + for ( + let next = item.nextElementSibling; + next != null; + next = next.nextElementSibling + ) { + if (next instanceof HTMLElement) { + rows.push(next); + } + } + item = item.parentElement?.closest('li') ?? null; + } + return rows; +} + +export interface TreeExpansionMotion { + /** Render the children: expanded, or still sliding away. */ + readonly showsChildren: boolean; + /** For the children's group (`ul[role="group"]`). */ + readonly groupRef: (element: HTMLUListElement | null) => void; +} + +/** The row's own chevron glyph (`data-tree-chevron`), beside its group. */ +function chevronOf(group: HTMLElement): HTMLElement | null { + return ( + group.parentElement?.querySelector( + ':scope > :not([role="group"]) [data-tree-chevron]', + ) ?? null + ); +} + +export function useTreeExpansionMotion( + isExpanded: boolean, +): TreeExpansionMotion { + const animates = useTouchPresentation().isTouch; + const [shown, setShown] = useState(isExpanded); + if (isExpanded && !shown) { + setShown(true); + } + if (!isExpanded && shown && !animates) { + setShown(false); + } + + const groupElementRef = useRef(null); + const previousRef = useRef({isExpanded, shown}); + /** The motion in flight; a newer one makes an older one's ending moot. */ + const generationRef = useRef(0); + /** A motion is running: a toggle now retargets it instead of restarting. */ + const inFlightRef = useRef(false); + /** + * What the motion moves outside the group (the rows after it in the + * tree), each with how far the group's layout moves it. + */ + const movedRef = useRef>(new Map()); + + // External system (`architecture:react-component-runtime` INV3): the shared + // motion animators (utils/rowMotion.ts) of the group's rows and of the rows + // after it in the tree. A toggle starts them, a toggle mid-motion retargets + // them, and the commit that removes the children stops them at rest; the + // unmount cleanup below releases any still moving. + useIsomorphicLayoutEffect(() => { + const before = previousRef.current; + previousRef.current = {isExpanded, shown}; + + // The commit that removed the children moved each element below up by + // its shift, where the collapse had already put it: it is at rest. + if (before.shown && !shown) { + for (const moved of movedRef.current.keys()) { + stopRow(moved, 'translate'); + } + movedRef.current = new Map(); + inFlightRef.current = false; + return; + } + if (before.isExpanded === isExpanded || !animates) { + return; + } + const element = groupElementRef.current; + if (element == null) { + return; + } + const at = motionNow(); + const mine = ++generationRef.current; + const height = element.offsetHeight; + const children = Array.from(element.children).filter( + (child): child is HTMLElement => child instanceof HTMLElement, + ); + const justMounted = !before.shown; + // The rows after the group in the tree, each by how far the group's + // layout moves it. Content after the tree is not the tree's to move: it + // takes its new place by layout. Kept as they are while a motion runs, + // so a toggle mid-motion retargets the same rows. + const moved = + justMounted || !inFlightRef.current + ? layoutShifts(element, rowsAfter(element)) + : movedRef.current; + movedRef.current = moved; + inFlightRef.current = true; + // The clip: the group's own box, whose top edge is the parent row's + // bottom, for the length of the motion. + element.style.overflow = 'clip'; + + const glyph = chevronOf(element); + if (glyph != null) { + // The class switch just turned the glyph's CSS transform a quarter + // turn; start the additive turn from where it was and spring it home. + const sign = isRtlElement(glyph) ? -1 : 1; + void springHome( + glyph, + 'rotate', + (isExpanded ? -QUARTER_TURN : QUARTER_TURN) * sign, + SPRING, + at, + ).then(arrived => { + if (arrived && generationRef.current === mine) { + releaseMotion(glyph, 'rotate'); + } + }); + } + + // Each element is released from its own motion's arrival: by then this + // module no longer tracks it, so its inline `translate` clears. + const releaseOnArrival = (target: HTMLElement) => (arrived: boolean) => { + if (arrived && generationRef.current === mine) { + releaseMotion(target, 'translate'); + } + }; + if (isExpanded) { + // Out from under the parent: the block starts its own height up, each + // element below starts where it was before the children took space. + // Under reduced motion the children fade in where they land. + const block = children.map(async child => { + const arrived = await (justMounted + ? springHome(child, 'y', -height, SPRING, at, 'entrance') + : springTo(child, 0, SPRING, at, 'entrance')); + releaseOnArrival(child)(arrived); + return arrived; + }); + for (const [target, shift] of moved) { + void ( + justMounted + ? springHome(target, 'y', -shift, SPRING, at) + : springTo(target, 0, SPRING, at) + ).then(releaseOnArrival(target)); + } + void Promise.all(block).then(results => { + if (generationRef.current !== mine || results.some(done => !done)) { + return; + } + element.style.removeProperty('overflow'); + inFlightRef.current = false; + }); + return; + } + + // Back under the parent; each element below goes where the group's + // removal will put it, following the block's bottom edge. + // Under reduced motion the children fade out where they are. + const block = children.map(async child => + springTo(child, -height, SPRING, at, 'exit'), + ); + for (const [target, shift] of moved) { + void springTo(target, -shift, SPRING, at); + } + void Promise.all(block).then(results => { + if (generationRef.current !== mine || results.some(done => !done)) { + return; + } + // The children sit a group's height up, hidden by the clip, until the + // commit that removes them takes the group away with them: dropping + // the clip first would show them over the parent row for a frame. + setShown(false); + }); + }, [isExpanded, shown, animates]); + + // External system (`architecture:react-component-runtime` INV3): the shared + // motion animators of elements outside this row's render, the rows after + // its group, which the effect above moves and releases. An unmount + // mid-motion must leave none of them moved: stop them at rest, clear their + // translate and the group's clip, and make any pending arrival moot. + useIsomorphicLayoutEffect( + () => () => { + generationRef.current += 1; + for (const moved of movedRef.current.keys()) { + stopRow(moved, 'translate'); + } + movedRef.current = new Map(); + groupElementRef.current?.style.removeProperty('overflow'); + }, + [], + ); + + const groupRef = useCallback((element: HTMLUListElement | null) => { + groupElementRef.current = element; + }, []); + return {showsChildren: shown, groupRef}; +} 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..9ed3a6447b414 100644 --- a/packages/core/src/__tests__/pressState.ts +++ b/packages/core/src/__tests__/pressState.ts @@ -179,7 +179,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(