An open source design system that's fully customizable and agent ready
TypeScript
test(interaction-harness): judge a play at the component's thresholds (#10501)
Christopher Chedeaub87846c1d518
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex fffff384f9..f95401dc87 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -563,6 +563,17 @@ gesture the same way, and the play fails with `TouchPacingError`. A play whoseproof reads no release from the lift, such as a pinch's end, passes`releaseUnread`.+A proof whose component decides on a threshold names it in `boundaries`:+the release speed a pager pages from (`releasePxPerS`), or the hold after+which it catches the content (`holdMs`). In WebKit the play then fails by+name when the page read the release, or the first finger's hold from+touch-down to lift, on the other side of the threshold from the script. A+scrolling surface reads its release as Core's `scrollVelocity` does: pass+`release: 'scroll'`. Each pacing error names the longest time the page drew no+frame during the gesture. A page that drew nothing for 100 ms or more never+received the gesture as scripted. To read a frame before the gesture, a judged+play starts one frame later.+A wheel gesture is a run of steps, and `wheel` waits for each step's roundtrip, so on a loaded runner awaited steps land as far apart as a round triptakes: 49 to 141 ms in WebKit, past the 100 ms a proof may allow between thediff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex e0a4d4f07a..6aa7c4360a 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -456,6 +456,11 @@ test.describe('touch input', () => {const {numbers} = outcome as TouchLiftStallError;expect(numbers.gapMs).toBeGreaterThan(40);expect(numbers.scriptedGapMs).toBeLessThanOrEqual(40);+ // Like every pacing error, it names the longest frame gap.+ expect(numbers.frameGapMs).toEqual(expect.any(Number));+ expect(String(outcome)).toMatch(+ /; the page drew no frame for \d+ ms during the gesture\. /,+ );// The error gives the gap the page itself read.const gap = await pageLiftGap();expect(gap).toBeGreaterThan(40);@@ -591,6 +596,43 @@ test.describe('touch input', () => {}});+ test("a tap the page holds past the component's catch time fails by name, with the time the page drew no frame, where the page stamps touches on arrival", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'webkit',+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',+ );+ // The page's own touchstart listener holds its main thread for 120 ms, so+ // WebKit hands it the lift late, and no frame is drawn meanwhile.+ await page.route('http://touch-hold.test/', route =>+ route.fulfill({+ contentType: 'text/html',+ body: '<!doctype html><body style="margin:0;height:3000px;touch-action:none"><script>addEventListener("touchstart",()=>{if(window.busy){const end=performance.now()+120;while(performance.now()<end){}}},{passive:true})</script>',+ }),+ );+ await page.goto('http://touch-hold.test/');+ const driver = await touchDriver(page);+ const script = tap({x: 200, y: 300}, {holdMs: 40});+ // On a free page, the 40 ms hold stays under the 85 ms bound.+ await driver.play(script, {boundaries: {holdMs: 85}});+ await page.evaluate(() => {+ (window as unknown as {busy: boolean}).busy = true;+ });+ // Without a bound, a tap's hold is not judged.+ await driver.play(script);+ const outcome = await driver.play(script, {boundaries: {holdMs: 85}}).then(+ () => 'resolved',+ (error: unknown) => error,+ );+ expect(String(outcome)).toMatch(+ /the page read a hold of \d+ ms where the script holds 40 ms, on the other side of the 85 ms the component decides on; the page drew no frame for (\d+) ms during the gesture/,+ );+ const gap = Number(/drew no frame for (\d+) ms/.exec(String(outcome))?.[1]);+ expect(gap).toBeGreaterThan(100);+ });+test('a Chromium play carries the scripted times, so a slow onEvent before its lift does not fail it', async ({page,browserName,diff --git a/internal/interaction-harness/src/touch.pacing.test.ts b/internal/interaction-harness/src/touch.pacing.test.tsindex 7583b4d0e1..2c9d111340 100644--- a/internal/interaction-harness/src/touch.pacing.test.ts+++ b/internal/interaction-harness/src/touch.pacing.test.ts@@ -15,12 +15,15 @@* interval after the last move reads as rest, a fault unless the script rests* too. A throw where the script rests is a fault, and so are fewer than two* moves. A gap the page's own listeners held is the page's; a late send is- * the runner's.+ * the runner's. A scrolling surface's release also reads the interval+ * before them. A release or a hold on the other side of a play's boundary+ * from the script's is a fault. Each pacing error names the longest time+ * the page drew no frame.* @position Node unit tests beside the harness's browser self-tests.** SYNC: When modified, update touch.ts (pacedDeadline, touchPacingFault,- * TouchPacingError, TouchPageStallError, TOUCH_STILLNESS_MS,- * TOUCH_RELEASE_NEWEST_WEIGHT).+ * TouchPacingError, TouchPageStallError, TouchLiftStallError,+ * TOUCH_STILLNESS_MS, TOUCH_RELEASE_NEWEST_WEIGHT).*/import {describe, expect, it} from 'vitest';@@ -37,6 +40,8 @@ import {TouchPacingError,TouchPageStallError,liftStallError,+ longestFrameGap,+ readHold,type TouchArrival,type TouchPacing,} from './touch';@@ -581,3 +586,91 @@ describe('touchPlayError', () => {expect(errorFor(heldLift, slowAt5)).toBeInstanceOf(TouchLiftStallError);});});++describe('boundaries, the scroll release and frame evidence', () => {+ // The third move reaches the page 20 ms late; the moves after it keep the+ // script's 16 ms.+ const lateThird = at([0, 16, 32, 68, 84, 100, 116]);++ it("reads a scrolling surface's release from the interval before the pan's two", () => {+ expect(readRelease(FLICK, lateThird)?.pagePxPerS).toBeCloseTo(1000, 6);+ // 0.25 x 1,000 + 0.75 x (0.2 x 1,000 + 0.8 x 444.4).+ expect(readRelease(FLICK, lateThird, 'scroll')?.pagePxPerS).toBeCloseTo(+ 666.67,+ 1,+ );+ expect(readRelease(FLICK, lateThird, 'scroll')?.scriptPxPerS).toBeCloseTo(+ 1000,+ 6,+ );+ });++ it('fails a release on the other side of the boundary from the script, and only then', () => {+ const fault = touchPacingFault(FLICK, lateThird, undefined, {+ release: 'scroll',+ boundaries: {releasePxPerS: 800},+ });+ expect(fault?.kind).toBe('boundary');+ expect(fault?.threshold).toBe(800);+ expect(new TouchPacingError(fault!).message).toMatch(+ /the page read a release of 667 px\/s where the script throws 1000 px\/s, on the other side of the 800 px\/s the component decides on \(gaps 36, 16, 16, 16 ms where the script spaces 16, 16, 16, 16 ms\)/,+ );+ // The pan's release reads the script's, and 667 px/s is past 600.+ expect(+ touchPacingFault(FLICK, lateThird, undefined, {+ boundaries: {releasePxPerS: 800},+ }),+ ).toBeNull();+ expect(+ touchPacingFault(FLICK, lateThird, undefined, {+ release: 'scroll',+ boundaries: {releasePxPerS: 600},+ }),+ ).toBeNull();+ });++ it('fails a hold on the other side of the boundary from the script, and only then', () => {+ const finger = {id: 0, x: 100, y: 50};+ const tap: TouchEventStep[] = [+ {t: 0, type: 'touchStart', fingers: [finger], changed: [finger]},+ {t: 40, type: 'touchEnd', fingers: [], changed: [finger]},+ ];+ expect(readHold(tap, at([0, 97]))).toEqual({page: 97, script: 40});+ const fault = touchPacingFault(tap, at([0, 97]), undefined, {+ boundaries: {holdMs: 85},+ });+ expect(fault?.kind).toBe('hold');+ expect(new TouchPacingError(fault!).message).toMatch(+ /the page read a hold of 97 ms where the script holds 40 ms, on the other side of the 85 ms the component decides on/,+ );+ expect(+ touchPacingFault(tap, at([0, 60]), undefined, {boundaries: {holdMs: 85}}),+ ).toBeNull();+ const long = tap.map((step, i) => (i === 1 ? {...step, t: 150} : step));+ expect(+ touchPacingFault(long, at([0, 140]), undefined, {+ boundaries: {holdMs: 85},+ }),+ ).toBeNull();+ });++ it('names the longest time the page drew no frame during the gesture', () => {+ const frames = [0, 16, 33, 50, 226, 243];+ expect(longestFrameGap(frames, at([20, 36, 52, 230]))).toBe(176);+ expect(longestFrameGap([], at([20, 230]))).toBeNull();+ // No frame before the gesture: the gap runs from its first touch.+ expect(longestFrameGap([381, 397, 408, 424], at([261, 420]))).toBe(120);+ const fault = touchPacingFault(FLICK, lateThird, undefined, {+ release: 'scroll',+ boundaries: {releasePxPerS: 800},+ });+ expect(new TouchPacingError({...fault!, frameGapMs: 176}).message).toMatch(+ /; the page drew no frame for 176 ms during the gesture: /,+ );+ const lift = {scriptedGapMs: 16, gapMs: 120, onEventMs: 104};+ expect(new TouchLiftStallError({...lift, frameGapMs: 176}).message).toMatch(+ /back; the page drew no frame for 176 ms during the gesture\. /,+ );+ expect(new TouchLiftStallError(lift).message).not.toMatch(/drew no frame/);+ });+});diff --git a/internal/interaction-harness/src/touch.ts b/internal/interaction-harness/src/touch.tsindex 5ffbb7a195..ee5c57faa7 100644--- a/internal/interaction-harness/src/touch.ts+++ b/internal/interaction-harness/src/touch.ts@@ -92,6 +92,22 @@ export const TOUCH_STILLNESS_MS = 40;*/export const TOUCH_RELEASE_NEWEST_WEIGHT = 0.2;+/**+ * The newest pan value's share of a scrolling surface's release, such as a+ * pager's; the pan value before it carries the rest (`PlayOptions.release`).+ *+ * SYNC: Keep equal to `UIKIT_VELOCITY.scrollReleaseWeight` in+ * packages/core/src/motion/uikit/gestures.ts.+ */+export const TOUCH_SCROLL_RELEASE_NEWEST_WEIGHT = 0.25;++/**+ * Which of Core's release filters a page reads (`PlayOptions.release`): a+ * dragged surface's (`'pan'`) or a scrolling surface's, such as a pager's+ * (`'scroll'`).+ */+export type TouchReleaseFilter = 'pan' | 'scroll';+export interface PlayOptions {/*** Pace dispatch on the wall clock so each event leaves at its scripted time@@ -133,6 +149,25 @@ export interface PlayOptions {* (see `pacing`).*/readonly releaseUnread?: boolean;+ /**+ * Which release the page reads (default `'pan'`, a dragged surface's). A+ * scrolling surface, such as a pager, reads `'scroll'`: Core's+ * `scrollVelocity` blends the newest pan value with the one before it.+ */+ readonly release?: TouchReleaseFilter;+ /**+ * The thresholds the component under test decides on: a release speed it+ * pages from (`releasePxPerS`), a hold it catches after (`holdMs`). The+ * play fails by name when the page read the release on the other side of+ * a threshold from the script. The first finger's hold from touch-down to+ * lift fails the same way. Then the proof never judges a gesture the page+ * did not receive. Only a driver whose page stamps touches on arrival+ * (WebKit) judges them.+ */+ readonly boundaries?: {+ readonly releasePxPerS?: number;+ readonly holdMs?: number;+ };/*** Called after each event is dispatched, before the next one (storyboards).* The next event waits for it, so page work here delays that event by a@@ -262,9 +297,10 @@ export interface TouchPacingFault {/*** `'rest'`: the page read a resting finger; `'throw'`: a throw where the* script rests; `'moves'`: fewer than two moves; `'release'`: another- * speed.+ * speed. `'boundary'` and `'hold'`: a release or a hold on the other side+ * of a play's `boundaries` from the script's.*/- readonly kind: 'rest' | 'throw' | 'moves' | 'release';+ readonly kind: 'rest' | 'throw' | 'moves' | 'release' | 'boundary' | 'hold';/** The release the page read, px/s (0 for a rest or too few moves). */readonly pageReleasePxPerS: number;/** The script's release, px/s. */@@ -281,6 +317,16 @@ export interface TouchPacingFault {readonly gapMs: number;readonly handlingMs: number;} | null;+ /** For `'boundary'` and `'hold'`: the threshold crossed, px/s or ms. */+ readonly threshold?: number;+ /** For `'hold'`: the first finger's hold as the page read it, and as scripted, ms. */+ readonly holdMs?: {readonly page: number; readonly script: number};+ /**+ * The longest time the page drew no frame during the gesture, ms, or null+ * unread. A gap far past a frame means the renderer was starved: no+ * dispatch can deliver a gesture's timing then.+ */+ readonly frameGapMs?: number | null;}/** The lifting finger's release, read from the page's stamps and the script's. */@@ -321,24 +367,30 @@ interface CoreReading {readonly moves: number;/** The finger was still for longer than the stillness interval. */readonly rests: boolean;- /** The moved samples the release reads, oldest first (up to three). */+ /**+ * The moved samples the release reads, oldest first: up to three for a+ * pan's release, four for a scrolling surface's.+ */readonly moved: readonly FingerSample[];}/*** The release Core's velocity tracker reads, px/s. It copies that filter:* Core's `VelocityTracker` is internal to the core package, so the harness- * cannot call it. Keep the two equal (`add`, `releases`, `panVelocity`):- * Core's VelocityTracker.harness.test.ts reads the same samples with both.- * Only a sample that moves+ * cannot call it. Keep the two equal (`add`, `releases`, `panVelocity`,+ * `scrollVelocity`): Core's VelocityTracker.harness.test.ts reads the same+ * samples with both. Only a sample that moves* counts, and a sample at the newest moved sample's time replaces it. The* newest interval weighs 0.2 and the one before it 0.8, and an interval- * across no time reads 0. The release is 0 with fewer than two moves after- * the touch-down, or after a rest longer than the stillness interval.+ * across no time reads 0. A scrolling surface's release blends the newest+ * pan value, 0.25, with the one before it. The release is 0 with fewer than+ * two moves after the touch-down, or after a rest longer than the stillness+ * interval.*/function coreRelease(samples: readonly FingerSample[],liftTime: number,+ filter: TouchReleaseFilter = 'pan',): CoreReading {const moved: FingerSample[] = [];let moves = 0;@@ -356,7 +408,7 @@ function coreRelease(moved[moved.length - 1] = sample;} else {moved.push(sample);- if (moved.length > 3) {+ if (moved.length > 4) {moved.shift();}if (last != null) {@@ -364,10 +416,11 @@ function coreRelease(}}}+ const read = filter === 'scroll' ? moved : moved.slice(-3);const last = moved[moved.length - 1];const rests = last != null && liftTime - last.time > TOUCH_STILLNESS_MS;if (moves < 2 || last == null || rests) {- return {x: 0, y: 0, moves, rests, moved};+ return {x: 0, y: 0, moves, rests, moved: read};}const pair = (a: FingerSample, b: FingerSample) => {const seconds = (b.time - a.time) / 1000;@@ -375,16 +428,33 @@ function coreRelease(? {x: (b.x - a.x) / seconds, y: (b.y - a.y) / seconds}: {x: 0, y: 0};};- const n = moved.length;- const current = pair(moved[n - 2], moved[n - 1]);- const before = n === 3 ? pair(moved[0], moved[1]) : current;- const w = TOUCH_RELEASE_NEWEST_WEIGHT;+ // The pan's value over the last three of `upTo`, as Core updates it on+ // each moved sample.+ const pan = (upTo: readonly FingerSample[]) => {+ const n = upTo.length;+ if (n < 2) {+ return {x: 0, y: 0};+ }+ const current = pair(upTo[n - 2], upTo[n - 1]);+ const before = n >= 3 ? pair(upTo[n - 3], upTo[n - 2]) : current;+ const w = TOUCH_RELEASE_NEWEST_WEIGHT;+ return {+ x: w * current.x + (1 - w) * before.x,+ y: w * current.y + (1 - w) * before.y,+ };+ };+ const current = pan(moved.slice(-3));+ if (filter === 'pan') {+ return {...current, moves, rests, moved: read};+ }+ const previous = pan(moved.slice(0, -1).slice(-3));+ const w = TOUCH_SCROLL_RELEASE_NEWEST_WEIGHT;return {- x: w * current.x + (1 - w) * before.x,- y: w * current.y + (1 - w) * before.y,+ x: w * current.x + (1 - w) * previous.x,+ y: w * current.y + (1 - w) * previous.y,moves,rests,- moved,+ moved: read,};}@@ -397,6 +467,7 @@ function coreRelease(export function readRelease(steps: readonly TouchEventStep[],arrivals: readonly TouchArrival[],+ filter: TouchReleaseFilter = 'pan',): ReleaseReading | null {const lift = steps.length - 1;const id =@@ -420,10 +491,12 @@ export function readRelease(const script = coreRelease(positions.map(p => ({...p, time: steps[p.index].t})),steps[lift].t,+ filter,);const page = coreRelease(positions.map(p => ({...p, time: arrivals[p.index].stamp})),arrivals[lift].stamp,+ filter,);const scriptPxPerS = Math.hypot(script.x, script.y);const first = page.moved[0]?.index ?? positions[0].index;@@ -466,20 +539,41 @@ export function touchPacingFault(steps: readonly TouchEventStep[],arrivals: readonly TouchArrival[],tolerance?: number,+ {+ release = 'pan',+ boundaries = {},+ }: Pick<PlayOptions, 'release' | 'boundaries'> = {},): TouchPacingFault | null {- const reading = readRelease(steps, arrivals);- if (- reading == null ||- !(- reading.rests ||+ const reading = readRelease(steps, arrivals, release);+ const sides = (threshold: number, page: number, script: number) =>+ page >= threshold !== script >= threshold;+ const releaseBound = boundaries.releasePxPerS;+ const crossesRelease =+ reading != null &&+ releaseBound != null &&+ sides(releaseBound, reading.pagePxPerS, reading.scriptPxPerS);+ const hold =+ arrivals.length === steps.length ? readHold(steps, arrivals) : null;+ const crossesHold =+ hold != null &&+ boundaries.holdMs != null &&+ sides(boundaries.holdMs, hold.page, hold.script);+ const releaseFault =+ reading != null &&+ (reading.rests ||reading.throws ||reading.fewMoves ||- (tolerance != null && reading.strayShare > tolerance)- )- ) {+ (tolerance != null && reading.strayShare > tolerance) ||+ crossesRelease);+ if (!releaseFault && !crossesHold) {return null;}- const {span} = reading;+ // The gaps the fault reads: the release's, or for a hold every gap from+ // touch-down to the lift.+ const span =+ releaseFault && reading != null+ ? reading.span+ : Array.from({length: steps.length - 1}, (_, k) => k + 1);const gapsMs = span.map(i => arrivals[i].stamp - arrivals[i - 1].stamp);const scriptedGapsMs = span.map(i => steps[i].t - steps[i - 1].t);let heldByPage: TouchPacingFault['heldByPage'] = null;@@ -499,6 +593,19 @@ export function touchPacingFault(}}});+ if (!releaseFault || reading == null) {+ return {+ kind: 'hold',+ pageReleasePxPerS: reading?.pagePxPerS ?? 0,+ scriptReleasePxPerS: reading?.scriptPxPerS ?? 0,+ gapsMs,+ scriptedGapsMs,+ heldByPage,+ threshold: boundaries.holdMs,+ holdMs: hold ?? undefined,+ };+ }+ const strays = tolerance != null && reading.strayShare > tolerance;return {kind: reading.rests? 'rest'@@ -506,17 +613,58 @@ export function touchPacingFault(? 'throw': reading.fewMoves? 'moves'- : 'release',+ : strays+ ? 'release'+ : 'boundary',pageReleasePxPerS: reading.pagePxPerS,scriptReleasePxPerS: reading.scriptPxPerS,gapsMs,scriptedGapsMs,heldByPage,+ threshold: strays ? undefined : releaseBound,+ };+}++/**+ * The first finger's hold from touch-down to the lift that ends the play, ms.+ * It gives the page's reading and the script's: a tap's hold, or a drag's+ * whole span.+ */+export function readHold(+ steps: readonly TouchEventStep[],+ arrivals: readonly TouchArrival[],+): {readonly page: number; readonly script: number} | null {+ const lift = steps.length - 1;+ if (+ lift < 1 ||+ steps[0].type !== 'touchStart' ||+ steps[lift].type !== 'touchEnd' ||+ arrivals.length !== steps.length+ ) {+ return null;+ }+ return {+ page: arrivals[lift].stamp - arrivals[0].stamp,+ script: steps[lift].t - steps[0].t,};}function describeFault(fault: TouchPacingFault): string {+ const frames =+ fault.frameGapMs == null+ ? ''+ : `; the page drew no frame for ${fault.frameGapMs.toFixed(0)} ms during the gesture`;+ return `${describeReading(fault)}${frames}`;+}++function describeReading(fault: TouchPacingFault): string {const gaps = `gaps ${fault.gapsMs.map(g => g.toFixed(0)).join(', ')} ms where the script spaces ${fault.scriptedGapsMs.map(g => g.toFixed(0)).join(', ')} ms`;+ if (fault.kind === 'hold' && fault.holdMs != null) {+ return `the page read a hold of ${fault.holdMs.page.toFixed(0)} ms where the script holds ${fault.holdMs.script.toFixed(0)} ms, on the other side of the ${fault.threshold} ms the component decides on`;+ }+ if (fault.kind === 'boundary') {+ return `the page read a release of ${fault.pageReleasePxPerS.toFixed(0)} px/s where the script throws ${fault.scriptReleasePxPerS.toFixed(0)} px/s, on the other side of the ${fault.threshold} px/s the component decides on (${gaps})`;+ }if (fault.kind === 'rest') {return `the page read a resting finger: the lift reached it more than ${TOUCH_STILLNESS_MS} ms after the last move (${gaps})`;}@@ -582,11 +730,17 @@ export class TouchLiftStallError extends Error {readonly gapMs: number;/** How long `onEvent` ran in that gap, ms. */readonly onEventMs: number;+ /** As in `TouchPacingFault`: the longest frame gap, ms, or null unread. */+ readonly frameGapMs?: number | null;},) {- const {scriptedGapMs, gapMs, onEventMs} = numbers;+ const {scriptedGapMs, gapMs, onEventMs, frameGapMs} = numbers;+ const frames =+ frameGapMs == null+ ? ''+ : `; the page drew no frame for ${frameGapMs.toFixed(0)} ms during the gesture`;super(- `touchDriver: the lift reached the page ${gapMs.toFixed(0)} ms after its finger's last move, where the script spaces ${scriptedGapMs.toFixed(0)} ms: past the ${TOUCH_STILLNESS_MS} ms stillness interval, the page reads a resting finger. onEvent ran ${onEventMs.toFixed(0)} ms in that gap: page work there holds the next event back. Read the page in a listener of its own, or rest the script before the lift`,+ `touchDriver: the lift reached the page ${gapMs.toFixed(0)} ms after its finger's last move, where the script spaces ${scriptedGapMs.toFixed(0)} ms: past the ${TOUCH_STILLNESS_MS} ms stillness interval, the page reads a resting finger. onEvent ran ${onEventMs.toFixed(0)} ms in that gap: page work there holds the next event back${frames}. Read the page in a listener of its own, or rest the script before the lift`,);this.name = 'TouchLiftStallError';}@@ -630,7 +784,12 @@ export function liftStallError(.slice(lastMoved, lift).reduce((sum, ms) => sum + ms, 0);return scriptedGapMs + ranMs > TOUCH_STILLNESS_MS- ? new TouchLiftStallError({scriptedGapMs, gapMs, onEventMs: ranMs})+ ? new TouchLiftStallError({+ scriptedGapMs,+ gapMs,+ onEventMs: ranMs,+ frameGapMs: fault.frameGapMs,+ }): null;}@@ -656,7 +815,34 @@ export function touchPlayError(/** Records what the page saw of a paced play's touches (WebKit). */interface TouchArrivalProbe {arm(): Promise<void>;- read(): Promise<TouchArrival[]>;+ /** Each touch event's arrival, and when the page drew each frame meanwhile. */+ read(): Promise<{arrivals: TouchArrival[]; frames: number[]}>;+}++/**+ * The longest time the page drew no frame while the gesture reached it, ms.+ * The span runs from the last frame before the first touch to the first+ * frame after the lift. With no such frame, the touch or the lift itself+ * bounds it. Null with no frame read.+ */+export function longestFrameGap(+ frames: readonly number[],+ arrivals: readonly TouchArrival[],+): number | null {+ if (frames.length === 0 || arrivals.length === 0) {+ return null;+ }+ const from = arrivals[0].stamp;+ const to = arrivals[arrivals.length - 1].stamp;+ const sorted = [...frames].sort((a, b) => a - b);+ const before = sorted.filter(t => t <= from).at(-1) ?? from;+ const after = sorted.find(t => t >= to) ?? to;+ const edges = [before, ...sorted.filter(t => t > from && t < to), after];+ let longest = 0;+ for (let i = 1; i < edges.length; i += 1) {+ longest = Math.max(longest, edges[i] - edges[i - 1]);+ }+ return longest;}async function playSteps(@@ -672,6 +858,8 @@ async function playSteps(pacing = 'schedule',releaseTolerance,releaseUnread = false,+ release = 'pan',+ boundaries,} = options;const steps = toTouchEvents(script);// Only where the page reads a velocity from arrival times: scripted@@ -707,7 +895,7 @@ async function playSteps(}// Judged once the lift is out, so no finger is left down.if (judges) {- const arrivals = await probe.read();+ const {arrivals, frames} = await probe.read();// A page that lost events, such as a target removed mid-gesture, gives no// release to read. Only a `'spacing'` play, which asks for the// judgment, fails then.@@ -716,11 +904,15 @@ async function playSteps(`touchDriver: the page received ${arrivals.length} of a paced play's ${steps.length} touch events`,);}- const fault = touchPacingFault(steps, arrivals, releaseTolerance);- if (fault != null) {+ const found = touchPacingFault(steps, arrivals, releaseTolerance, {+ release,+ boundaries,+ });+ if (found != null) {+ const fault = {...found, frameGapMs: longestFrameGap(frames, arrivals)};throw touchPlayError(steps, arrivals, fault, onEventMs);}- const reading = readRelease(steps, arrivals);+ const reading = readRelease(steps, arrivals, release);if (reading != null) {played[played.length - 1] = {...played[played.length - 1],@@ -870,15 +1062,43 @@ export function touchArrivalsFrom(record: {*/function touchArrivalProbe(page: Page): TouchArrivalProbe {let armed: JSHandle<InputRun> | null = null;+ let drawn: JSHandle<{times: number[]; stopped: boolean}> | null = null;return {async arm() {await armed?.evaluate(run => run.stop());await armed?.dispose();+ await drawn?.evaluate(record => {+ record.stopped = true;+ });+ await drawn?.dispose();armed = await armInputRun(page, TOUCH_TYPES);+ // When the page draws each frame, on the clock its events are stamped+ // on. The harness's own frames run on the real timers: a frozen timer+ // gate (story.ts) holds only the page's.+ drawn = await page.evaluateHandle(() => {+ const gate = (+ window as unknown as {+ __harnessTimerGate?: {frame?: typeof requestAnimationFrame};+ }+ ).__harnessTimerGate;+ const frame = gate?.frame ?? window.requestAnimationFrame.bind(window);+ const record = {times: [] as number[], stopped: false};+ // Resolves at the first frame, so a frame before the gesture is read.+ return new Promise<typeof record>(resolve => {+ const tick = (time: number) => {+ if (!record.stopped) {+ record.times.push(time);+ resolve(record);+ frame(tick);+ }+ };+ frame(tick);+ });+ });},async read() {if (armed == null) {- return [];+ return {arrivals: [], frames: []};}const run = armed;armed = null;@@ -892,7 +1112,16 @@ function touchArrivalProbe(page: Page): TouchArrivalProbe {};});await run.dispose();- return touchArrivalsFrom(record);+ const frames =+ drawn == null+ ? []+ : await drawn.evaluate(recorded => {+ recorded.stopped = true;+ return recorded.times.slice();+ });+ await drawn?.dispose();+ drawn = null;+ return {arrivals: touchArrivalsFrom(record), frames};},};}diff --git a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.tsindex 8791a13813..e71a600dc3 100644--- a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts+++ b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts@@ -32,6 +32,7 @@ import {withStorybook,} from '@astryxdesign/interaction-harness';+import {paging} from '../../motion/uikit/paging';import {nearestStop} from '../snapPagingValue';const storybook = withStorybook(test);@@ -139,7 +140,13 @@ async function swipe(const from = {x: box.x + box.width / 2 + (rtl ? -half : half), y};const to = {x: from.x + (rtl ? px : -px), y};const driver = await touchDriver(page);- await driver.play(drag(from, to, {durationMs: ms, restMs}));+ // The paging reads a scrolling surface's release and pages from+ // `advanceSpeed`. A release the page reads on the other side of it from+ // the script fails by name, never as the paging's verdict.+ await driver.play(drag(from, to, {durationMs: ms, restMs}), {+ release: 'scroll',+ boundaries: {releasePxPerS: paging.release.advanceSpeed},+ });}for (const mode of ['paging', 'item'] as const) {diff --git a/packages/core/src/gestures/__tests__/VelocityTracker.harness.test.ts b/packages/core/src/gestures/__tests__/VelocityTracker.harness.test.tsindex 0cd69fd869..119f20d6be 100644--- a/packages/core/src/gestures/__tests__/VelocityTracker.harness.test.ts+++ b/packages/core/src/gestures/__tests__/VelocityTracker.harness.test.ts@@ -4,7 +4,8 @@* @file VelocityTracker.harness.test.ts* @input VelocityTracker and the interaction harness's `readRelease`* @output Checks that the harness reads a paced play's release as this- * tracker does, on the same samples+ * tracker does, on the same samples: a dragged surface's release and a+ * scrolling surface's* @position Testing. The harness copies this tracker's filter because it* cannot import Core's gestures. This test keeps the two equal.*@@ -92,6 +93,16 @@ const GESTURES: Record<string, Gesture> = {],lift: 66,},+ 'a turn after four moves': {+ samples: [+ [100, 50, 0],+ [116, 50, 16],+ [140, 50, 32],+ [150, 50, 48],+ [190, 50, 64],+ ],+ lift: 72,+ },'a single move': {samples: [[100, 50, 0],@@ -111,13 +122,18 @@ const GESTURES: Record<string, Gesture> = {'a lift 1 ms past the stillness interval': PAST_STILLNESS,};-/** The tracker's release speed for the gesture, in px/s. */-function coreSpeed({samples, lift}: Gesture): number {+/**+ * The tracker's release speed for the gesture, in px/s: a dragged surface's,+ * or with `scroll` a scrolling surface's.+ */+function coreSpeed({samples, lift}: Gesture, scroll = false): number {const tracker = new VelocityTracker();for (const [x, y, t] of samples) {tracker.add(x, y, t);}- const velocity = tracker.velocity(lift);+ const velocity = scroll+ ? tracker.scrollVelocity(lift)+ : tracker.velocity(lift);return Math.hypot(velocity.x, velocity.y);}@@ -155,6 +171,18 @@ describe("the interaction harness's copy of the release filter", () => {expect(reading?.scriptPxPerS).toBeCloseTo(core, 6);expect(reading?.pagePxPerS).toBeCloseTo(core, 6);});++ it(`reads ${name} as a scrolling surface's VelocityTracker does`, () => {+ const core = coreSpeed(gesture, true);+ const steps = stepsOf(gesture);+ const reading = readRelease(+ steps,+ steps.map(step => ({stamp: step.t, handledAt: step.t})),+ 'scroll',+ );+ expect(reading?.scriptPxPerS).toBeCloseTo(core, 6);+ expect(reading?.pagePxPerS).toBeCloseTo(core, 6);+ });}it('straddles the stillness reset with its two boundary lifts', () => {