An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a spring retarget committed late starts at its frame (#10607)
Christopher Chedeau3fb73b3d437b
diff --git a/.changeset/motion-retarget-late-frame.md b/.changeset/motion-retarget-late-frame.mdnew file mode 100644index 0000000000..c938d31942--- /dev/null+++ b/.changeset/motion-retarget-late-frame.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Motion: a spring retarget that the browser commits late, behind a busy main thread, now starts at that frame, from where the element is on screen. Before, it kept the clock of the call, so the element jumped to where the new curve had got to: 42 px back in one frame for a retarget behind a 200 ms block. Motion calls made in one callback now share one clock, so the children of a pager line up after a retarget. A retarget made inside a page's own frame or ResizeObserver callback now shows its new curve one frame later.++@vjeuxdiff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex 6905c8e9c3..d2ab0d6ce9 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -278,8 +278,16 @@ a measured, sourced difference exists.simulator, 2026-11-06). A rebase toward the new rest shifts a spring headingthere whole: its curve and target move by the rest's change, and it keeps itsstart time and velocity. On a starved page, the Switch's value change then- shows no step in its frame proofs; any other retarget may still skip ahead by- up to the browser's commit delay.+ shows no step in its frame proofs. A retarget's spring that the browser+ commits late starts at that frame, from the value on screen there, as+ UIKit's added spring begins at its commit (iOS 26.2 simulator, 2026-11-07).+ Late means more than 34 ms after the first call that frame commits; a sooner+ commit keeps the call's clock. It keeps the velocity on screen, or one its+ call hands it, such as a release's. A played curve or a coast that retargets+ keeps the call's clock. Calls made in one callback, such as one event+ listener or one observer callback, share the clock of its first call, so+ several elements line up; a call more than 34 ms after that first call+ starts a new clock.- **FR7 — Exits keep the native counterpart's look.** A touch presentation MUSTplay an exit with the look of its UIKit counterpart's exit, on every touchplatform: a menu shrinks into its trigger, and an alert fades. In a component@@ -1021,6 +1029,11 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 andeach carry an amendment for touch presentations (FR11, FR14, Platformsupport); `design:motion` DR3 and DR5 (draft) are departed from or met asFR4 and FR8 state.+- FR6 gap: a retarget made inside a page's own frame or ResizeObserver+ callback shows its new curve one frame later.+- FR6 gap: under a starved compositor, Chromium can show a frame 40 to 60 ms+ after the main-thread frame that builds it. A retarget then first shows that+ far into its curve: up to 6.5 px on a loaded Switch.- Consumer docs: none until a component ships its touch presentation; eachcomponent documents its own, including the `presentation` value that keepsthe released surface (FR25).@@ -1062,7 +1075,8 @@ Motion that FR45 moves, by component. Each component's record carries its own li| FR5 glide | Browser proof: the animated-layout glide keeps moving through a 700 ms main-thread block, on every frame a compositor control moves | the content after a Collapsible, a TreeList branch and a Table row; verified in Chromium; WebKit by an iOS Simulator spot-check (38/39 frames), not an automated run (evidence gap) | a glide stepped from the main thread freezes || FR6 | Unit and browser tests catching an animation mid-flight and retargeting it | catch at peak velocity; retarget with a new spring; a retarget before the browser reports the call's start | a layout read, a jump, or a lost velocity fails || FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, a catch that loses the on-screen velocity, or a programmatic page change mid-settle that starts from rest fails; a page change during a drag starts from rest |-| FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); unit tests of a retarget on a settle tail and a rebase toward a new rest | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still; a value change mid-slide, whose rebase moves the travel whole | a jump out of a thumb that is still fails; a value change mid-slide shows no step; another retarget's step within the browser's commit delay is the known limit |+| FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); unit tests of a retarget on a settle tail and a rebase toward a new rest | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still; a value change mid-slide, whose rebase moves the travel whole | a jump out of a thumb that is still fails; a value change mid-slide shows no step |+| FR6 late commit | A browser test of a retarget behind a 200 ms block; unit tests of a retarget whose frame comes late | a retarget made in a task, and one made in a frame callback of the page, before a 200 ms block; a frame within 34 ms of the call; a velocity the call hands the spring; a hidden page; two properties, and two animators, before one late frame; retargets on two animators in one callback | a step at the frame that commits a retarget fails; a retarget whose frame comes within 34 ms keeps the call's own clock; a retarget made in a frame callback of the page that shows its new curve in any frame but the next fails; a late frame that drops a handed velocity fails; a hidden page's retarget that never finishes fails; a later call before a late frame that keeps its own clock fails; two animators' retargets in one callback on different clocks fail || FR7, FR8 | Component browser tests and storyboards with and without Reduce Motion | entrance, exit, move; a drag and its lift under Reduce Motion; a tap-, key- and program-started close of a sheet and the Lightbox | a missing exit, any travel, scale or spring under Reduce Motion other than a coast after a throw and its settle at an edge (`design:reduced-motion` DR2), an opacity fade over 200 ms, or a tap-, key- or program-started close of a gesture component on the exit curve instead of its spring, fails || FR45 | Browser tests with a mouse, a pen, a trackpad and a finger at each `tempo` bound and each `character`, and with Reduce Motion | a tap, a click, a key and a programmatic change on a Switch, a menu, an alert, a sheet and a ProgressBar under a fine and a coarse pointer; a drag release, a flick and a pinch on a Switch, a Slider, a sheet, a pager and a Lightbox photo under each pointer; a tap that continues as a drag | a tap, click, key or programmatic change in a tap-classified component that plays a measured role or a spring instead of the theme's duration and easing tokens, a touch tap-started move in a gesture or gesture-capable component on a curve instead of its spring, a click, a key or a value change on Switch or SegmentedControl without a touch presentation that leaves the theme's curve, a velocity-carrying release that settles from rest or on a curve, a gesture's spring that ignores `character` or `tempo`, or a part that follows one pointer and not another, fails; the pager's measured settle, which does not yet follow `character`, is a recorded implementation gap || FR45 | Component source and token tests for a tap component's motion whose record names no step, with a platform measurement | a small anchored surface (a popover, a menu, a toggle, a row) and a full-screen surface (a Dialog, an AlertDialog), each with its own measurement; a tap component's overlay exit | a token cited as nearest to the measurement in the Storybook theme passes, and a tap component's overlay exit on `--duration-exit` passes; a token chosen by role alone, or nearest at Core's unthemed defaults, fails |diff --git a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.tsindex f53b73975e..87ada80af8 100644--- a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts+++ b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts@@ -2211,20 +2211,94 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',const FRAME_60_MS = 1000 / 60;/**- * The lift's turn back of the thumb, page ms. `call` is when it was made,- * and `inLiftTask` whether the lift's own task made it. `commit` is when the- * page's next frame began to run. `release` is when the release's travel- * came, if before that frame. `frames` are its keyframes, `[ms, x px from- * the on side's rest]`.+ * A translate curve of the thumb, page ms. `made` is when it was made,+ * `start` when the browser started it, and `end` when it stopped. `frames`+ * are its keyframes, `[ms, x px from the rest of the side the switch was+ * on]`.*/- interface Retarget {- call: number;- inLiftTask: boolean;- commit: number | null;- release: number | null;+ interface ThumbCurve {+ made: number;+ start: number | null;+ end: number | null;frames: [number, number][];}+ /** The thumb's curves, and when the page saw the second lift, page ms. */+ interface ThumbRecord {+ armed: boolean;+ lift: number | null;+ curves: ThumbCurve[];+ }++ /** A critically damped spring fitted to a curve's keyframes, x in px. */+ interface SpringFit {+ start: number;+ residual: number;+ x(at: number): number;+ v(at: number): number;+ }++ /** A frame that no curve the page made shows at that frame's time. */+ class UnprescribedFrameError extends Error {+ override name = 'UnprescribedFrameError';+ }++ /** A curve's keyframes, `[ms, x]`, at `ms`, as the browser plays them. */+ function keyframeAt(frames: number[][], ms: number): number {+ if (ms <= frames[0][0]) {+ return frames[0][1];+ }+ for (let i = 1; i < frames.length; i++) {+ const [[m0, x0], [m1, x1]] = [frames[i - 1], frames[i]];+ if (ms <= m1) {+ return m1 > m0 ? x0 + ((x1 - x0) * (ms - m0)) / (m1 - m0) : x1;+ }+ }+ return frames[frames.length - 1][1];+ }++ /**+ * Fits `spring` (critically damped) toward `target` to `frames`, timed from+ * `start`, page ms. x − target = (a + b·t)·e^(−ωt) is linear in a and b.+ */+ function fitSpring(+ frames: number[][],+ spring: {response: number},+ target: number,+ start: number,+ ): SpringFit {+ const omega = (2 * Math.PI) / spring.response;+ let [s11, s12, s22, y1, y2] = [0, 0, 0, 0, 0];+ for (const [ms, x] of frames) {+ const t = ms / 1000;+ const e = Math.exp(-omega * t);+ s11 += e * e;+ s12 += t * e * e;+ s22 += t * t * e * e;+ y1 += e * (x - target);+ y2 += t * e * (x - target);+ }+ const det = s11 * s22 - s12 * s12;+ const a = (y1 * s22 - y2 * s12) / det;+ const b = (s11 * y2 - s12 * y1) / det;+ const x = (at: number) => {+ const t = Math.max(0, at - start) / 1000;+ return target + (a + b * t) * Math.exp(-omega * t);+ };+ const v = (at: number) => {+ const t = Math.max(0, at - start) / 1000;+ return (b - omega * (a + b * t)) * Math.exp(-omega * t);+ };+ return {+ start,+ x,+ v,+ residual: Math.max(+ ...frames.map(([ms, value]) => Math.abs(x(start + ms) - value)),+ ),+ };+ }+/** How long after the thaw the page handles the second lift, ms. */const LATE_LIFT_MS = 100;/**@@ -2329,7 +2403,7 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',);}- test("P14 · a second tap whose lift the page handles 100 ms after the thaw turns the thumb back on its tracking spring; only the frame that shows a late commit may skip, by the curves' gap (spec:AST-094 FR6)", async ({+ test('P14 · a second tap whose lift the page handles 100 ms after the thaw turns the thumb back from where the screen stands, and every frame shows a curve the page made (spec:AST-094 FR6)', async ({page,browserName,}) => {@@ -2337,58 +2411,63 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',browserName !== 'chromium','screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',);- // The page notes the lift's turn back: the thumb's first translate- // curve after the second lift. It notes whether the lift's own task made- // it, when the page's next frame began to run, and the curve's keyframes.- // Until that frame commits it, the screen keeps the travel it replaces- // (spec:AST-094 FR6).+ // The page notes every translate curve of the thumb: when it was made,+ // when the browser started it, and its keyframes. It notes the second+ // lift too. The marks use the page's clocks from before the freeze and the+ // timer gate replaced them, so they read real time from `origin`.await page.addInitScript(() => {const animate = Element.prototype.animate;+ const startTime = Object.getOwnPropertyDescriptor(+ Animation.prototype,+ 'startTime',+ );+ const startOf = startTime?.get;+ // A start the page sets is noted when it is set: a curve can end before+ // a later frame reads it.+ const recorded = new WeakMap<Animation, ThumbCurve>();+ if (startTime?.get != null && startTime.set != null) {+ const {get, set} = startTime;+ Object.defineProperty(Animation.prototype, 'startTime', {+ configurable: true,+ get(this: Animation): number | null {+ return get.call(this) as number | null;+ },+ set(this: Animation, value: number | null) {+ set.call(this, value);+ const curve = recorded.get(this);+ if (curve != null && value != null) {+ curve.start = value;+ }+ },+ });+ }const now = performance.now.bind(performance);const frame = requestAnimationFrame.bind(window);- const later = setTimeout.bind(window);- const w = window as unknown as {__retarget?: Retarget | null};- let lifted = false;- let liftTask = false;+ const w = window as unknown as {__thumb?: ThumbRecord};+ const record: ThumbRecord = {armed: false, lift: null, curves: []};+ w.__thumb = record;const onLift = () => {- if (w.__retarget !== null || liftTask) {- return;+ if (record.armed && record.lift == null) {+ record.lift = now();}- lifted = true;- liftTask = true;- // A task queued here runs once the lift's own task ends.- later(() => {- liftTask = false;- }, 0);};addEventListener('pointerup', onLift, {capture: true, passive: true});addEventListener('touchend', onLift, {capture: true, passive: true});Element.prototype.animate = function (keyframes, options) {const animation = animate.call(this, keyframes, options);if (- !lifted ||!this.classList.contains('astryx-switch-thumb') ||!Array.isArray(keyframes) ||!keyframes.some(k => 'translate' in k)) {return animation;}- const turned = w.__retarget;- if (turned != null) {- // The release's travel, if it comes before the frame that commits- // the turn back.- if (turned.commit == null && turned.release == null) {- turned.release = now();- }- return animation;- }const effect = animation.effect as KeyframeEffect;const duration = Number(effect.getTiming().duration);- const retarget: Retarget = {- call: now(),- inLiftTask: liftTask,- commit: null,- release: null,+ const curve: ThumbCurve = {+ made: now(),+ start: null,+ end: null,frames: effect.getKeyframes().map(k => [@@ -2396,10 +2475,32 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',Number.parseFloat(String(k.translate)),]),};- w.__retarget = retarget;- frame(() => {- retarget.commit = now();- });+ record.curves.push(curve);+ recorded.set(animation, curve);+ const readStart = (left: number) =>+ frame(() => {+ const at = startOf?.call(animation);+ if (at != null) {+ curve.start = Number(at);+ } else if (left > 0) {+ readStart(left - 1);+ }+ });+ readStart(60);+ animation.ready.then(+ () => {+ const at = startOf?.call(animation);+ if (at != null) {+ curve.start ??= Number(at);+ }+ },+ () => {},+ );+ const ended = () => {+ curve.end ??= now();+ };+ animation.addEventListener('cancel', ended);+ animation.addEventListener('finish', ended);return animation;};});@@ -2431,7 +2532,10 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',const second = await driver.press(center);const hold = await holdInputUntil(page, {afterResumeMs: LATE_LIFT_MS});await page.evaluate(() => {- (window as unknown as {__retarget?: Retarget | null}).__retarget = null;+ const record = (window as unknown as {__thumb?: ThumbRecord}).__thumb;+ if (record != null) {+ record.armed = true;+ }});const beforeThaw = Date.now();await thawPage(page);@@ -2502,132 +2606,162 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',where: frame => frame.t >= movedAt - FRAME_60_MS,},);- // The lift is a drag step of its own. It turns the running travel back:- // a retarget, on the model's clock (spec:AST-094 FR6).- const retarget = await page.evaluate(- () => (window as unknown as {__retarget?: Retarget | null}).__retarget,+ // A retarget starts at the frame that commits it, from the value on+ // screen there (spec:AST-094 FR6). The proof reads the curves the page+ // made and checks every presented frame against them.+ const thumbRecord = await page.evaluate(+ () => (window as unknown as {__thumb?: ThumbRecord}).__thumb,);- if (retarget?.commit == null) {- throw new Error('the late lift sent the travel back on no new curve');+ if (thumbRecord?.lift == null) {+ throw new Error('the page saw no second lift');}- // Any delay to the commit is then the browser's, which the record allows.- expect(- retarget.inLiftTask,- 'the lift turns the thumb back in the task that handles it',- ).toBe(true);- // The page took its marks with its clocks from before the freeze and the- // timer gate. So they read real time from `origin`. The turn back comes- // after the held lift, in its task. A mark on the frozen page clock reads- // the frozen span earlier.- const madeAt = origin + retarget.call;+ const liftMark = thumbRecord.lift;+ const travelCurve = thumbRecord.curves+ .filter(curve => curve.made < liftMark && curve.start != null)+ .at(-1);+ if (travelCurve?.start == null) {+ throw new Error('the travel has no started curve');+ }+ const after = thumbRecord.curves.filter(curve => curve.made >= liftMark);+ // The page's marks come after the held lift on the real clock. A mark on+ // the frozen page clock reads the frozen span earlier.expect(- madeAt,- 'the turn back comes after the held lift on the real clock',+ origin + (after[0]?.made ?? Number.POSITIVE_INFINITY),+ 'the first curve after the lift comes after the held lift on the real clock',).toBeGreaterThan(liftAt - CLOCK_SKEW_MS);- // The curves the record prescribes, x in px from the on side's rest. The- // travel plays TRAVEL from the off side's rest. The lift is a drag step of- // its own: it turns the thumb back on TRACKING, from where it stood, at- // the travel's speed there.- const travelX = (s: number) =>- -TRAVEL_PX * (1 - springStep(TRAVEL, s * 1000));- const speedAt = (x: (s: number) => number, s: number) =>- (x(s + 0.0005) - x(s - 0.0005)) / 0.001;- const towardOff =- (spring: typeof TRAVEL, from: number, speed: number) => (s: number) =>- from +- (-TRAVEL_PX - from) *- springStep(- {...spring, initialVelocity: speed / (-TRAVEL_PX - from)},- s * 1000,- );- const turnsFrom = retarget.frames[0][1];- let [early, late] = [0, 2];- for (let i = 0; i < 50; i++) {- const mid = (early + late) / 2;- if (travelX(mid) < turnsFrom) {- early = mid;- } else {- late = mid;- }+ const liftPage = liftAt - origin;+ // A curve read from the rest of the side the switch was on, x px from the+ // on side's rest at `at`, page ms. Before its start it shows its first+ // keyframe.+ interface ShownCurve {+ start: number;+ end: number | null;+ x(at: number): number;}- const turn = towardOff(TRACKING, turnsFrom, speedAt(travelX, late));- const strays = Math.max(- ...retarget.frames.map(([ms, x]) => Math.abs(x - turn(ms / 1000))),+ const asShown = (+ curve: ThumbCurve,+ startsAt: number,+ shift: number,+ ): ShownCurve => {+ const frames = curve.frames.map(([ms, x]) => [ms, x + shift]);+ return {+ start: startsAt,+ end: curve.end,+ x: at => keyframeAt(frames, at - startsAt),+ };+ };+ const travelShift =+ Math.abs(+ travelCurve.frames[travelCurve.frames.length - 1][1] - TRAVEL_PX,+ ) < 0.5+ ? -TRAVEL_PX+ : 0;+ const travelFit = fitSpring(+ travelCurve.frames+ .filter(([ms]) => ms < 2000)+ .map(([ms, x]) => [ms, x + travelShift]),+ TRAVEL,+ 0,+ travelCurve.start,);- expect(- strays,- 'the lift turns the thumb back on the tracking spring, from where it stood, at its speed',- ).toBeLessThan(0.5);- // steps[i] is the step into samples[i + 1]. Until the commit, the screen- // shows the travel. The frame that shows the commit is the first, from- // one frame before the page's, that falls more than 1 px behind it. A- // starved compositor can show it some frames late. The commit lands no- // later than that frame.- const commitAt = origin + retarget.commit;- const steps = frameSteps(samples);- const shows =- samples.findIndex(- ([t, x]) =>- t >= commitAt - FRAME_60_MS &&- x - rest < TRAVEL_PX + travelX(late + (t - madeAt) / 1000) - 1,- ) - 1;- const shownAt = shows >= 0 ? samples[shows + 1][0] : commitAt;- const delay = (shownAt - madeAt) / 1000;- const travelAtCommit = travelX(late + delay);- // The commit shows the newest curve made before it. When the browser's- // click comes first, the release's travel replaces the turn back. It plays- // TRAVEL toward the off side's rest, from the turn back's place and speed.- let shownAtCommit = turn(delay);- if (retarget.release != null) {- const released = (retarget.release - retarget.call) / 1000;- shownAtCommit = towardOff(- TRAVEL,- turn(released),- speedAt(turn, released),- )(delay - released);+ expect(travelFit.residual, 'the travel plays TRAVEL').toBeLessThan(0.5);+ // The curves the browser started after the lift, in the order they were+ // made. A curve read from the other side's rest takes the reading that+ // meets the curve before it.+ const sequence: ShownCurve[] = [+ asShown(travelCurve, travelCurve.start, travelShift),+ ];+ const turns: {curve: ThumbCurve; shift: number}[] = [];+ for (const curve of after) {+ if (curve.start == null) {+ continue;+ }+ const startsAt = curve.start;+ const before = sequence[sequence.length - 1];+ const shift = [0, -TRAVEL_PX].reduce((a, b) =>+ Math.abs(curve.frames[0][1] + b - before.x(startsAt)) <+ Math.abs(curve.frames[0][1] + a - before.x(startsAt))+ ? b+ : a,+ );+ expect(+ startsAt,+ 'a curve after the lift starts after the held lift',+ ).toBeGreaterThan(liftPage - CLOCK_SKEW_MS);+ sequence.push(asShown(curve, startsAt, shift));+ turns.push({curve, shift});}- // How far apart the two curves are when the screen shows the commit.- const apartPx = Math.abs(travelAtCommit - shownAtCommit);- // The farthest the turn back can carry the thumb: from where the travel- // stood at the commit, at its speed there.- const carry = towardOff(- TRACKING,- travelAtCommit,- speedAt(travelX, late + delay),- );- let reachPx = travelAtCommit;- for (let t = 0; t < 1; t += 0.001) {- reachPx = Math.max(reachPx, carry(t));+ if (turns.length === 0) {+ throw new Error('the late lift sent the travel back on no new curve');+ }+ // Each presented frame shows the newest curve the compositor has, at the+ // frame's own time. That is the travel, a curve started after the lift,+ // or the off side's rest after the last one ends. The curves replace one+ // another only in order.+ const lastEnd = sequence[sequence.length - 1].end;+ const showsAt: number[] = [];+ let index = 0;+ for (const [t, x] of samples) {+ const at = t - origin;+ const onX = x - rest - TRAVEL_PX;+ const valueOf = (i: number) =>+ i < sequence.length ? sequence[i].x(at) : -TRAVEL_PX;+ const candidates = [...Array(sequence.length + 1).keys()].filter(+ i =>+ i >= index &&+ (i === 0 ||+ (i === sequence.length+ ? lastEnd != null && at >= lastEnd - FRAME_60_MS+ : sequence[i].start <= at + 1)),+ );+ const match = candidates.find(i => Math.abs(valueOf(i) - onX) <= 1);+ if (match == null) {+ throw new UnprescribedFrameError(+ `the frame at ${at.toFixed(1)} ms shows ${onX} px, which no curve the page made shows then: ${candidates.map(i => valueOf(i).toFixed(2)).join(', ')} px`,+ );+ }+ index = match;+ showsAt.push(match);+ }+ // Each turn back that the frames show starts within 1 px of the newest+ // curve the browser started before it. It plays TRACKING or TRAVEL, to+ // the off side.+ for (let i = 1; i < sequence.length; i++) {+ if (!showsAt.includes(i)) {+ continue;+ }+ expect(+ Math.abs(+ sequence[i].x(sequence[i].start) -+ sequence[i - 1].x(sequence[i].start),+ ),+ 'a turn back starts where the screen stood',+ ).toBeLessThanOrEqual(1);+ const {curve, shift} = turns[i - 1];+ const frames = curve.frames+ .filter(([ms]) => ms < 2000)+ .map(([ms, x]) => [ms, x + shift]);+ expect(+ Math.abs(frames[frames.length - 1][1] + TRAVEL_PX),+ 'a curve after the lift turns the thumb back to the off side',+ ).toBeLessThan(0.5);+ const residual = Math.min(+ ...[TRACKING, TRAVEL].map(+ spring =>+ fitSpring(frames, spring, -TRAVEL_PX, sequence[i].start).residual,+ ),+ );+ expect(residual, 'the turn back plays TRACKING or TRAVEL').toBeLessThan(+ 0.5,+ );}- // A commit that lands late shows the turn back that far in. So the frame- // that shows it may step by how far apart the two curves are then, plus- // 4 px. Every other frame moves the thumb less than 4 px from the one- // before, on the compositor's clock.const farthest = Math.max(...samples.map(([, x]) => x)) - rest;- const reach = TRAVEL_PX + reachPx;test.info().annotations.push({- type: 'late retarget',- description: `committed ${(retarget.commit - retarget.call).toFixed(1)} ms after its call, shown ${(delay * 1000).toFixed(1)} ms after it${retarget.release == null ? '' : `, released ${(retarget.release - retarget.call).toFixed(1)} ms after it`}; both curves ${apartPx.toFixed(2)} px apart; the frame that shows it steps ${shows < 0 ? 'none' : steps[shows].toFixed(2)} px; the thumb reached ${farthest} px of ${reach.toFixed(2)} px`,+ type: 'turn back',+ description: `${turns.length} curve(s) started after the lift; the thumb reached ${farthest} px; the largest frame step ${Math.max(...frameSteps(samples)).toFixed(2)} px`,});- expect(- Math.max(...steps.filter((_, i) => i !== shows)),- JSON.stringify(samples),- ).toBeLessThan(4);- if (shows >= 0) {- expect(- steps[shows],- `the frame that shows the turn back, ${(delay * 1000).toFixed(1)} ms after its call, both curves ${apartPx.toFixed(2)} px apart: ${JSON.stringify(samples)}`,- ).toBeLessThan(apartPx + 4);- }- // It turned around mid-travel. The screen keeps the travel until the- // retarget commits, and then turns back (spec:AST-094 FR6). The thumb- // never shows past the farthest a turn back carries it. The frames read x- // from the off side's rest, TRAVEL_PX before the on side's.+ // It turned around mid-travel.expect(farthest).toBeGreaterThan(1);- expect(- farthest,- `the thumb reached ${farthest} px; a turn back at the commit reaches ${reach.toFixed(2)} px`,- ).toBeLessThanOrEqual(reach + 1);});test('a tap whose first frame the page commits late (its main thread busy for 100 ms after the lift) starts the travel from rest on that frame, not partway into its curve', async ({diff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.tsindex 6b8209e1b4..0810f44360 100644--- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts@@ -430,10 +430,21 @@ test('a frame painted before the compositor has the curve shows the element wherconst onScreen = retarget.animator.get('x');retarget.animator.animate({x: 0}, {spring: Motion.springs.settle});frozen = null;+ // The frame that commits the retarget builds its curve: drop it there.+ // A busy page can make that frame late. The curve then starts at it,+ // from the screen, so the inline value is where the curve starts.+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ const [built] = retarget.element.getAnimations();+ const startsAt = retarget.animator.get(+ 'x',+ Number(built?.startTime ?? Number.NaN),+ );for (const animation of retarget.element.getAnimations()) {animation.cancel();}- return {presentX, onScreen, retargetX: x(retarget.element)};+ return {presentX, onScreen, startsAt, retargetX: x(retarget.element)};},{travel: TRAVEL},);@@ -444,7 +455,7 @@ test('a frame painted before the compositor has the curve shows the element wherexpect(result.presentX).toBeCloseTo(0, 1);expect(result.onScreen).toBeGreaterThan(20);// The inline value is written to a thousandth of a pixel.- expect(result.retargetX).toBeCloseTo(result.onScreen, 2);+ expect(result.retargetX).toBeCloseTo(result.startsAt, 2);});test('under Reduce Motion, a dip a busy main thread lands late still ends within its 200 ms cross-fade', async ({@@ -822,6 +833,170 @@ for (const how of ['from a page frame callback', 'presented'] as const) {});}+for (const how of ['in a task', 'in a frame callback of the page'] as const) {+ test(`a retarget made ${how}, whose next frame a 200 ms block delays, starts at that frame, from the value and the velocity on screen there (spec:AST-094 FR6)`, async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'screencast frame evidence is Chromium-only in Playwright',+ );+ await open(page);+ const box = page.locator('#box');+ await markElement(box, {inset: MARKER_INSET});+ const {start: controlStart} = await startBusyControl(page);+ const {start: secondStart} = await startBusyControl(page, {ahead: true});+ const cast = await startScreencast(page);+ const out = {response: 1.2, dampingRatio: 1};+ // The call comes 250 ms into the first curve, and the page then stays+ // busy for 200 ms. A call in a task is committed by the frame after that+ // block. A call in a frame callback waits for the frame after that block+ // too: the frame it runs in shows the first curve.+ const run = await page.evaluate(+ async ({spring, back, travel, inFrame}) => {+ const handle = window.animator.animate({x: travel}, {spring});+ const started = await handle.started;+ await new Promise(resolve =>+ setTimeout(resolve, Math.max(0, started + 250 - performance.now())),+ );+ return new Promise<{start: number; call: number; end: number}>(+ resolve => {+ let call = 0;+ const block = () => {+ const from = performance.now();+ while (performance.now() < from + 200) {+ // the page's main thread is busy+ }+ resolve({+ start: performance.timeOrigin + started,+ call: performance.timeOrigin + call,+ end: performance.timeOrigin + performance.now(),+ });+ };+ if (inFrame) {+ requestAnimationFrame(() => {+ call = performance.now();+ window.animator.animate({x: 0}, {spring: back});+ setTimeout(block, 0);+ });+ } else {+ setTimeout(() => {+ call = performance.now();+ window.animator.animate({x: 0}, {spring: back});+ block();+ }, 0);+ }+ },+ );+ },+ {+ spring: out,+ back: SLOW,+ travel: TRAVEL,+ inFrame: how === 'in a frame callback of the page',+ },+ );+ await page.waitForTimeout(400);+ const frames = await cast.stop();+ const tracked = await trackMarker(page, frames);+ const control = await trackMarker(page, frames, {rgb: CONTROL_RGB});+ const second = await trackControl(page, frames, {ahead: true});+ // Each frame on the page clock, read from the two controls, as in the 1 s+ // block above.+ const clocks = [+ {clock: controlClock(control), origin: controlStart},+ {clock: controlClock(second), origin: secondStart},+ ];+ const timed = tracked.flatMap(f => {+ const reader = clocks.find(({clock}) => clock.has(f.t));+ if (f.box == null || reader == null) {+ return [];+ }+ const ms = reader.clock.get(f.t) ?? NaN;+ const cycles = Math.round((f.t - reader.origin - ms) / 800);+ const at = reader.origin + ms + cycles * 800;+ return at >= run.call - 50 && at <= run.end + 150+ ? [{x: f.box.x - MARKER_INSET, at}]+ : [];+ });+ // The frames fit the first curve up to a start at or after the block's+ // end. After that start, they fit a spring from the value and the velocity+ // on screen there. `skip` fits the same frames to the call's own clock+ // instead.+ const fit = await page.evaluate(+ ({spring, back, travel, times, frames: judged}) => {+ const first = Motion.solveSpring(Motion.toSpring(spring), {+ from: 0,+ to: travel,+ });+ const firstAt = (at: number) => first.value((at - times.start) / 1000);+ const firstVelocity = (at: number) =>+ first.velocity((at - times.start) / 1000);+ const from = (at: number) =>+ Motion.solveSpring(Motion.toSpring(back), {+ from: firstAt(at),+ to: 0,+ velocity: firstVelocity(at),+ });+ const worstFor = (curve: (at: number) => number) =>+ Math.max(...judged.map(({x, at}) => Math.abs(x - curve(at))));+ // The best switch from the first curve to `next(commit)`, at or after+ // the block's end.+ const bestFit = (+ next: (commit: number) => (elapsedMs: number) => number,+ ) => {+ let best = {commit: NaN, worst: Infinity};+ for (let commit = times.end; commit <= times.end + 60; commit += 1) {+ const curve = next(commit);+ const worst = worstFor(at =>+ at < commit ? firstAt(at) : curve(at - commit),+ );+ if (worst < best.worst) {+ best = {commit, worst};+ }+ }+ return best;+ };+ const fromScreen = bestFit(commit => {+ const next = from(commit);+ return elapsed => next.value(elapsed / 1000);+ });+ const ownClock = from(times.call);+ const onOwnClock = bestFit(+ commit => elapsed =>+ ownClock.value((elapsed + commit - times.call) / 1000),+ );+ return {+ commitAfterBlock: fromScreen.commit - times.end,+ worst: fromScreen.worst,+ skip: onOwnClock.worst,+ };+ },+ {spring: out, back: SLOW, travel: TRAVEL, times: run, frames: timed},+ );+ const read = {+ ...fit,+ inBlock: timed.filter(({at}) => at > run.call && at < run.end).length,+ after: timed.filter(({at}) => at > run.end + 20).length,+ };+ test.info().annotations.push({+ type: 'a retarget behind a 200 ms block (px, ms)',+ description: JSON.stringify({read, timed}),+ });+ // The compositor showed the first curve through the block, and the frames+ // after it show the call.+ expect(read.inBlock, JSON.stringify(read)).toBeGreaterThanOrEqual(3);+ expect(read.after, JSON.stringify(read)).toBeGreaterThanOrEqual(3);+ // Within 4 px everywhere: the marker and the controls are read at whole+ // px, so each read adds up to a px.+ expect(read.worst, JSON.stringify(read)).toBeLessThanOrEqual(4);+ // The call's own clock misses the same frames by far more, so the case+ // tells the two apart.+ expect(read.skip, JSON.stringify(read)).toBeGreaterThan(20);+ });+}+test('no Layout or Paint runs while it animates', async ({page,browserName,diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex 33ec8e26e9..406d4aa75d 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -22,6 +22,7 @@ import {createMotionEngine,END_HOLD_MS,PROMOTION_LINGER_MS,+ type Animator,type AnimatorOptions,} from './animator';import {cubicBezier} from './bezier';@@ -398,6 +399,8 @@ describe('animate: keyframes on the compositor', () => {{x: 0, scale: 1, rotate: 0},{spring: springs.quickChange},);+ // The frame that commits the call builds its animations.+ await commitFrame(clock);// While the motion back runs, the inline value is where it starts.expect(live('translate')).toHaveLength(1);expect(parse(element.style.translate)[0]).toBeCloseTo(animator.get('x'), 2);@@ -724,6 +727,7 @@ describe('a call from rest starts at the commit, as Core Animation does', () =>await commitFrame(1000);clock = 1100;animator.animate({x: 0}, {spring: springs.settle});+ await commitFrame(1100);expect((live('translate').at(-1) as Recorded).startTime).toBe(1100);});@@ -900,6 +904,7 @@ describe('a call from rest starts at the commit, as Core Animation does', () =>// 100 ms into the curve on screen; the page still has no start to read.clock = 1116;animator.animate({x: 400}, {spring: springs.settle});+ await commitFrame(1116, {startUnread: true});const retarget = live('translate').at(-1) as Recorded;expect(retarget.startTime).toBe(1116);expect(sampleAt(retarget, 'translate', 1116)[0]).toBeCloseTo(@@ -1385,6 +1390,7 @@ describe('a call from rest starts at the commit, as Core Animation does', () =>await advance(100);await expect(first.started).resolves.toBe(1000);const second = animator.animate({x: 0}, {spring: springs.settle});+ await commitFrame(1100);expect(live('translate')[0].startTime).toBe(1100);await expect(second.started).resolves.toBe(1100);});@@ -1459,6 +1465,8 @@ describe('review fixes', () => {for (let i = 1; i <= 10; i++) {clock = 1000 + (i * 1000) / 120;animator.animate({x: -12 * i}, {spring: tracking});+ // Each move is its own task.+ await Promise.resolve();}// Nothing has moved on screen, but the model is moving with the finger.expect(animator.get('x')).toBe(0);@@ -1482,6 +1490,8 @@ describe('review fixes', () => {for (let i = 1; i <= 6; i++) {clock = 1000 + (i * 1000) / 60;animator.animate({x: -20 * i}, {spring: tracking});+ // Each move is its own task.+ await Promise.resolve();}const velocity = animator.getVelocity('x');expect(velocity).toBeLessThan(0);@@ -1970,6 +1980,7 @@ describe('start: when a call\u2019s animations start', () => {// The element is moving, not at rest: no two frames on the old curve and// no restart at the commit from the call's value. The new curve starts at// the call, from what is on screen, as a retarget does.+ await commitFrame(1100);const [animation] = live('translate');expect(animation.startTime).toBe(1100);expect(animator.get('x', 1100)).toBeCloseTo(from, 6);@@ -2052,6 +2063,7 @@ describe('animatorFor: one animator per element', () => {const x = solveSpring(toSpring(springs.settle), {from: 0, to: -120});const removal = animatorFor(row, options);removal.animate({y: -44}, {spring: springs.settle});+ await commitFrame(clock);const tracks = live('translate');expect(tracks).toHaveLength(1);// x stays on its curve; y starts its own.@@ -2275,6 +2287,7 @@ describe('atRest: waiting out every curve', () => {await advance(100);// Someone else retargets the row: the wait follows the new curve.const second = animator.animate({y: 0}, {spring: springs.settle});+ await commitFrame(clock);const [track] = live('translate');const end = Number(track.options.duration) - END_HOLD_MS;await advance(end - 1);@@ -2310,6 +2323,9 @@ describe('presentation values, retargeting, velocity (spec:AST-094 FR6)', () =>const value = animator.get('x');const velocity = animator.getVelocity('x');animator.animate({x: -100}, {spring: springs.emphasis});+ // The frame that commits the call replaces the animation.+ expect(first.cancelled).toBe(false);+ await commitFrame(clock);expect(first.cancelled).toBe(true);const second = live('translate')[0];expect(second.startTime).toBe(clock);@@ -2325,6 +2341,516 @@ describe('presentation values, retargeting, velocity (spec:AST-094 FR6)', () =>expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 9);});+ describe('a spring retarget committed late starts at its frame', () => {+ // The first curve, as the screen shows it from its start at 1000.+ const old = solveSpring(toSpring(springs.emphasis), {+ from: 0,+ to: 300,+ velocity: 800,+ });+ const shownAt = (time: number) => old.value((time - 1000) / 1000);+ const shownVelocityAt = (time: number) =>+ old.velocity((time - 1000) / 1000);++ async function moving() {+ const setUp = setup();+ setUp.animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ await advance(120);+ return setUp;+ }++ it('a retarget whose frame comes late starts there, from the value and the velocity on screen', async () => {+ const {animator} = await moving();+ animator.animate({x: -100}, {spring: springs.emphasis});+ // A main-thread block: the frame that commits the call comes 200 ms+ // later, and the screen shows the first curve until then.+ clock += 200;+ await commitFrame(clock);+ const [animation] = live('translate');+ expect(animation.startTime).toBe(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ expect(sampleAt(animation, 'translate', clock)[0]).toBeCloseTo(+ shownAt(clock),+ 2,+ );+ const curve = solveSpring(toSpring(springs.emphasis), {+ from: shownAt(clock),+ to: -100,+ velocity: shownVelocityAt(clock),+ });+ expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);+ });++ it('a retarget whose frame comes on time keeps its own clock', async () => {+ const {animator} = await moving();+ const call = clock;+ const [old] = live('translate');+ animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 30;+ await commitFrame(clock);+ const [made] = live('translate');+ expect(made).not.toBe(old);+ expect(made.startTime).toBe(call);+ const curve = solveSpring(toSpring(springs.emphasis), {+ from: shownAt(call),+ to: -100,+ velocity: shownVelocityAt(call),+ });+ expect(animator.get('x', clock + 90)).toBeCloseTo(+ curve.value((clock + 90 - call) / 1000),+ 6,+ );+ });++ it('calls before a late frame start there from the curve that the screen still shows', async () => {+ const {animator} = await moving();+ animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 10;+ animator.animate({x: 40}, {spring: springs.settle});+ clock += 190;+ await commitFrame(clock);+ const curve = solveSpring(toSpring(springs.settle), {+ from: shownAt(clock),+ to: 40,+ velocity: shownVelocityAt(clock),+ });+ expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);+ });++ it('a rebase before the late frame moves the place on screen with the element', async () => {+ const {animator} = await moving();+ animator.animate({x: -100}, {spring: springs.emphasis});+ animator.rebase({x: -40});+ clock += 200;+ await commitFrame(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock) - 40, 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ });++ it('an additive retarget whose frame comes late adds to the curve on screen from there', async () => {+ const {animator} = await moving();+ animator.animate({x: -100}, {spring: springs.settle}, {additive: true});+ clock += 200;+ await commitFrame(clock);+ expect(live('translate')[0].startTime).toBe(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ const difference = solveSpring(toSpring(springs.settle), {+ from: 0,+ to: -400,+ });+ // The first curve keeps its own spring: one spring from the screen's+ // value and velocity would be elsewhere.+ const replaced = solveSpring(toSpring(springs.settle), {+ from: shownAt(clock),+ to: -100,+ velocity: shownVelocityAt(clock),+ });+ let apart = 0;+ for (let ms = 50; ms <= 600; ms += 50) {+ const added = shownAt(clock + ms) + difference.value(ms / 1000);+ expect(animator.get('x', clock + ms)).toBeCloseTo(added, 6);+ apart = Math.max(apart, Math.abs(added - replaced.value(ms / 1000)));+ }+ expect(apart).toBeGreaterThan(1);+ });++ it('stop() before a late frame freezes where the screen shows', async () => {+ const {animator, element} = await moving();+ animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 200;+ animator.stop();+ expect(inlineX(element)).toBeCloseTo(shownAt(clock), 3);+ expect(animator.get('x')).toBeCloseTo(shownAt(clock), 6);+ });++ it('a retarget that starts at its late frame finishes at the end of that curve', async () => {+ const {animator} = await moving();+ const handle = animator.animate({x: 250}, {spring: springs.quickChange});+ let finished: boolean | null = null;+ void handle.finished.then(value => {+ finished = value;+ });+ // The block outlasts the call's own curve, so its timers come due in it.+ const own = (handle.curve('x')?.duration ?? 0) * 1000;+ clock += own + 50;+ await vi.advanceTimersByTimeAsync(own + 50);+ expect(finished).toBe(null);+ await commitFrame(clock);+ const left = Number(live('translate')[0].options.duration) - END_HOLD_MS;+ await advance(left - 20);+ expect(finished).toBe(null);+ await advance(40);+ expect(finished).toBe(true);+ });++ it('a played curve keeps its own clock when its frame comes late', async () => {+ const {animator} = await moving();+ const call = clock;+ animator.play({+ x: {duration: 0.3, at: t => 100 * t, velocity: () => 100},+ });+ clock += 200;+ await commitFrame(clock);+ expect(live('translate')[0].startTime).toBe(call);+ });++ it('a second property\u2019s retarget before the same late frame starts there too', async () => {+ const {animator} = setup();+ animator.animate(+ {x: 300, y: 300},+ {spring: springs.emphasis, velocity: {x: 800, y: 800}},+ );+ await advance(120);+ animator.animate({x: -100}, {spring: springs.emphasis});+ // Another task, 20 ms later, before the frame that commits both.+ await Promise.resolve();+ clock += 20;+ animator.animate({y: -100}, {spring: springs.emphasis});+ // That frame comes 45 ms after the first call it commits: late.+ clock += 25;+ await commitFrame(clock);+ for (const property of ['x', 'y'] as const) {+ expect(animator.get(property, clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity(property, clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ }+ const curve = solveSpring(toSpring(springs.emphasis), {+ from: shownAt(clock),+ to: -100,+ velocity: shownVelocityAt(clock),+ });+ expect(animator.get('y', clock + 90)).toBeCloseTo(curve.value(0.09), 6);+ });++ it('a late frame judges every animator from the first call it commits', async () => {+ const now = () => clock;+ const first = setup({now});+ const second = setup({now});+ for (const {animator} of [first, second]) {+ animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ }+ await advance(120);+ first.animator.animate({x: -100}, {spring: springs.emphasis});+ await Promise.resolve();+ clock += 20;+ second.animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 25;+ await commitFrame(clock);+ expect(live('translate').map(animation => animation.startTime)).toEqual([+ clock,+ clock,+ ]);+ for (const {animator} of [first, second]) {+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ }+ });++ it('retargets made in one callback on several animators share one clock', async () => {+ const now = () => clock;+ const first = setup({now});+ const second = setup({now});+ for (const {animator} of [first, second]) {+ animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ }+ await advance(120);+ const call = clock;+ first.animator.animate({x: -100}, {spring: springs.emphasis});+ // The callback goes on to a pager's next child.+ clock += 3;+ second.animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 13;+ await commitFrame(clock);+ expect(live('translate').map(animation => animation.startTime)).toEqual([+ call,+ call,+ ]);+ for (const ms of [0, 50, 200]) {+ expect(second.animator.get('x', clock + ms)).toBeCloseTo(+ first.animator.get('x', clock + ms),+ 6,+ );+ }+ });++ it('a call in the next callback, after a microtask checkpoint, starts its own clock', async () => {+ const now = () => clock;+ const first = setup({now});+ const second = setup({now});+ for (const {animator} of [first, second]) {+ animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ }+ await advance(120);+ const call = clock;+ first.animator.animate({x: -100}, {spring: springs.emphasis});+ // The browser runs a microtask checkpoint after each callback.+ await Promise.resolve();+ clock += 3;+ second.animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 13;+ await commitFrame(clock);+ expect(live('translate').map(animation => animation.startTime)).toEqual([+ call,+ call + 3,+ ]);+ });++ async function twoMoving() {+ const now = () => clock;+ const first = setup({now});+ const second = setup({now});+ for (const {animator} of [first, second]) {+ animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ }+ await advance(120);+ return [first, second] as const;+ }++ it('a call that a disposed animator left waiting does not make a later frame late', async () => {+ const [first, second] = await twoMoving();+ first.animator.animate({x: -100}, {spring: springs.emphasis});+ first.animator.dispose();+ await commitFrame(clock);+ // A second later the other element moves again and retargets.+ clock += 1000;+ second.animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ await advance(120);+ const call = clock;+ second.animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 10;+ await commitFrame(clock);+ const [made] = live('translate').filter(+ animation => animation.element === second.element,+ );+ expect(made.startTime).toBe(call);+ });++ it('a call that a rebuild committed early does not make its frame late', async () => {+ const [first, second] = await twoMoving();+ first.animator.animate({x: -100}, {spring: springs.emphasis});+ // A rebuild commits that call at once, before the frame.+ first.animator.set({x: 0});+ await Promise.resolve();+ clock += 20;+ const call = clock;+ second.animator.animate({x: -100}, {spring: springs.emphasis});+ clock += 25;+ await commitFrame(clock);+ const [made] = live('translate').filter(+ animation => animation.element === second.element,+ );+ expect(made.startTime).toBe(call);+ });++ it('a retarget made in a frame callback of the page waits for the next frame, which starts it from the screen when it comes late', async () => {+ const {animator} = await moving();+ const [old] = live('translate');+ // The page's own frame callback makes the call, in the frame it runs in.+ frameQueue.push(() =>+ animator.animate({x: -100}, {spring: springs.emphasis}),+ );+ await commitFrame(clock);+ // That frame shows the old curve still.+ expect(old.cancelled).toBe(false);+ clock += 200;+ await commitFrame(clock);+ const [made] = live('translate');+ expect(made.startTime).toBe(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ });++ it('a retarget made in a frame callback of the page shows its new curve in the next frame, on its own clock', async () => {+ const {animator} = await moving();+ const [old] = live('translate');+ const call = clock;+ frameQueue.push(() =>+ animator.animate({x: -100}, {spring: springs.emphasis}),+ );+ await commitFrame(clock);+ // The frame that runs the callback still shows the old curve.+ expect(live('translate')).toEqual([old]);+ clock += 16;+ await commitFrame(clock);+ // The next frame shows the new curve, from the call's own time.+ const [made] = live('translate');+ expect(old.cancelled).toBe(true);+ expect(made).not.toBe(old);+ expect(made.startTime).toBe(call);+ const curve = solveSpring(toSpring(springs.emphasis), {+ from: shownAt(call),+ to: -100,+ velocity: shownVelocityAt(call),+ });+ // The keyframes hold the curve within a quarter of a pixel.+ expect(+ Math.abs(+ sampleAt(made, 'translate', clock)[0] -+ curve.value((clock - call) / 1000),+ ),+ ).toBeLessThan(0.26);+ });++ it('a late frame keeps a velocity that the call handed the spring, such as a release’s', async () => {+ const {animator} = await moving();+ animator.animate(+ {x: -100},+ {spring: springs.emphasis, velocity: {x: -900}},+ );+ clock += 200;+ await commitFrame(clock);+ expect(live('translate')[0].startTime).toBe(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(-900, 4);+ const curve = solveSpring(toSpring(springs.emphasis), {+ from: shownAt(clock),+ to: -100,+ velocity: -900,+ });+ expect(animator.get('x', clock + 90)).toBeCloseTo(curve.value(0.09), 6);+ });++ it('a late frame takes the velocity on screen when the call hands the curve’s own velocity', async () => {+ const {animator} = await moving();+ animator.animate(+ {x: -100},+ {spring: springs.emphasis, velocity: {x: animator.getVelocity('x')}},+ );+ clock += 200;+ await commitFrame(clock);+ expect(animator.get('x', clock)).toBeCloseTo(shownAt(clock), 6);+ expect(animator.getVelocity('x', clock)).toBeCloseTo(+ shownVelocityAt(clock),+ 4,+ );+ });++ it('a retarget whose frame source’s page is hidden while the element shows elsewhere keeps its own clock and finishes', async () => {+ // The opener page's frames drive the animator; the element is in+ // another visible document, as in a Picture-in-Picture window.+ vi.stubGlobal('requestAnimationFrame', requestFrame);+ const other = document.implementation.createHTMLDocument('elsewhere');+ Object.defineProperty(other, 'visibilityState', {+ configurable: true,+ get: () => 'visible',+ });+ const element = other.createElement('div');+ other.body.append(element);+ stubMedia(false, false);+ const animator = createMotionEngine(element, {now: () => clock});+ animator.animate(+ {x: 300},+ {spring: springs.emphasis, velocity: {x: 800}},+ );+ await advance(120);+ const showAgain = hidePage();+ try {+ const handle = animator.animate(+ {x: 250},+ {spring: springs.quickChange},+ );+ let finished: boolean | null = null;+ void handle.finished.then(value => {+ finished = value;+ });+ // No frame comes: the timers end the call.+ const own = (handle.curve('x')?.duration ?? 0) * 1000;+ clock += own + 50;+ await vi.advanceTimersByTimeAsync(own + 50);+ expect(finished).toBe(true);+ expect(inlineX(element)).toBeCloseTo(250, 3);+ } finally {+ showAgain();+ }+ });++ /** Hides the page, as a background tab is, until the call it returns. */+ function hidePage() {+ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ get: () => 'hidden',+ });+ document.dispatchEvent(new Event('visibilitychange'));+ return () => {+ Reflect.deleteProperty(document, 'visibilityState');+ document.dispatchEvent(new Event('visibilitychange'));+ };+ }++ async function finishesOnItsClock(+ animator: Animator,+ element: HTMLElement,+ hideFirst: boolean,+ ) {+ const show = hideFirst ? hidePage() : null;+ const handle = animator.animate({x: 250}, {spring: springs.quickChange});+ const showAgain = show ?? hidePage();+ try {+ let finished: boolean | null = null;+ void handle.finished.then(value => {+ finished = value;+ });+ // No frame comes: the timers end the call.+ const own = (handle.curve('x')?.duration ?? 0) * 1000;+ clock += own + 50;+ await vi.advanceTimersByTimeAsync(own + 50);+ expect(finished).toBe(true);+ expect(inlineX(element)).toBeCloseTo(250, 3);+ } finally {+ showAgain();+ }+ // The frame after the page shows again starts nothing. Animators of+ // other tests hear the page change too, so only this one's count.+ await commitFrame(clock);+ expect(+ live('translate').filter(animation => animation.element === element),+ ).toHaveLength(0);+ }++ it('on a hidden page, which draws no frames, a retarget keeps its own clock and finishes at its end', async () => {+ const {animator, element} = await moving();+ await finishesOnItsClock(animator, element, true);+ });++ it('a page that goes hidden before a retarget’s frame finishes it on its own clock', async () => {+ const {animator, element} = await moving();+ await finishesOnItsClock(animator, element, false);+ });+ });+it('velocity is continuous across a retarget (property sweep)', async () => {for (const spring of [springs.settle,@@ -4726,6 +5252,7 @@ describe('the presented offset iOS hit testing reads', () => {await advance(100);expect(presentedOffsetOf(element).y).toBeCloseTo(30, 6);animator.animate({y: 0}, {spring: springs.sheetPresent});+ await commitFrame(clock);expect(presentedOffsetOf(element).y).toBeCloseTo(0, 6);animator.dispose();});diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 2f831304ed..0d85a9c74e 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -64,16 +64,18 @@* learns that start only a frame or more later (Chromium), the call starts* at the frame that commits it, the start the compositor takes, so a* retarget or a rebase before then continues from the frame on screen. A- * call that continues motion on- * screen (a retarget, a catch) keeps an explicit start at the call time, or- * `options.at` to line several animators up, so the new curve continues- * from the frame on screen. Keyframes are sampled from the call's start, so- * a value that keeps moving through a rebuild stays on its curve to the- * frame. `options.start` changes that per call: `'commit'` dates a retarget- * by the browser's commit as well, and `'presented'` creates the animations- * of a call from rest two frames later, once its element at rest has been- * presented (a UI process that applies commits late); a retarget still starts- * now, from the value and velocity on screen.+ * call that continues motion on screen (a retarget, a catch) keeps an+ * explicit start: the first motion call of its callback, or `options.at`.+ * So calls on several animators in one callback line up. The new curve+ * then continues from the frame on screen. A late commit restarts each+ * spring at its frame (lookAtShown). Keyframes are sampled from the call's+ * start, so a value that keeps moving through a rebuild stays on its curve+ * to the frame.+ * `options.start` changes that per call. `'commit'` dates a retarget by the+ * browser's commit as well. `'presented'` creates the animations of a call+ * from rest two frames later, once its element at rest has been presented.+ * That serves a UI process that applies commits late. It does not change+ * when a retarget starts.* `handle.curve(property)` hands out the curve a call plays, so a* companion can follow it on the same clock.* `options.additive` retargets as UIKit does: the old curve keeps going and a@@ -389,7 +391,9 @@ export interface MotionHandle {/*** When the motion started on the document timeline (ms): for a call from* rest, the time the browser committed it (a block before the first frame- * moves it later); otherwise the call time, or `at`.+ * moves it later); otherwise the call time, or `at`. A retarget whose+ * frame comes late starts its springs at that frame, and this stays the+ * call time.*/readonly started: Promise<number>;/** Presentation value of a property at `time` (default now). */@@ -401,7 +405,8 @@ export interface MotionHandle {* in seconds from the call's start: what the keyframes play. Null for a* property the call does not move, or moves without travel (Reduced* Motion). Map it onto a companion property with `mapProgress`, and play- * that on the same clock.+ * that on the same clock. A retarget whose frame comes late starts its+ * spring again at that frame, and this stays the curve the call started.*/curve(property: MotionProperty | 'scale'): MotionCurve | null;/** New targets for this call's properties, keeping their velocity. */@@ -533,6 +538,10 @@ interface Segment {group?: StartGroup;/** The spring driving it, when one does (`rebase` keeps it). */spring?: SpringDescription;+ /** The old curve plus a spring of the difference (`additive`). */+ readonly isAdditive?: true;+ /** A velocity the call handed the spring, such as a release's. */+ readonly handedVelocity?: number;}/**@@ -762,6 +771,75 @@ function markTask(time: number, clock: () => number): TaskMark {/** The first read of the time an animation frame runs, by its timestamp. */let frameRead: {readonly frame: number; readonly time: number} | null = null;+/** The first motion call on a clock since the last microtask checkpoint. */+let openCall: {readonly time: number; readonly clock: () => number} | null =+ null;++/**+ * The time of a motion call with no explicit clock. It is the time of the+ * first such call on the same clock since the last microtask checkpoint. One+ * event listener or frame callback thus shares one clock. So calls on+ * several animators in one callback, such as a pager's children, line up, as+ * calls from rest share one start. A call more than LATE_START_MS after the+ * first opens a new clock: the curves that a block passed restart at their+ * frame instead.+ */+function callTime(clock: () => number): number {+ const time = clock();+ if (+ openCall != null &&+ openCall.clock === clock &&+ time - openCall.time <= LATE_START_MS+ ) {+ return openCall.time;+ }+ const call = {time, clock};+ openCall = call;+ queueMicrotask(() => {+ if (openCall === call) {+ openCall = null;+ }+ });+ return time;+}++/**+ * Per animator, the first of its calls that still wait for the frame that+ * commits them. An animator removes its entry once nothing of its waits: a+ * rebuild or a hidden page committed its calls, or it was disposed or moved.+ * The frame's first read takes every entry.+ */+const waitingCalls = new Map<object, number>();++/** The first waiting call, read once by the frame with this timestamp. */+let waitingRead: {readonly frame: number; readonly first: number} | null = null;++/**+ * The first call that the animation frame with timestamp `frame` commits.+ * The frame reads it once, so every animator in it judges a late commit from+ * the same call. `own` is the first of the reading animator's calls.+ */+function firstCommitted(frame: number | undefined, own: number): number {+ if (frame != null && waitingRead?.frame === frame) {+ return Math.min(waitingRead.first, own);+ }+ const first = Math.min(own, ...waitingCalls.values());+ // The frame commits every call that waits now. An animator whose look+ // never runs, such as one on another frame source, counts once at most.+ waitingCalls.clear();+ if (frame != null) {+ const read = {frame, first};+ waitingRead = read;+ // A browser runs every callback of a frame before its next task.+ setTimeout(() => {+ if (waitingRead === read) {+ waitingRead = null;+ }+ }, 0);+ }+ return first;+}+/*** The time the animation frame with timestamp `frame` runs, read once in* that frame. Every animator's callback in the frame takes that read, so the@@ -1671,12 +1749,16 @@ export function createMotionEngine(if (stale.size === 0) {return;}- const properties = [...stale].flatMap(channel => CHANNELS[channel]);+ // A waiting channel rebuilds at the frame that commits its call.+ const properties = [...stale]+ .filter(channel => !heldForFrame.has(channel))+ .flatMap(channel => CHANNELS[channel]);stale.clear();commit(properties, now());};const rebuild = (channel: Channel, time: number) => {+ commitWaitingNow(channel);stale.delete(channel);const previous = running.get(channel);running.delete(channel);@@ -1983,6 +2065,14 @@ export function createMotionEngine(if (running.get(channel) !== animation) {return;}+ // The old curve plays on until the frame that commits the call+ // (lookAtShown).+ if (heldForFrame.has(channel)) {+ if (!retireTimers.has(channel)) {+ retireTimers.set(channel, setTimeout(retire, END_RECHECK_MS));+ }+ return;+ }// Paused or sought (a sampler holding it): retire when its own time// reaches the curve's end, never from the wall clock.const remaining = remainingCurve(animation);@@ -2427,12 +2517,12 @@ export function createMotionEngine(}return null;}- // A call that continues motion starts now, unless it asks for the- // browser's start (`commit`). `presented` asks only for a call from rest.- // A curve that still moves is not at rest, so a call on it starts now,- // from the value and velocity on screen. A tail that shows as at rest- // counts as rest, so a call on it waits, under `presented` for its two- // frames.+ // A call that continues motion keeps its call's clock, unless it asks+ // for the browser's start (`commit`). `presented` asks only for a call+ // from rest. A curve that still moves is not at rest, so a call on it+ // continues from the value and velocity on screen. A tail that shows as+ // at rest counts as rest, so a call on it waits, under `presented` for+ // its two frames.for (const channel of start === 'commit' ? [] : channels) {for (const property of CHANNELS[channel]) {const segment = segments.get(property);@@ -2473,6 +2563,7 @@ export function createMotionEngine(changed: MotionProperty[],time: number,presented = false,+ waitsForFrame = false,) => {if (group != null) {for (const property of changed) {@@ -2496,6 +2587,10 @@ export function createMotionEngine(requestFrame(() => requestFrame(() => flushDeferredThrough(call)));return;}+ if (group == null && waitsForFrame) {+ deferRebuild(changed, time);+ return;+ }startCall(group, changed, time);};@@ -2935,6 +3030,10 @@ export function createMotionEngine() {continue;}+ if (heldForFrame.has(channel)) {+ wait = Math.max(wait, END_RECHECK_MS);+ continue;+ }const remaining = remainingCurve(animation);if (remaining != null && remaining > 0) {wait = Math.max(@@ -3059,13 +3158,34 @@ export function createMotionEngine(to: number,spring: SpringDescription,velocity: number,+ ): Segment | null =>+ // The motion role it plays, at the tempo of the theme it is in.+ springFrom(+ owner,+ property,+ start,+ valueAt(property, start),+ velocity,+ to,+ resolveMotion(target, spring),+ );++ /**+ * `resolved` is already at the theme's tempo. A restart passes a segment's+ * spring as it is.+ */+ const springFrom = (+ owner: HandleState,+ property: MotionProperty,+ start: number,+ from: number,+ velocity: number,+ to: number,+ resolved: SpringDescription,): Segment | null => {- const from = valueAt(property, start);if (from === to && velocity === 0) {return null;}- // The motion role it plays, at the tempo of the theme it is in.- const resolved = resolveMotion(target, spring);const curve = solveSpring(toSpring(resolved), {from, to, velocity});const duration = Math.min(MAX_DURATION_MS,@@ -3120,6 +3240,7 @@ export function createMotionEngine(.filter(jump => jump > 0),owner,spring: resolved,+ isAdditive: true,};};@@ -3196,6 +3317,378 @@ export function createMotionEngine(};};+ // -- a retarget's start ----------------------------------------------------++ /**+ * What the screen shows of a property after a call that continues its+ * motion: the old curve, or the value at rest. It shows that until the+ * frame that commits the call. A rebase since then moves the element+ * under it by `offset`.+ */+ interface Shown {+ readonly segment: Segment | null;+ readonly resting: number;+ offset: number;+ /** When the first such call changed the property. */+ readonly since: number;+ }++ const shown = new Map<MotionProperty, Shown>();+ /**+ * Channels whose rebuild waits for the frame that commits their call, with+ * the time of the last call on each.+ */+ const heldForFrame = new Map<Channel, number>();+ let isShownLookQueued = false;+ let stopWatchingHidden: (() => void) | null = null;++ /** The page whose frames the animator's own frame source draws. */+ const framePage =+ options.requestFrame == null && typeof document !== 'undefined'+ ? document+ : null;++ /**+ * Whether no frame comes. A hidden page draws none. The frame source of a+ * hidden page draws none either, while the element shows elsewhere (a+ * Picture-in-Picture window's opener).+ */+ const isPageHidden = () =>+ target?.ownerDocument.visibilityState === 'hidden' ||+ framePage?.visibilityState === 'hidden';++ const forgetShown = () => {+ shown.clear();+ syncWaiting();+ stopWatchingHidden?.();+ };++ /** This animator's entry in the waiting calls, from what still waits. */+ const waitKey = {};+ const syncWaiting = () => {+ let first = Infinity;+ for (const entry of shown.values()) {+ first = Math.min(first, entry.since);+ }+ if (first === Infinity) {+ waitingCalls.delete(waitKey);+ } else {+ waitingCalls.set(waitKey, first);+ }+ };++ /**+ * Rebuilds channels from their last calls' times, as those calls would+ * have rebuilt them: the same keyframes and start time.+ */+ const rebuildOnCallClocks = (channels: [Channel, number][]) => {+ for (const time of new Set(channels.map(([, at]) => at))) {+ commit(+ channels+ .filter(([, at]) => at === time)+ .flatMap(([channel]) => CHANNELS[channel]),+ time,+ );+ }+ };++ const flushWaiting = () => {+ const channels = [...heldForFrame];+ heldForFrame.clear();+ rebuildOnCallClocks(channels);+ };++ /**+ * A hidden page draws no frames and shows nothing, so its calls keep their+ * own clock, as the timers do (scheduleRetire). A page that goes hidden+ * before the frame forgets what it showed and rebuilds what waits.+ */+ const watchHidden = () => {+ const pages = [+ ...new Set(+ [target?.ownerDocument, framePage].filter(page => page != null),+ ),+ ];+ if (stopWatchingHidden != null || pages.length === 0) {+ return;+ }+ const onChange = () => {+ if (isPageHidden()) {+ forgetShown();+ flushWaiting();+ }+ };+ for (const page of pages) {+ page.addEventListener('visibilitychange', onChange);+ }+ stopWatchingHidden = () => {+ for (const page of pages) {+ page.removeEventListener('visibilitychange', onChange);+ }+ stopWatchingHidden = null;+ };+ };++ /**+ * Holds a call's channels for the frame that commits it, which rebuilds+ * them (lookAtShown). Until then the old curve plays on, and no end look+ * retires it.+ */+ const deferRebuild = (changed: MotionProperty[], time: number) => {+ for (const property of changed) {+ const channel = CHANNEL_OF[property];+ const isNew = !heldForFrame.has(channel);+ heldForFrame.set(channel, time);+ if (!isNew) {+ continue;+ }+ stale.delete(channel);+ clearTimeout(retireTimers.get(channel));+ retireTimers.delete(channel);+ clearTimeout(retireLooks.get(channel));+ retireLooks.delete(channel);+ }+ };++ /** A rebuild before that frame commits the channel's calls at once. */+ const commitWaitingNow = (channel: Channel) => {+ if (!heldForFrame.delete(channel)) {+ return;+ }+ for (const property of CHANNELS[channel]) {+ shown.delete(property);+ }+ syncWaiting();+ };++ /**+ * Rebuilds a waiting channel from what the screen shows, after a rebase+ * moved the element under it. The old curve plays on, shifted with the+ * element, until the frame that commits the call.+ */+ const rebuildShown = (channel: Channel, time: number) => {+ const model = new Map<MotionProperty, Segment | undefined>();+ const rests = new Map<MotionProperty, number>();+ for (const property of CHANNELS[channel]) {+ const entry = shown.get(property);+ if (entry == null) {+ continue;+ }+ model.set(property, segments.get(property));+ rests.set(property, resting[property]);+ if (entry.segment == null) {+ segments.delete(property);+ resting[property] = entry.resting + entry.offset;+ } else {+ segments.set(property, shifted(entry.segment, entry.offset));+ }+ }+ const callTime = heldForFrame.get(channel);+ heldForFrame.delete(channel);+ try {+ rebuild(channel, time);+ } finally {+ for (const [property, segment] of model) {+ if (segment == null) {+ segments.delete(property);+ } else {+ segments.set(property, segment);+ }+ }+ for (const [property, rest] of rests) {+ resting[property] = rest;+ }+ if (callTime != null) {+ heldForFrame.set(channel, callTime);+ }+ }+ };++ /**+ * Notes what the screen shows of each property that a call continuing+ * motion changes, before the call replaces its curve. The call's channels+ * then wait for the frame that commits it, which rebuilds them+ * (lookAtShown). That holds for a call in a frame callback of the page's.+ * A call from rest, a call on an explicit clock and a call in an+ * animator's frame callback start on their frame already.+ */+ const noteShown = (+ properties: Iterable<MotionProperty>,+ time: number,+ group: StartGroup | null,+ at: number | undefined,+ ): boolean => {+ if (+ group != null ||+ at != null ||+ frameDepth > 0 ||+ requestFrame == null ||+ target == null ||+ typeof target.animate !== 'function' ||+ isPageHidden()+ ) {+ return false;+ }+ // A curve on these channels may still wait for the browser's start.+ // Its call's own start then settles where the new curve begins.+ const list = [...properties];+ if (+ list.some(property =>+ CHANNELS[CHANNEL_OF[property]].some(other => {+ const segment = segments.get(other);+ return segment != null && isHeld(segment);+ }),+ )+ ) {+ return false;+ }+ for (const property of list) {+ if (shown.has(property)) {+ continue;+ }+ shown.set(property, {+ segment: segments.get(property) ?? null,+ resting: resting[property],+ offset: 0,+ since: time,+ });+ }+ syncWaiting();+ watchHidden();+ if (!isShownLookQueued) {+ isShownLookQueued = true;+ requestFrame(lookAtShown);+ }+ return true;+ };++ /** The value and velocity that the screen shows of a property at `time`. */+ const shownAt = (entry: Shown, time: number) => {+ const {segment, offset} = entry;+ if (segment == null) {+ return {value: entry.resting + offset, velocity: 0};+ }+ const elapsed = time - segment.start;+ if (elapsed >= segment.duration) {+ return {value: segment.target + offset, velocity: 0};+ }+ const t = Math.max(0, elapsed);+ return {value: segment.at(t) + offset, velocity: segment.speed(t)};+ };++ const shifted = (segment: Segment, offset: number): Segment =>+ offset === 0+ ? segment+ : {+ ...segment,+ target: segment.target + offset,+ at: t => segment.at(t) + offset,+ };++ /**+ * The frame that commits calls that continue motion. When it comes more+ * than LATE_START_MS after the first call it commits on any animator, the+ * screen has shown the old curve. Each spring that they leave+ * then starts here, from the value on screen, as UIKit's added spring+ * begins at its commit. It keeps a velocity that its call handed it, such+ * as a release's, and otherwise takes the one on screen. A played curve or+ * a coast keeps its call's clock, and an earlier frame keeps every call on+ * its own clock.+ */+ const lookAtShown = (frame?: number) => {+ isShownLookQueued = false;+ const entries = [...shown];+ const channels = [...heldForFrame];+ heldForFrame.clear();+ forgetShown();+ if (target == null) {+ return;+ }+ const at = frameTime(frame, now);+ const late =+ at -+ firstCommitted(+ frame,+ Math.min(...entries.map(([, entry]) => entry.since)),+ ) >+ LATE_START_MS;+ const changed: MotionProperty[] = [];+ const owners = new Set<HandleState>();+ for (const [property, entry] of entries) {+ const current = segments.get(property);+ if (+ !late ||+ current == null ||+ current.spring == null ||+ current.isFade === true ||+ isHeld(current)+ ) {+ continue;+ }+ const screen = shownAt(entry, at);+ const next =+ current.isAdditive === true && entry.segment != null+ ? additiveSegment(+ current.owner,+ property,+ at,+ current.target,+ current.spring,+ shifted(entry.segment, entry.offset),+ )+ : springFrom(+ current.owner,+ property,+ at,+ screen.value,+ current.handedVelocity ??+ // From rest, the call's own start velocity.+ (entry.segment == null ? current.speed(0) : screen.velocity),+ current.target,+ current.spring,+ );+ if (next == null) {+ segments.delete(property);+ resting[property] = current.target;+ } else {+ segments.set(+ property,+ current.handedVelocity == null+ ? next+ : {...next, handedVelocity: current.handedVelocity},+ );+ }+ owners.add(current.owner);+ changed.push(property);+ }+ const restarted = new Set(changed.map(property => CHANNEL_OF[property]));+ if (restarted.size > 0) {+ commit(+ [...restarted].flatMap(channel => CHANNELS[channel]),+ at,+ );+ }+ rebuildOnCallClocks(+ channels.filter(([channel]) => !restarted.has(channel)),+ );+ for (const owner of owners) {+ if (owner.settled || owner.timer == null) {+ continue;+ }+ clearTimeout(owner.timer);+ let end = at;+ for (const segment of segments.values()) {+ if (segment.owner === owner) {+ end = Math.max(end, segment.start + segment.duration);+ }+ }+ owner.timer = setTimeout(+ () => settleAtEnd(owner),+ Math.max(0, end - now()),+ );+ }+ };+// -- the animator -----------------------------------------------------------const commit = (changed: Iterable<MotionProperty>, time: number) => {@@ -3657,6 +4150,9 @@ export function createMotionEngine(}flushDeferred();present(false);+ // The next node never showed the old curves.+ forgetShown();+ heldForFrame.clear();if (next == null) {// Unmount, unless a node replaces this one in the same task (React's// replacement order: attach(null), then the new node): nothing is@@ -3836,6 +4332,7 @@ export function createMotionEngine(][]) {interrupt(property, time);segments.delete(property);+ shown.delete(property);resting[property] = value;}// Direct manipulation: the layer makes each write a composite only.@@ -3852,7 +4349,7 @@ export function createMotionEngine(if (animateOptions.start !== 'presented') {flushDeferred();}- const time = animateOptions.at ?? now();+ const time = animateOptions.at ?? callTime(now);const targets = expand(to);const velocities = expand(transition.velocity ?? {});const {owner, finished} = newOwner();@@ -3888,15 +4385,27 @@ export function createMotionEngine();continue;}- const velocity = velocities[property] ?? velocityAt(property, time);- next[property] = springSegment(+ const handed = velocities[property];+ const current = velocityAt(property, time);+ const segment = springSegment(owner,property,time,targets[property] as number,transition.spring,- velocity,+ handed ?? current,);+ // A velocity that is the curve's own at the call keeps the current+ // velocity, as no velocity does. Any other is handed on, such as a+ // release's.+ const isHanded =+ handed != null &&+ Math.abs(handed - current) >+ SAMPLE_TOLERANCE[property] * REST_FRAMES_PER_SECOND;+ next[property] =+ segment != null && isHanded+ ? {...segment, handedVelocity: handed}+ : segment;}}@@ -3906,6 +4415,12 @@ export function createMotionEngine(animateOptions.at,animateOptions.start,);+ const waitsForFrame = noteShown(+ Object.keys(next) as MotionProperty[],+ time,+ group,+ animateOptions.at,+ );const adopted =plan?.landing != null? adoptLandings(plan.landing, Object.keys(next) as MotionProperty[])@@ -3935,6 +4450,7 @@ export function createMotionEngine(changed,time,animateOptions.start === 'presented' && animateOptions.at == null,+ waitsForFrame,);if (plan?.borrowed != null) {// The dip's own commit cleared it; the borrow lasts the dip.@@ -3958,7 +4474,7 @@ export function createMotionEngine(if (playOptions.start !== 'presented') {flushDeferred();}- const time = playOptions.at ?? now();+ const time = playOptions.at ?? callTime(now);const {owner, finished} = newOwner();const byProperty: Partial<Record<MotionProperty, MotionCurve>> = {};// `scale` first, so an explicit `scaleX` or `scaleY` beside it wins.@@ -4036,6 +4552,12 @@ export function createMotionEngine(playOptions.at,playOptions.start,);+ const waitsForFrame = noteShown(+ Object.keys(next) as MotionProperty[],+ time,+ group,+ playOptions.at,+ );const adopted =plan?.landing != null? adoptLandings(plan.landing, Object.keys(next) as MotionProperty[])@@ -4065,6 +4587,7 @@ export function createMotionEngine(changed,time,playOptions.start === 'presented' && playOptions.at == null,+ waitsForFrame,);if (plan?.borrowed != null) {// The dip's own commit cleared it; the borrow lasts the dip.@@ -4086,7 +4609,7 @@ export function createMotionEngine(decay(curves, decayOptions = {}) {syncPending();flushDeferred();- const time = decayOptions.at ?? now();+ const time = decayOptions.at ?? callTime(now);// Under Reduce Motion only momentum keeps moving (DR2, DEC-2): a curve// that is a transition plays as `animate` does, a cross-fade or at once.const reduce = prefersReducedMotion();@@ -4114,6 +4637,7 @@ export function createMotionEngine(return transitioned;}const group = beginGroup(time, properties, decayOptions.at);+ const waitsForFrame = noteShown(properties, time, group, decayOptions.at);for (const property of properties) {const curve = curves[property] as MotionCurve;interrupt(property, time);@@ -4132,7 +4656,7 @@ export function createMotionEngine(owner,});}- commitCall(group, owner, properties, time);+ commitCall(group, owner, properties, time, false, waitsForFrame);const handle = makeHandle(owner, properties, finished, time, group);if (transitioned == null) {return handle;@@ -4184,9 +4708,15 @@ export function createMotionEngine(continue;}// A Reduce Motion fade is never left half done: it finishes, and a- // dip on the stylesheet's opacity hands that opacity back.+ // dip on the stylesheet's opacity hands that opacity back. A call+ // that continued the motion and is still not on screen past its+ // frame shows the old curve: the element stops where that is.+ const noted = shown.get(property);+ shown.delete(property);const value = !segment.isFade- ? valueAt(property, time)+ ? noted != null && time - noted.since > LATE_START_MS+ ? shownAt(noted, time).value+ : valueAt(property, time): wasBorrowed? IDENTITY.opacity: heading;@@ -4215,6 +4745,10 @@ export function createMotionEngine(if (delta === 0) {continue;}+ const noted = shown.get(property);+ if (noted != null) {+ noted.offset += delta;+ }const segment = segmentAt(property, time);if (segment == null) {changed.push(property);@@ -4304,7 +4838,17 @@ export function createMotionEngine(});}}- commit(changed, time);+ // A waiting channel shows its old curve, moved with the element, until+ // the frame that commits its call.+ commit(+ changed.filter(property => !heldForFrame.has(CHANNEL_OF[property])),+ time,+ );+ for (const channel of new Set(changed.map(p => CHANNEL_OF[p]))) {+ if (heldForFrame.has(channel)) {+ rebuildShown(channel, time);+ }+ }// The handles that own the rebased curves finish at their new ends.for (const owner of owners) {if (owner.settled || owner.timer == null) {@@ -4387,6 +4931,8 @@ export function createMotionEngine(}running.clear();stale.clear();+ forgetShown();+ heldForFrame.clear();for (const timer of retireTimers.values()) {clearTimeout(timer);}