An open source design system that's fully customizable and agent ready
TypeScript
test(interaction): curve sampling (#8044)
Christopher Chedeau4444d70bd729
diff --git a/.github/scripts/ci-interaction.test.mjs b/.github/scripts/ci-interaction.test.mjsindex 959a20ce6d..016f024177 100644--- a/.github/scripts/ci-interaction.test.mjs+++ b/.github/scripts/ci-interaction.test.mjs@@ -233,7 +233,7 @@ describe('interaction proof routing', () => {}});- it('keeps the harness, components, Storybook and its own setup in scope', () => {+ it('keeps the harness, components, themes, Storybook and its own setup in scope', () => {const pattern = new RegExp(decide().run.match(/bash "\$helper" "\$BASE_SHA" '([^']+)'/)[1],);@@ -242,6 +242,8 @@ describe('interaction proof routing', () => {'internal/a11y-spec/src/storybook.ts','playwright.interaction.config.ts','packages/core/src/BottomSheet/BottomSheet.tsx',+ // Themes set the motion durations components animate with.+ 'packages/themes/neutral/src/neutralTheme.ts','apps/storybook/.storybook/preview.tsx','.github/workflows/ci.yml','package.json',@@ -253,6 +255,7 @@ describe('interaction proof routing', () => {'docs/specs/AST-030/spec.md','apps/docsite/src/app/page.tsx','packages/core/package.json',+ 'packages/themes/neutral/package.json','.github/scripts/native-swift.sh',]) {expect(pattern.test(untouched), untouched).toBe(false);diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ad2191efe0..b8afa7ea57 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1767,7 +1767,7 @@ jobs:&& git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \&& git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; thenscope=0- bash "$helper" "$BASE_SHA" '^(internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$)' || scope=$?+ bash "$helper" "$BASE_SHA" '^(internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/[^/]+/src/|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$)' || scope=$?fiif [ "$scope" = 1 ]; thenecho 'No harness, component, Storybook or proof-setup change; skipping the interaction proofs.'diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex 08a393f9e1..cd53a4b9ca 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -1,8 +1,8 @@# @astryxdesign/interaction-harness-Playwright instruments for touch interaction proofs: real touch input.-**Internal and unpublished.** Specs live next to their component as-`*.interaction.browser.spec.ts` and run under+Playwright instruments for touch interaction and animation proofs: real touch+input and curve sampling. **Internal and unpublished.** Specs live+next to their component as `*.interaction.browser.spec.ts` and run under[`playwright.interaction.config.ts`](../../playwright.interaction.config.ts) ona phone-sized touch screen (402 × 714 CSS px page, 402 × 874 screen, 3 devicepixels per CSS px, touch, mobile viewport rules), in Chromium and WebKit.@@ -26,21 +26,42 @@ pnpm test:interaction <spec file> # one spec, both engines| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `scripts.ts` | Touch scripts as data: `tap`, `drag` (hold, rest), `flick` (exact final-move speed, velocity profiles), `holdThenDrag`, `pinch`, `rotate`, `path`, `merge` (a second finger mid-gesture), `releaseVelocity`, `toTouchEvents`. || `touch.ts` | `touchDriver(page).play(script)`: the script as real engine input. `installInputLog` / `readInputLog`: what the page received. |-| `story.ts` | `phone`, `withStorybook`, `openStory`, `frames`. |+| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `releaseAnimations`. || `math.ts` | Oracles independent of the code under test: `cubicBezier`, `timingFunction`, `springStep` (SwiftUI response / dampingFraction, initial velocity), `projectDecay`, `rubberBand`, `parseTransform`, `compareCurve`, `timeline`. |+| `story.ts` | `phone`, `withStorybook`, `openStory`, `frames`. |-## Real touch+## The proofs-Untrusted DOM events are not input: they start no native scroll, claim no-gesture, and read `isTrusted: false`. Chromium input goes through CDP-`Input.dispatchTouchEvent` with an explicit timestamp per event: the page's-`event.timeStamp` is the scripted time to 0.1 ms, whatever the+**Real touch.** Untrusted DOM events are not input: they start no native+scroll, claim no gesture, and read `isTrusted: false`. Chromium input goes+through CDP `Input.dispatchTouchEvent` with an explicit timestamp per event: the+page's `event.timeStamp` is the scripted time to 0.1 ms, whatever thedispatch latency, and the events go through the compositor's gesture detection(native scrolling, flings with velocity from those timestamps, `touch-action`,`pointercancel`). WebKit input goes through the engine's own input command; seethe limits below. Read positions a frame after a move: Chromium delivers`pointermove` aligned to animation frames.+**Curve sampling.** Pause every running animation (CSS transitions and+animations are Web Animations too), seek to a time, read `getComputedStyle`:+the presented value at that exact time, independent of frame timing. Finished+animations, ones the page paused and ones on a scroll or view timeline are left+alone; held animations keep their offsets from the first hold's earliest start, and release+resumes only them. Compare it with an+oracle from `math.ts` through `compareCurve`; a tolerance states the error+budget (for a spring baked into `linear()` stops of `h` ms, chords err by up to+`h² / 8 · |x''|`). A seek past an animation's end lands half a millisecond+inside it, the last frame it presents, and the sample says so (`presentedAt`,+where oracles are read). An animation whose keyframes end in a run of+identical values (an end value held so a later interruption can read it)+ends where that run starts: `curveEndMs` stops there. That holds for an+animation that plays forward under a linear or cubic-bézier effect easing (the+time the run starts is solved from the curve); under any other effect easing+(steps, `linear()` stops, an overshoot) or another direction the curve is read+to its full end. `holdAnimations` refuses an animation running backward+(`reverse()`, a negative playback rate): seeking and sampling run a curve+forward.+## Engine limits (measured with Playwright 1.61)| | Chromium 149 | WebKit 26.5 (Linux build) |@@ -51,7 +72,7 @@ the limits below. Read positions a frame after a move: Chromium delivers| Native scroll, fling, pinch-zoom from injected touches | yes | no || Lifting one finger while others stay down | yes | pointer events right, but that `touchend` lists no remaining `touches`: skip with `PARTIAL_LIFT_SKIP` || Click synthesised from a touch | yes | only from `driver.tap` (WebKit's tap gesture), not from a raw touch sequence |-| Input log | yes | yes |+| Curve sampling, input log | yes | yes |What WebKit cannot show here — native scroll hand-off, flings, a fingerlifting while another stays down, and anything iOS-only — needs Mobile Safaridiff --git a/internal/interaction-harness/package.json b/internal/interaction-harness/package.jsonindex 81fc8e0ead..de2f8e87aa 100644--- a/internal/interaction-harness/package.json+++ b/internal/interaction-harness/package.json@@ -3,7 +3,7 @@"version": "0.0.0","private": true,"type": "module",- "description": "Internal: Playwright helpers for touch interaction proofs (real touch input). Never published.",+ "description": "Internal: Playwright helpers for touch interaction and animation proofs (real touch input, curve sampling). Never published.","main": "./src/index.ts","exports": {".": "./src/index.ts",diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.tsnew file mode 100644index 0000000000..394e285915--- /dev/null+++ b/internal/interaction-harness/src/curves.ts@@ -0,0 +1,645 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file curves.ts+ * @input Uses a Playwright `Page`, a `Locator` for the animated element, and+ * the Web Animations API in the page (CSS transitions and CSS animations are+ * Web Animations too)+ * @output `holdAnimations` (pause every running animation and describe it),+ * `seekAnimations` (move them to t ms from the held origin, each keeping+ * its offset), `sampleCurve` (the presented+ * transform/opacity at each t, with the individual `translate`, `rotate` and+ * `scale` properties composed in), `releaseAnimations`, `curveOf`, which+ * picks one channel out of the samples for ./math's `compareCurve`.+ * @position Curve sampling: the exact presented value of an animation at a+ * fixed time, independent of frame timing, so a curve can be compared with+ * the UIKit reference to a fraction of a pixel. A paused animation's effect+ * is applied at its current time and `getComputedStyle` reads it.+ */++import type {Locator, Page} from '@playwright/test';+import {parseTransform, type TimedValue, type Transform2D} from './math';++/** How far inside its end a seek past an animation's end lands, ms. */+export const END_INSET_MS = 0.5;++/**+ * Installs `window.__harnessCurveEnd(animation)`: the local time (ms, delay+ * included) where the animation's effect stops changing. An animation whose+ * keyframes end in a run of identical values (an end value held so that a+ * later interruption can read it) ends where that run starts, when it plays+ * forward under a linear or cubic-bézier effect easing (the time the run+ * starts is solved from the curve); any other ends at its end time.+ */+async function installCurveEnd(page: Page): Promise<void> {+ await page.evaluate(() => {+ const w = window as unknown as {+ __harnessCurveEnd?: (animation: Animation) => number;+ };+ if (w.__harnessCurveEnd) {+ return;+ }+ const timingKeys = new Set([+ 'offset',+ 'computedOffset',+ 'easing',+ 'composite',+ ]);+ const values = (k: ComputedKeyframe) =>+ JSON.stringify(+ Object.keys(k)+ .filter(p => !timingKeys.has(p))+ .sort()+ .map(p => [p, String(k[p])]),+ );+ w.__harnessCurveEnd = animation => {+ const effect = animation.effect as KeyframeEffect | null;+ const timing = effect?.getComputedTiming();+ const delay = Number(timing?.delay ?? 0);+ const active = Number(timing?.activeDuration ?? 0);+ if (+ effect == null ||+ !Number.isFinite(active) ||+ Number(timing?.iterations ?? 1) !== 1+ ) {+ return delay + active;+ }+ // A held end is read only for an animation that plays forward: run+ // backward (a reverse or alternating direction, or `reverse()`'s+ // negative playback rate), the held run is where its motion starts.+ if (+ (timing?.direction ?? 'normal') !== 'normal' ||+ animation.playbackRate < 0+ ) {+ return delay + active;+ }+ const frames = effect.getKeyframes();+ // A run holds only when it reaches offset 1 and every frame in it keys+ // every property the animation keys: a property left out, or a last+ // frame before offset 1, gets an implicit end frame and keeps moving.+ const keyed = new Set(+ frames.flatMap(k => Object.keys(k).filter(p => !timingKeys.has(p))),+ );+ const keysAll = (k: ComputedKeyframe) =>+ [...keyed].every(p => k[p] !== undefined);+ const last = frames[frames.length - 1];+ if (last == null || Number(last.computedOffset) !== 1 || !keysAll(last)) {+ return delay + active;+ }+ let first = frames.length - 1;+ while (+ first > 0 &&+ keysAll(frames[first - 1]) &&+ values(frames[first - 1]) === values(frames[first])+ ) {+ first -= 1;+ }+ const offset = Number(frames[first]?.computedOffset ?? 1);+ if (offset >= 1) {+ return delay + active;+ }+ // Keyframe offsets are progress, not time. Under a cubic-bézier effect+ // easing (the CSS keywords included) whose progress only rises, the+ // time the held run starts is solved from the curve; under any other+ // easing (steps, linear() stops, an overshoot) the curve is read to the+ // full end.+ const easing = String(effect.getTiming().easing ?? 'linear').trim();+ const named: Record<string, number[]> = {+ linear: [0, 0, 1, 1],+ ease: [0.25, 0.1, 0.25, 1],+ 'ease-in': [0.42, 0, 1, 1],+ 'ease-out': [0, 0, 0.58, 1],+ 'ease-in-out': [0.42, 0, 0.58, 1],+ };+ const match = /^cubic-bezier\(([^)]+)\)$/.exec(easing);+ const points =+ named[easing] ?? (match ? match[1].split(',').map(Number) : null);+ if (+ points == null ||+ points.length !== 4 ||+ !points.every(Number.isFinite) ||+ points[1] < 0 ||+ points[1] > 1 ||+ points[3] < 0 ||+ points[3] > 1+ ) {+ return delay + active;+ }+ const [x1, y1, x2, y2] = points;+ const bezier = (u: number, p1: number, p2: number) =>+ 3 * (1 - u) * (1 - u) * u * p1 + 3 * (1 - u) * u * u * p2 + u * u * u;+ let lo = 0;+ let hi = 1;+ for (let i = 0; i < 60; i += 1) {+ const mid = (lo + hi) / 2;+ if (bezier(mid, y1, y2) < offset) {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ return delay + bezier((lo + hi) / 2, x1, x2) * active;+ };+ });+}++export interface HeldAnimation {+ readonly index: number;+ /** `CSSTransition`, `CSSAnimation` or `Animation` (script-created). */+ readonly kind: string;+ /** Transitioned property or animation name, when CSS made it. */+ readonly name: string | null;+ readonly target: string | null;+ readonly durationMs: number;+ readonly delayMs: number;+ /**+ * Where its curve ends, ms from its start (delay included): before a held+ * end value, if its keyframes end in one and it plays forward under a+ * linear or cubic-bézier effect easing; otherwise its end time.+ */+ readonly curveEndMs: number;+ readonly easing: string;+ readonly keyframes: readonly Record<string, unknown>[];+ /** Where it was when held, ms. */+ readonly heldAtMs: number | null;+ /**+ * How much later than the held origin (the earliest start among the+ * animations the first hold took) it started, ms; negative for an earlier+ * start held by a later hold. A seek to t moves it to its own t - offsetMs,+ * so staggered starts stay staggered.+ */+ readonly offsetMs: number;+}++/**+ * Pauses every running animation in the document (optionally only those whose+ * target is inside `scope`) and returns what was held. Finished animations,+ * animations the page paused, and animations on a scroll or view timeline are+ * left as they are. Later `seekAnimations` calls move exactly the held set,+ * each by its offset from the held origin, and `releaseAnimations` resumes+ * only it. A second call adds to the held set: what the first held stays held+ * until the release, and offsets keep counting from the origin the first call+ * set (the earliest start it took), so offsets already returned stay true.+ * An animation the page cancels after the hold (retargeting a CSS transition+ * cancels it) leaves the held set: seeking, sampling and releasing skip it+ * rather than revive it.+ */+export async function holdAnimations(+ page: Page,+ scope?: Locator,+): Promise<HeldAnimation[]> {+ const scopeHandle = scope ? await scope.elementHandle() : null;+ await installCurveEnd(page);+ return page.evaluate(root => {+ const curveEnd = (+ window as unknown as {__harnessCurveEnd: (a: Animation) => number}+ ).__harnessCurveEnd;+ const describe = (node: Element | null) =>+ node == null+ ? null+ : node.tagName.toLowerCase() ++ (node.id ? `#${node.id}` : '') ++ (node.classList.length+ ? `.${[...node.classList].slice(0, 2).join('.')}`+ : '');+ const now = Number(document.timeline.currentTime ?? performance.now());+ const all = document.getAnimations().filter(animation => {+ const target =+ (animation.effect as KeyframeEffect | null)?.target ?? null;+ return (+ animation.playState === 'running' &&+ animation.timeline instanceof DocumentTimeline &&+ (root == null ||+ (target != null && (root === target || root.contains(target))))+ );+ });+ // Seeking and sampling run a curve forward: an animation running+ // backward (`reverse()`, a negative playback rate) cannot be held and+ // read, so it is refused rather than misread.+ const backward = all.find(animation => animation.playbackRate < 0);+ if (backward != null) {+ throw new Error(+ `holdAnimations: ${describe((backward.effect as KeyframeEffect | null)?.target ?? null) ?? 'an animation'} runs backward (reverse() or a negative playback rate); hold and sample a forward run instead`,+ );+ }+ // Each animation's start on the document timeline, read before the pause+ // clears it (a pending play has no start time yet: it starts now).+ const starts = all.map(animation =>+ animation.startTime != null+ ? Number(animation.startTime)+ : now - Number(animation.currentTime ?? 0),+ );+ const held = all.map(animation => {+ animation.pause();+ // `pause()` only schedules the pause: the engine takes the hold time at+ // its next frame, a frame past where this read it. Setting the current+ // time completes a pending pause at once, here.+ // eslint-disable-next-line no-self-assign+ animation.currentTime = animation.currentTime;+ return animation;+ });+ // A later hold adds to the held set: what an earlier one held stays held+ // (it is paused, so it is not taken again above) until released.+ const w = window as unknown as {+ __harnessHeld?: Animation[];+ __harnessHeldStarts?: number[];+ __harnessHeldOrigin?: number;+ };+ w.__harnessHeld = [...(w.__harnessHeld ?? []), ...held];+ w.__harnessHeldStarts = [...(w.__harnessHeldStarts ?? []), ...starts];+ // Times count from the origin the first hold set (its earliest start)+ // until the release: a later hold, even of an animation that started+ // earlier (its offset is then negative), and dropping one never move it,+ // so every offsetMs already returned stays true.+ const origin = Number.isFinite(w.__harnessHeldOrigin ?? Number.NaN)+ ? (w.__harnessHeldOrigin as number)+ : Math.min(...starts);+ w.__harnessHeldOrigin = origin;+ const offsets = starts.map(start => start - origin);+ return held.map((animation, index) => {+ const effect = animation.effect as KeyframeEffect | null;+ const timing = effect?.getComputedTiming();+ const cssName =+ 'transitionProperty' in animation+ ? (animation as unknown as {transitionProperty: string})+ .transitionProperty+ : 'animationName' in animation+ ? (animation as unknown as {animationName: string}).animationName+ : null;+ return {+ index,+ kind: animation.constructor.name,+ name: cssName,+ target: describe((effect?.target as Element | null) ?? null),+ durationMs: Number(timing?.duration ?? 0),+ delayMs: Number(timing?.delay ?? 0),+ curveEndMs: curveEnd(animation),+ easing: String(effect?.getTiming().easing ?? 'linear'),+ keyframes: (effect?.getKeyframes() ?? []).map(+ (k): Record<string, unknown> => ({...k}),+ ),+ heldAtMs:+ animation.currentTime == null ? null : Number(animation.currentTime),+ offsetMs: offsets[index],+ };+ });+ }, scopeHandle);+}++/**+ * Moves every held animation to `timeMs` from the held origin (delay+ * included): each to its own `timeMs - offsetMs`. A time at or past an+ * animation's end is clamped to END_INSET_MS before it: an animation without+ * `fill` stops applying its effect exactly at the end, and the frame wanted+ * there is the last one it presents. (Half a millisecond, not less: engines+ * round `currentTime` writes to their timer resolution.) Returns the time the+ * page then presents: `timeMs`, or the latest clamped end when every held+ * animation was clamped.+ */+export async function seekAnimations(+ page: Page,+ timeMs: number,+): Promise<number> {+ return page.evaluate(+ ({t, inset}) => {+ const w = window as unknown as {+ __harnessHeld?: Animation[];+ __harnessHeldStarts?: number[];+ __harnessHeldOrigin?: number;+ };+ // An animation the page cancelled since the hold (a CSS transition is+ // cancelled whenever the page retargets its property) leaves the held set:+ // applying or playing it again would revive what the page dropped.+ const kept = (w.__harnessHeld ?? []).flatMap((animation, index) =>+ animation.playState === 'idle'+ ? []+ : [{animation, start: (w.__harnessHeldStarts ?? [])[index] ?? 0}],+ );+ w.__harnessHeld = kept.map(k => k.animation);+ w.__harnessHeldStarts = kept.map(k => k.start);+ const origin = w.__harnessHeldOrigin ?? 0;+ let presented = -Infinity;+ kept.forEach(({animation, start}) => {+ const offset = start - origin;+ const end = Number(+ animation.effect?.getComputedTiming().endTime ?? Infinity,+ );+ // A faster rate runs more curve per timeline ms.+ const rate = animation.playbackRate || 1;+ const local = Math.min((t - offset) * rate, end - inset);+ animation.currentTime = local;+ presented = Math.max(presented, local / rate + offset);+ });+ return Number.isFinite(presented) ? presented : t;+ },+ {t: timeMs, inset: END_INSET_MS},+ );+}++/**+ * Resumes (default) or finishes every held animation: only those+ * `holdAnimations` paused, so an animation the page paused stays paused. An+ * animation that repeats forever has no end to finish at, so `finish`+ * resumes it instead. The held set is cleared even if one throws.+ */+export async function releaseAnimations(+ page: Page,+ {finish = false}: {finish?: boolean} = {},+): Promise<void> {+ await page.evaluate(shouldFinish => {+ const w = window as unknown as {+ __harnessHeld?: Animation[];+ __harnessHeldStarts?: number[];+ __harnessHeldOrigin?: number;+ };+ // An animation the page cancelled since the hold (a CSS transition is+ // cancelled whenever the page retargets its property) leaves the held set:+ // applying or playing it again would revive what the page dropped.+ const kept = (w.__harnessHeld ?? []).flatMap((animation, index) =>+ animation.playState === 'idle'+ ? []+ : [{animation, start: (w.__harnessHeldStarts ?? [])[index] ?? 0}],+ );+ w.__harnessHeld = kept.map(k => k.animation);+ w.__harnessHeldStarts = kept.map(k => k.start);+ try {+ for (const {animation} of kept) {+ const end = Number(+ animation.effect?.getComputedTiming().endTime ?? Infinity,+ );+ if (shouldFinish && Number.isFinite(end)) {+ animation.finish();+ } else {+ animation.play();+ }+ }+ } finally {+ w.__harnessHeld = [];+ w.__harnessHeldStarts = [];+ w.__harnessHeldOrigin = undefined;+ }+ }, finish);+}++export interface CurveSample {+ /** The requested time. */+ readonly t: number;+ /**+ * The time the sampled element presents: `t`, or just inside the end of+ * its own animations when the sample was taken at or past it (see+ * `seekAnimations`). Read from the element's own animations only (from+ * every held one if none targets it).+ */+ readonly presentedAt: number;+ /**+ * The same per channel group, from the element's animations of those+ * properties: a 300 ms move beside a 400 ms fade on one element is read+ * just inside 300 ms for the transform and at the requested time for the+ * opacity. `curveOf` reads oracles here.+ */+ readonly presentedAtFor: {+ readonly transform: number;+ readonly opacity: number;+ };+ /**+ * The presented 2D transform: `translate` · `rotate` · `scale` ·+ * `transform`, composed in the order CSS applies them.+ */+ readonly transform: Transform2D;+ readonly opacity: number;+ /** Raw computed values, for the JSON trace. */+ readonly raw: {+ readonly transform: string;+ readonly translate: string;+ readonly rotate: string;+ readonly scale: string;+ readonly opacity: string;+ };+}++/**+ * The presented transform and opacity of `locator` at each time (ms from the+ * held origin, as for `seekAnimations`). Hold the animations first. An animation of the+ * individual `translate`, `rotate` or `scale` properties is included: they+ * are composed with `transform` into one matrix.+ */+export async function sampleCurve(+ locator: Locator,+ times: readonly number[],+): Promise<CurveSample[]> {+ const raw = await locator.evaluate(+ (element, {ts, inset}) => {+ const w = window as unknown as {+ __harnessHeld?: Animation[];+ __harnessHeldStarts?: number[];+ __harnessHeldOrigin?: number;+ };+ // An animation the page cancelled since the hold (a CSS transition is+ // cancelled whenever the page retargets its property) leaves the held set:+ // applying or playing it again would revive what the page dropped.+ const kept = (w.__harnessHeld ?? []).flatMap((animation, index) =>+ animation.playState === 'idle'+ ? []+ : [{animation, start: (w.__harnessHeldStarts ?? [])[index] ?? 0}],+ );+ w.__harnessHeld = kept.map(k => k.animation);+ w.__harnessHeldStarts = kept.map(k => k.start);+ const held = kept.map(k => k.animation);+ const origin = w.__harnessHeldOrigin ?? 0;+ if (held.length === 0) {+ throw new Error(+ 'sampleCurve: no held animations (call holdAnimations first)',+ );+ }+ // The properties each held animation of this element animates. A+ // `::before` or `::after` animation is not the element's own: its+ // clock would label the element's samples with another box's time.+ const own = held.map(animation => {+ const effect = animation.effect as KeyframeEffect | null;+ if (effect?.target !== element || effect.pseudoElement != null) {+ return null;+ }+ const properties = new Set<string>();+ for (const keyframe of effect.getKeyframes()) {+ for (const key of Object.keys(keyframe)) {+ properties.add(key);+ }+ }+ return properties;+ });+ const TRANSFORM = ['transform', 'translate', 'rotate', 'scale'];+ return ts.map(t => {+ let presented = -Infinity;+ let presentedOwn = -Infinity;+ let presentedTransform = -Infinity;+ let presentedOpacity = -Infinity;+ held.forEach((animation, index) => {+ // Each at its own offset, just inside its end: see seekAnimations.+ const offset = kept[index].start - origin;+ const end = Number(+ animation.effect?.getComputedTiming().endTime ?? Infinity,+ );+ // A faster rate runs more curve per timeline ms.+ const rate = animation.playbackRate || 1;+ const local = Math.min((t - offset) * rate, end - inset);+ animation.currentTime = local;+ presented = Math.max(presented, local / rate + offset);+ const properties = own[index];+ if (properties == null) {+ return;+ }+ presentedOwn = Math.max(presentedOwn, local / rate + offset);+ if (TRANSFORM.some(p => properties.has(p))) {+ presentedTransform = Math.max(+ presentedTransform,+ local / rate + offset,+ );+ }+ if (properties.has('opacity')) {+ presentedOpacity = Math.max(+ presentedOpacity,+ local / rate + offset,+ );+ }+ });+ const or = (value: number, fallback: number) =>+ Number.isFinite(value) ? value : fallback;+ const presentedAt = or(presentedOwn, or(presented, t));+ const style = getComputedStyle(element);+ // translate · rotate · scale · transform, as CSS applies them (all+ // about the same transform origin, which `transform` excludes too).+ // A percentage resolves against the border box, unrounded+ // (`offsetWidth` rounds it); anything else it cannot resolve (a+ // `calc()`) is an error, not a guess.+ const px = (value: string) => parseFloat(value) || 0;+ const borderBox =+ style.boxSizing === 'border-box'+ ? {width: px(style.width), height: px(style.height)}+ : {+ width:+ px(style.width) ++ px(style.paddingLeft) ++ px(style.paddingRight) ++ px(style.borderLeftWidth) ++ px(style.borderRightWidth),+ height:+ px(style.height) ++ px(style.paddingTop) ++ px(style.paddingBottom) ++ px(style.borderTopWidth) ++ px(style.borderBottomWidth),+ };+ const length = (value: string, size: number) => {+ const match = /^(-?[\d.]+(?:e-?\d+)?)(px|%)$/.exec(value);+ if (match == null) {+ throw new Error(+ `sampleCurve: cannot resolve translate ${JSON.stringify(style.translate)}`,+ );+ }+ const amount = Number(match[1]);+ return match[2] === '%' ? (amount / 100) * size : amount;+ };+ const matrix = new DOMMatrix();+ if (style.translate !== 'none') {+ // "x", "x y" or "x y z"; a calc() holds spaces, so split at the+ // top level only.+ const parts = style.translate.match(/(?:calc\([^)]*\)|\S)+/g) ?? [];+ const [x = '0px', y = '0px'] = parts;+ matrix.translateSelf(+ length(x, borderBox.width),+ length(y, borderBox.height),+ );+ }+ if (style.rotate !== 'none') {+ // "45deg", "x 45deg" (or y, z) or "1 0 0 45deg": the angle is the+ // last token, the axis what comes before it (z when none).+ const tokens = style.rotate.split(' ');+ const angle = tokens.at(-1) ?? '0deg';+ const turns: Record<string, number> = {+ deg: 1,+ rad: 180 / Math.PI,+ grad: 0.9,+ turn: 360,+ };+ const unit = /[a-z]+$/.exec(angle)?.[0] ?? 'deg';+ const named: Record<string, [number, number, number]> = {+ x: [1, 0, 0],+ y: [0, 1, 0],+ z: [0, 0, 1],+ };+ const axis: [number, number, number] =+ tokens.length === 1+ ? [0, 0, 1]+ : tokens.length === 2 && named[tokens[0]] != null+ ? named[tokens[0]]+ : tokens.length === 4+ ? [Number(tokens[0]), Number(tokens[1]), Number(tokens[2])]+ : [Number.NaN, Number.NaN, Number.NaN];+ if (!axis.every(Number.isFinite)) {+ throw new Error(+ `sampleCurve: cannot resolve rotate ${JSON.stringify(style.rotate)}`,+ );+ }+ matrix.rotateAxisAngleSelf(+ ...axis,+ parseFloat(angle) * (turns[unit] ?? 1),+ );+ }+ if (style.scale !== 'none') {+ const [sx = 1, sy = sx] = style.scale.split(' ').map(Number);+ matrix.scaleSelf(sx, sy);+ }+ if (style.transform !== 'none') {+ matrix.multiplySelf(new DOMMatrix(style.transform));+ }+ const {a, b, c, d, e, f} = matrix;+ return {+ t,+ presentedAt,+ presentedAtFor: {+ transform: or(presentedTransform, presentedAt),+ opacity: or(presentedOpacity, presentedAt),+ },+ matrix: `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`,+ transform: style.transform,+ translate: style.translate,+ rotate: style.rotate,+ scale: style.scale,+ opacity: style.opacity,+ };+ });+ },+ {ts: [...times], inset: END_INSET_MS},+ );+ return raw.map(r => ({+ t: r.t,+ presentedAt: r.presentedAt,+ presentedAtFor: r.presentedAtFor,+ transform: parseTransform(r.matrix),+ opacity: Number(r.opacity),+ raw: {+ transform: r.transform,+ translate: r.translate,+ rotate: r.rotate,+ scale: r.scale,+ opacity: r.opacity,+ },+ }));+}++export type Channel =+ 'translateX' | 'translateY' | 'scaleX' | 'scaleY' | 'rotate' | 'opacity';++/** One channel of a sampled curve, ready for `compareCurve`. */+export function curveOf(+ samples: readonly CurveSample[],+ channel: Channel,+): TimedValue[] {+ return samples.map(s => ({+ t:+ channel === 'opacity'+ ? s.presentedAtFor.opacity+ : s.presentedAtFor.transform,+ value: channel === 'opacity' ? s.opacity : s.transform[channel],+ }));+}diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex 38aa9c4876..21417851b0 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -3,23 +3,38 @@/*** @file harness.interaction.browser.spec.ts* @input Fixture pages written inline (no Storybook), real Chromium/WebKit- * @output Proof that each touch instrument delivers real engine input:+ * @output Proof that each harness instrument measures what it claims:* scripted timestamps reach the page; a flick flings natively (Chromium);- * a second finger and a pinch arrive as distinct pointers.+ * a second finger and a pinch arrive as distinct pointers; sampled curves+ * match the oracles; a held end is not part of the curve, and individual+ * transform properties are sampled; a sample at+ * an end reports the time it was read at; holding takes only running+ * document-timeline animations, each at its own offset, holds each where it+ * was read, adds a second hold to the held set without moving the first+ * hold's times, drops one the page cancels, and releases only them.* @position The harness's own test. A component spec trusts these* instruments; this file is why it may.*/-import {expect, test, type Page} from '@playwright/test';+import {expect, test, type Locator, type Page} from '@playwright/test';import {+ compareCurve,+ cubicBezier,+ curveOf,drag,flick,+ holdAnimations,installInputLog,merge,PARTIAL_LIFT_SKIP,pinch,readInputLog,+ releaseAnimations,+ sampleCurve,+ seekAnimations,+ springStep,tap,+ timeline,touchDriver,withFinger,} from './index';@@ -46,6 +61,37 @@ async function fixture(page: Page) {await page.goto('http://harness.test/');}+/** Until an animation on the element runs with a start time, `ms` into it. */+async function untilRunning(locator: Locator, ms = 0) {+ await expect+ .poll(() =>+ locator.evaluate(+ (el, min) =>+ el+ .getAnimations()+ .some(+ a =>+ a.playState === 'running' &&+ a.startTime != null &&+ Number(a.currentTime ?? 0) >= min,+ ),+ ms,+ ),+ )+ .toBe(true);+}++/** Until nothing on the element is running. */+async function untilIdle(locator: Locator) {+ await expect+ .poll(() =>+ locator.evaluate(el =>+ el.getAnimations().some(a => a.playState === 'running'),+ ),+ )+ .toBe(false);+}+test.describe('touch input', () => {test('the page receives trusted touches and pointers at the scripted positions and times', async ({page,@@ -206,3 +252,620 @@ test.describe('touch input', () => {).toBe(2);});});++test.describe('curve sampling', () => {+ test('a CSS transition samples onto its cubic-bezier to 0.05 px', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.style.transition = 'transform 400ms cubic-bezier(0.24, 1, 0.4, 1)';+ void (el as HTMLElement).offsetWidth;+ el.style.transform = 'translateY(200px)';+ });+ const held = await holdAnimations(page, box);+ expect(held).toHaveLength(1);+ expect(held[0].kind).toBe('CSSTransition');+ const samples = curveOf(+ await sampleCurve(box, timeline(400)),+ 'translateY',+ );+ const ease = cubicBezier(0.24, 1, 0.4, 1);+ const result = compareCurve(samples, t => 200 * ease(t / 400), 0.05);+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.05,+ );+ });++ test('a spring baked into linear() matches the SwiftUI spring oracle', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ const spring = {response: 0.4, dampingFraction: 0.75};+ const duration = 1200;+ await box.evaluate(+ (el, {stops, ms}) => {+ el.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(200px)'}],+ {duration: ms, easing: `linear(${stops})`},+ );+ },+ {+ stops: timeline(duration, 4)+ .map(t => springStep(spring, t).toFixed(6))+ .join(', '),+ ms: duration,+ },+ );+ await holdAnimations(page, box);+ const samples = curveOf(+ await sampleCurve(box, timeline(duration, 1000 / 60)),+ 'translateX',+ );+ // linear() draws chords between the 4 ms stops: at most h²/8 · |x''| =+ // 0.004² / 8 · 200 · (2π / 0.4)² ≈ 0.1 px off the exact oracle.+ const result = compareCurve(+ samples,+ t => 200 * springStep(spring, t),+ 0.15,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.15,+ );+ expect(Math.max(...samples.map(s => s.value))).toBeGreaterThan(200); // the overshoot is presented+ });+});++test.describe('holding', () => {+ test('a sample at an end reports the time it was read at', async ({page}) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el =>+ el.animate(+ [{transform: 'translateY(0px)'}, {transform: 'translateY(200px)'}],+ {duration: 300, easing: 'linear'},+ ),+ );+ await holdAnimations(page, box);+ const samples = await sampleCurve(box, [0, 150, 300]);+ // Read just inside the end, and labelled so.+ expect(samples.at(-1)).toMatchObject({t: 300, presentedAt: 299.5});+ const result = compareCurve(+ curveOf(samples, 'translateY'),+ t => (200 * t) / 300,+ 0.05,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.05,+ );+ await releaseAnimations(page);+ });++ test('only running document-timeline animations are held, each at its own offset', async ({+ page,+ }) => {+ await fixture(page);+ // Besides #box: a finished fade, an animation the page paused, one on a+ // scroll timeline, and a second runner started 100 ms after #box's.+ const startGap = await page.evaluate(async () => {+ const make = (id: string) => {+ const el = document.createElement('div');+ el.id = id;+ el.style.cssText =+ 'position:absolute;left:0;top:300px;width:40px;height:40px;background:#c63';+ document.body.append(el);+ return el;+ };+ make('finished').animate([{opacity: 0}, {opacity: 1}], {+ duration: 50,+ fill: 'both',+ });+ const paused = make('paused').animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(100px)'}],+ {duration: 1000},+ );+ paused.pause();+ paused.currentTime = 500;+ const timelines = window as unknown as {+ ScrollTimeline?: new (options: object) => AnimationTimeline;+ };+ if (timelines.ScrollTimeline != null) {+ new Animation(+ new KeyframeEffect(make('scrolled'), [{opacity: 0}, {opacity: 1}], {+ duration: 1000,+ }),+ new timelines.ScrollTimeline({source: document.scrollingElement}),+ ).play();+ }+ await new Promise(resolve => setTimeout(resolve, 120));+ const run = (el: Element | null) =>+ el?.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(300px)'}],+ {duration: 600, easing: 'linear'},+ );+ const box = run(document.getElementById('box'));+ const gap = new Promise(resolve => setTimeout(resolve, 100));+ // #box's first frame comes late, as on a loaded machine: its start time+ // resolves then, so the runners' offset is the difference of their start+ // times, not the timer's 100 ms.+ const until = performance.now() + 60;+ while (performance.now() < until) {+ // Busy: no frame runs.+ }+ await gap;+ const later = run(make('later'));+ await Promise.all([box?.ready, later?.ready]);+ return Number(later?.startTime) - Number(box?.startTime);+ });+ const held = await holdAnimations(page);+ expect(held.map(a => a.target)).toEqual(['div#box', 'div#later']);+ const [first, later] = held;+ expect(first.offsetMs).toBe(0);+ expect(startGap).toBeGreaterThan(0);+ expect(later.offsetMs).toBeCloseTo(startGap, 0);+ const x = (id: string) =>+ page+ .locator(`#${id}`)+ .evaluate(el => new DOMMatrix(getComputedStyle(el).transform).m41);+ expect(await seekAnimations(page, 300)).toBe(300);+ expect(await x('box')).toBeCloseTo(150, 1);+ expect(await x('later')).toBeCloseTo(+ (300 * (300 - later.offsetMs)) / 600,+ 1,+ );+ // The finished fade kept its end value; the paused animation stays put.+ expect(+ await page+ .locator('#finished')+ .evaluate(el => getComputedStyle(el).opacity),+ ).toBe('1');+ await releaseAnimations(page);+ await page.waitForTimeout(100);+ expect(+ await page.evaluate(() => {+ const animation = document.getElementById('paused')?.getAnimations()[0];+ return [animation?.playState, Number(animation?.currentTime)];+ }),+ ).toEqual(['paused', 500]);+ });++ test("a sample is labelled from its own element's animations, per channel", async ({+ page,+ }) => {+ await fixture(page);+ // #box moves for 300 ms and fades for 400 ms; another element runs longer.+ await page.evaluate(() => {+ const box = document.getElementById('box');+ box?.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(300px)'}],+ {duration: 300, easing: 'linear'},+ );+ box?.animate([{opacity: 1}, {opacity: 0}], {+ duration: 400,+ easing: 'linear',+ });+ const other = document.createElement('div');+ other.style.cssText =+ 'position:absolute;top:300px;width:40px;height:40px';+ document.body.append(other);+ other.animate([{opacity: 0}, {opacity: 1}], {duration: 600});+ });+ await holdAnimations(page);+ const samples = await sampleCurve(page.locator('#box'), [0, 150, 300]);+ // The move is read just inside its end, the fade where it is.+ expect(samples.at(-1)?.presentedAtFor).toEqual({+ transform: 299.5,+ opacity: 300,+ });+ const move = compareCurve(curveOf(samples, 'translateX'), t => t, 0.05);+ expect(move.maxError, JSON.stringify(move.worst)).toBeLessThanOrEqual(0.05);+ const fade = compareCurve(+ curveOf(samples, 'opacity'),+ t => 1 - t / 400,+ 0.002,+ );+ expect(fade.maxError, JSON.stringify(fade.worst)).toBeLessThanOrEqual(+ 0.002,+ );+ await releaseAnimations(page);+ });++ test("a pseudo-element's animation does not label its element's samples", async ({+ page,+ }) => {+ await fixture(page);+ // #box moves for 300 ms; its ::after fades for 600 ms.+ await page.evaluate(() => {+ const style = document.createElement('style');+ style.textContent = "#box::after { content: ''; display: block; }";+ document.head.append(style);+ const box = document.getElementById('box');+ box?.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(300px)'}],+ {duration: 300, easing: 'linear'},+ );+ box?.animate([{opacity: 1}, {opacity: 0}], {+ duration: 600,+ pseudoElement: '::after',+ });+ });+ await holdAnimations(page);+ const samples = await sampleCurve(page.locator('#box'), [0, 150, 300]);+ // The move is read just inside its own end, not at the ::after's time.+ expect(samples.at(-1)?.presentedAt).toBe(299.5);+ await releaseAnimations(page);+ });++ test('a percentage translate resolves against the unrounded border box, and a calc() is refused', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.style.width = '80.6px';+ el.style.height = '40.4px';+ el.animate([{translate: '0% 0%'}, {translate: '100% 50%'}], {+ duration: 300,+ easing: 'linear',+ });+ });+ await holdAnimations(page, box);+ const [mid] = await sampleCurve(box, [150]);+ expect(mid.transform.translateX).toBeCloseTo(40.3, 2);+ expect(mid.transform.translateY).toBeCloseTo(10.1, 2);+ // Finished, so no frame can pass between this release and the next+ // animation with the first one still running.+ await releaseAnimations(page, {finish: true});++ await box.evaluate(el => {+ el.animate(+ [+ {translate: 'calc(10% + 5px) 0px'},+ {translate: 'calc(20% + 5px) 0px'},+ ],+ {duration: 300, easing: 'linear'},+ );+ });+ await holdAnimations(page, box);+ await expect(sampleCurve(box, [150])).rejects.toThrow(+ /cannot resolve translate/,+ );+ await releaseAnimations(page);+ });++ test('a faster playback rate is read on the timeline by seeks and samples', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ // At playback rate 2 a seek or sample at t reads the curve at 2t.+ await box.evaluate(el => {+ const animation = el.animate(+ [{translate: '0px 0px'}, {translate: '100px 0px'}],+ {duration: 1000, easing: 'linear'},+ );+ animation.playbackRate = 2;+ });+ await holdAnimations(page, box);+ await seekAnimations(page, 125);+ const x = await box.evaluate(+ el =>+ new DOMMatrix(getComputedStyle(el).transform).m41 ++ Number.parseFloat(getComputedStyle(el).translate || '0'),+ );+ expect(x).toBeCloseTo(25, 0);+ const [sample] = await sampleCurve(box, [250]);+ expect(sample.transform.translateX).toBeCloseTo(50, 0);+ await releaseAnimations(page, {finish: true});+ });++ test('a held end is solved through a cubic-bézier effect easing, a reversed one reads to the full end, and a rotate about x composes on its axis', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.animate(+ [+ {translate: '0px 0px', offset: 0},+ {translate: '100px 0px', offset: 0.5},+ {translate: '100px 0px', offset: 1},+ ],+ {duration: 1000, easing: 'cubic-bezier(0.42, 0, 1, 1)'},+ );+ });+ const [held] = await holdAnimations(page, box);+ // The keyframe offset 0.5 is progress, not 500 ms of time: the run starts+ // where the eased progress reaches 0.5.+ const ease = cubicBezier(0.42, 0, 1, 1);+ let lo = 0;+ let hi = 1;+ for (let i = 0; i < 60; i += 1) {+ const mid = (lo + hi) / 2;+ if (ease(mid) < 0.5) {+ lo = mid;+ } else {+ hi = mid;+ }+ }+ expect(held.curveEndMs).toBeCloseTo(lo * 1000, 0);+ expect(held.curveEndMs).toBeGreaterThan(600);+ await releaseAnimations(page, {finish: true});++ // Played in reverse, the held run is where the motion starts: the curve+ // runs to the full end.+ await box.evaluate(el => {+ el.animate(+ [+ {translate: '0px 0px', offset: 0},+ {translate: '100px 0px', offset: 0.5},+ {translate: '100px 0px', offset: 1},+ ],+ {duration: 1000, easing: 'linear', direction: 'reverse'},+ );+ });+ const [reversed] = await holdAnimations(page, box);+ expect(reversed.curveEndMs).toBeCloseTo(1000, 0);+ await releaseAnimations(page, {finish: true});++ // One reversed by `reverse()` (a negative playback rate) is refused by+ // a hold, which seeks curves forward only.+ await box.evaluate(async el => {+ const animation = el.animate(+ [+ {translate: '0px 0px', offset: 0},+ {translate: '100px 0px', offset: 0.5},+ {translate: '100px 0px', offset: 1},+ ],+ {duration: 1000, easing: 'linear'},+ );+ animation.reverse();+ await animation.ready;+ });+ // Chromium lists a reversed run in getAnimations() a frame after ready.+ await untilRunning(box);+ await expect(holdAnimations(page, box)).rejects.toThrow(/runs backward/);+ await box.evaluate(el => el.getAnimations().forEach(a => a.finish()));++ // A property keyed only before the held run, and a last keyframe short of+ // offset 1, each get an implicit end frame: the curve runs to its end.+ for (const keyframes of [+ [+ {translate: '0px 0px', opacity: 0, offset: 0},+ {translate: '100px 0px', offset: 0.5},+ {translate: '100px 0px', offset: 1},+ ],+ [+ {translate: '0px 0px', offset: 0},+ {translate: '100px 0px', offset: 0.5},+ {translate: '100px 0px', offset: 0.8},+ ],+ ]) {+ await box.evaluate((el, frames) => {+ el.animate(frames, {duration: 1000, easing: 'linear'});+ }, keyframes);+ const [moving] = await holdAnimations(page, box);+ expect(moving.curveEndMs).toBeCloseTo(1000, 0);+ await releaseAnimations(page, {finish: true});+ }++ await box.evaluate(el => {+ el.animate([{rotate: 'x 0deg'}, {rotate: 'x 60deg'}], {+ duration: 300,+ easing: 'linear',+ });+ });+ await holdAnimations(page, box);+ const [end] = await sampleCurve(box, [300]);+ // About x, nothing turns in the plane: no z rotation, and y shrinks by+ // cos 60°.+ expect(end.transform.rotate).toBeCloseTo(0, 1);+ expect(end.transform.scaleY).toBeCloseTo(0.5, 2);+ await releaseAnimations(page, {finish: true});+ });++ test('a hold stays where it was read, not a frame later', async ({page}) => {+ await fixture(page);+ await page.evaluate(() => {+ document+ .getElementById('box')+ ?.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(300px)'}],+ {duration: 1000, easing: 'linear'},+ );+ });+ const box = page.locator('#box');+ await untilRunning(box, 50);+ const [held] = await holdAnimations(page, box);+ // Two frames later, the held animation is still where the hold read it.+ const after = await box.evaluate(+ el =>+ new Promise<number>(resolve =>+ requestAnimationFrame(() =>+ requestAnimationFrame(() =>+ resolve(Number(el.getAnimations()[0]?.currentTime)),+ ),+ ),+ ),+ );+ expect(held.heldAtMs).not.toBeNull();+ expect(Math.abs(after - (held.heldAtMs ?? 0))).toBeLessThan(0.5);+ await releaseAnimations(page);+ });++ test('a second hold adds to the held set, and releasing resumes both', async ({+ page,+ }) => {+ await fixture(page);+ await page.evaluate(() => {+ document+ .getElementById('box')+ ?.animate(+ [{transform: 'translateX(0px)'}, {transform: 'translateX(300px)'}],+ {duration: 300, easing: 'linear', fill: 'forwards'},+ );+ const other = document.createElement('div');+ other.id = 'other';+ document.body.append(other);+ other.animate([{opacity: 0}, {opacity: 1}], {+ duration: 300,+ fill: 'forwards',+ });+ });+ const box = page.locator('#box');+ expect(await holdAnimations(page, box)).toHaveLength(1);+ expect(await holdAnimations(page, page.locator('#other'))).toHaveLength(1);+ await releaseAnimations(page);+ // The first hold was released too: the move runs to its end, and rest is+ // its end, not the frame it was held on.+ await untilIdle(box);+ expect(await box.evaluate(el => getComputedStyle(el).transform)).toBe(+ 'matrix(1, 0, 0, 1, 300, 0)',+ );+ expect(+ await page.evaluate(+ () =>+ document.getAnimations().filter(a => a.playState === 'paused').length,+ ),+ ).toBe(0);+ });++ test("a later hold of an earlier-started animation keeps the first hold's times", async ({+ page,+ }) => {+ await fixture(page);+ // #early starts 100 ms before #box's 600 ms linear move to 300 px.+ await page.evaluate(+ () =>+ new Promise<void>(resolve => {+ const early = document.createElement('div');+ early.id = 'early';+ document.body.append(early);+ early.animate([{opacity: 0}, {opacity: 1}], {duration: 2000});+ setTimeout(() => {+ document+ .getElementById('box')+ ?.animate(+ [+ {transform: 'translateX(0px)'},+ {transform: 'translateX(300px)'},+ ],+ {duration: 600, easing: 'linear'},+ );+ resolve();+ }, 100);+ }),+ );+ const box = page.locator('#box');+ await untilRunning(box);+ // The later-started element is held first.+ const [first] = await holdAnimations(page, box);+ const [later] = await holdAnimations(page, page.locator('#early'));+ const samples = await sampleCurve(box, [0, 150, 300]);+ expect(+ samples.map(sample => Math.round(sample.transform.translateX)),+ ).toEqual([0, 75, 150]);+ // A later hold's earlier start has a negative offset; the origin stays.+ expect(first.offsetMs).toBe(0);+ expect(later.offsetMs).toBeLessThan(-50);+ await releaseAnimations(page);+ });++ test('a held transition the page retargets is dropped, not revived', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ await box.evaluate(el => {+ el.style.transition = 'transform 300ms linear';+ el.getBoundingClientRect();+ el.style.transform = 'translateX(300px)';+ });+ await untilRunning(box);+ expect(await holdAnimations(page, box)).toHaveLength(1);+ // The page sends the box back: the held transition is cancelled, and a+ // new one runs from where the box is.+ await box.evaluate(el => {+ const w = window as unknown as {__cancelled: Animation};+ w.__cancelled = el.getAnimations()[0];+ el.style.transform = 'none';+ });+ const state = () =>+ page.evaluate(() => {+ const w = window as unknown as {+ __cancelled: Animation;+ __harnessHeld: Animation[];+ };+ return {+ cancelled: w.__cancelled.playState,+ held: w.__harnessHeld.length,+ };+ });+ await seekAnimations(page, 150);+ expect(await state()).toEqual({cancelled: 'idle', held: 0});+ await releaseAnimations(page);+ await untilIdle(box);+ expect(await state()).toEqual({cancelled: 'idle', held: 0});+ expect(await box.evaluate(el => getComputedStyle(el).transform)).toBe(+ 'none',+ );+ });++ test('finishing resumes an animation that repeats forever and still clears the held set', async ({+ page,+ }) => {+ await fixture(page);+ await page.evaluate(() => {+ const box = document.getElementById('box');+ box?.animate([{rotate: '0deg'}, {rotate: '360deg'}], {+ duration: 800,+ iterations: Infinity,+ });+ const fade = document.createElement('div');+ fade.id = 'fade';+ document.body.append(fade);+ fade.animate([{opacity: 0}, {opacity: 1}], {duration: 300});+ });+ expect(await holdAnimations(page)).toHaveLength(2);+ await releaseAnimations(page, {finish: true});+ expect(+ await page.evaluate(() => ({+ spinner: document.getElementById('box')?.getAnimations()[0]?.playState,+ fade: document.getElementById('fade')?.getAnimations().length,+ held: (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld+ .length,+ })),+ ).toEqual({spinner: 'running', fade: 0, held: 0});+ });+});++test.describe('held ends', () => {+ test('an end value held by the keyframes is not part of the curve, and individual transform properties are sampled', async ({+ page,+ }) => {+ await fixture(page);+ const box = page.locator('#box');+ // 300 ms of motion on the individual `translate` and `scale` properties,+ // then 5 s holding the end values: playState stays 'running' throughout.+ await box.evaluate(el => {+ el.animate(+ [+ {translate: '0px 0px', scale: '1', offset: 0},+ {translate: '0px 120px', scale: '1.5', offset: 300 / 5300},+ {translate: '0px 120px', scale: '1.5', offset: 1},+ ],+ {duration: 5300, fill: 'forwards'},+ );+ });+ const held = await holdAnimations(page, box);+ expect(held[0].curveEndMs).toBeCloseTo(300, 0);+ const [mid, end] = await sampleCurve(box, [150, 300]);+ expect(mid.raw.translate).toBe('0px 60px');+ expect(mid.transform.translateY).toBeCloseTo(60, 1);+ expect(mid.transform.scaleX).toBeCloseTo(1.25, 3);+ expect(end.transform.translateY).toBeCloseTo(120, 1);+ expect(end.transform.scaleY).toBeCloseTo(1.5, 3);+ });+});diff --git a/internal/interaction-harness/src/index.ts b/internal/interaction-harness/src/index.tsindex 6fc3b85340..32c238e4a1 100644--- a/internal/interaction-harness/src/index.ts+++ b/internal/interaction-harness/src/index.ts@@ -12,6 +12,7 @@* SYNC: When a module is added, export it here and describe it in README.md.*/+export * from './curves';export * from './math';export * from './scripts';export * from './story';diff --git a/playwright.interaction.config.ts b/playwright.interaction.config.tsindex b3dfd65472..e4bfed2f51 100644--- a/playwright.interaction.config.ts+++ b/playwright.interaction.config.ts@@ -3,8 +3,8 @@/*** @file playwright.interaction.config.ts* @input Uses @playwright/test- * @output Touch interaction proofs on a phone-sized touch screen, in Chromium- * and WebKit.+ * @output Touch interaction and animation proofs on a phone-sized touch+ * screen, in Chromium and WebKit.* @position Run with `pnpm test:interaction`. Separate from `pnpm test` (no* browser needed there) and from playwright.config.ts (accessibility* contracts on desktop profiles).