An open source design system that's fully customizable and agent ready
TypeScript
fix(motion): WebKit draws a glide's last frame at its place (#10663)
Christopher Chedeau9ea776e22bb5
diff --git a/.changeset/animated-layout-webkit-end-frame.md b/.changeset/animated-layout-webkit-end-frame.mdnew file mode 100644index 0000000000..690bb5f3d8--- /dev/null+++ b/.changeset/animated-layout-webkit-end-frame.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Motion: in WebKit on Linux, the last frame of an `animatedLayout` change shows where each motion ends once a frame has drawn the motion near its end. Under load, that frame, and every frame of a long task over its end, could show a glide, an exit's fade or an indicator's turn part of the way through: a collapsing `TreeList` drew the rows below 44 px back, its leaving rows half faded and its chevron mid-turn. A long task that starts before that frame, or a motion near its end only at its last keyframe, can still show it. At normal speed the motion is unchanged.++@vjeuxdiff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex fce16b0e83..68854de0ea 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -239,6 +239,19 @@ Out of coverage, each taking its final place at once:handles, on an element mid-glide, still goes to what was at that spot beforethe glide, until the glide ends (glides last at most the theme's moveduration).+- Each motion of a change also makes the engine resolve its element once+ more, in the first frame the motion is drawn near its end: within half a+ pixel or half a percent, or 0.005 of an opacity or of an indicator's turn.+ WebKit can draw a compositor animation's last frame, and every frame of a+ long task over its end, with the values it last resolved; that frame shows+ the motion's end. It covers the glides, an exit and its parts, a reveal's+ parts and an indicator's transition. A Reduce Motion fade gets none: WebKit+ draws its end values at its end. Implementation gap: a long task that starts+ before that frame still shows the values from the last resolve, and a+ motion near its end only at its last keyframe (a linear curve, or a long+ move on a steep curve) gets no such resolve. Review condition: re-measure on+ each WebKit release, and remove these resolves once WebKit draws an ended+ compositor animation at its final values.## Verificationdiff --git a/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.tsindex 7b2c8c65e5..4bd33ea07d 100644--- a/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts+++ b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts@@ -28,12 +28,15 @@ import {releaseAnimations,requireFrames,seekAnimations,+ startBusyControl,startCompositorTrace,startScreencast,touchDriver,trackMarker,withStorybook,writeEvidence,+ type Box,+ type CastFrame,type HeldAnimation,} from '@astryxdesign/interaction-harness';import {expectReducedMotionCrossFade} from '../../List/__tests__/reducedMotion';@@ -411,6 +414,125 @@ async function seekThroughGlide(*/const RECORDED_GLIDE_MS = 1200;+/** How long the page is held past a glide's end, ms. */+const TAIL_BLOCK_MS = 500;++/** A pixel darker than this, on a 0 to 255 grey, is ink. */+const INK_BELOW = 230;++/**+ * How many ink pixels of each frame inside `box`, and of `rest`, have no ink+ * within one pixel in the other. A motion drawn within half a pixel of its+ * end matches, as does text a layer draws a shade lighter. Two frames of one+ * scene count 0 in both engines. Frames are decoded in a scratch page, as+ * trackMarker decodes them.+ */+async function inkOffRest(+ page: Page,+ frames: ReadonlyArray<CastFrame>,+ rest: CastFrame,+ box: Box,+): Promise<number[]> {+ const scratch = await page.context().newPage();+ try {+ const counts: number[] = [];+ for (let i = 0; i < frames.length; i += 12) {+ counts.push(+ ...(await scratch.evaluate(+ async ({items, base, area, below}) => {+ const inkOf = async (frame: typeof base) => {+ const blob = await (+ await fetch(`data:image/${frame.format};base64,${frame.data}`)+ ).blob();+ const bitmap = await createImageBitmap(blob);+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ const context = canvas.getContext('2d');+ if (context == null) {+ throw new Error('no 2d context');+ }+ context.drawImage(bitmap, 0, 0);+ const scale = bitmap.width / frame.viewportWidth;+ const {data, width, height} = context.getImageData(+ Math.floor(area.x * scale),+ Math.floor(area.y * scale),+ Math.ceil(area.width * scale),+ Math.ceil(area.height * scale),+ );+ const ink = new Uint8Array(width * height);+ for (let p = 0; p < ink.length; p += 1) {+ const grey =+ (data[p * 4] + data[p * 4 + 1] + data[p * 4 + 2]) / 3;+ ink[p] = grey < below ? 1 : 0;+ }+ return {ink, width, height};+ };+ // Ink in `a` with no ink in `b` within one pixel.+ const missing = (+ a: Uint8Array,+ b: Uint8Array,+ width: number,+ height: number,+ ) => {+ let count = 0;+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ if (a[y * width + x] === 0) {+ continue;+ }+ let isNear = false;+ for (let dy = -1; dy <= 1 && !isNear; dy += 1) {+ for (let dx = -1; dx <= 1 && !isNear; dx += 1) {+ const ny = y + dy;+ const nx = x + dx;+ isNear =+ ny >= 0 &&+ ny < height &&+ nx >= 0 &&+ nx < width &&+ b[ny * width + nx] === 1;+ }+ }+ if (!isNear) {+ count += 1;+ }+ }+ }+ return count;+ };+ const at = await inkOf(base);+ const out: number[] = [];+ for (const item of items) {+ const {ink} = await inkOf(item);+ out.push(+ missing(ink, at.ink, at.width, at.height) ++ missing(at.ink, ink, at.width, at.height),+ );+ }+ return out;+ },+ {+ items: frames.slice(i, i + 12).map(f => ({+ data: f.data,+ format: f.format,+ viewportWidth: f.viewportWidth,+ })),+ base: {+ data: rest.data,+ format: rest.format,+ viewportWidth: rest.viewportWidth,+ },+ area: box,+ below: INK_BELOW,+ },+ )),+ );+ }+ return counts;+ } finally {+ await scratch.close();+ }+}+/** Sets the glide's duration where the tree reads it, as a theme does. */const lengthenGlide = async (page: Page, ms: number) =>page@@ -610,6 +732,67 @@ test('collapse under a finger: the group fades out as the rows below glide up, wawait expect(group).toHaveCount(0);});+test('collapse under a finger: a long task over the end of the glide draws the tree as it rests, its leaving rows and chevron included', async ({+ page,+}) => {+ await open(page);+ await tapToggle(page);+ await expect(parts(page).child).toBeVisible();+ await treeAtRest(page);+ await lengthenGlide(page, RECORDED_GLIDE_MS);+ const {below, group} = parts(page);+ // The compositor's own box keeps frames coming while the page is held.+ const control = await startBusyControl(page);+ const cast = await startScreencast(page);+ await expect+ .poll(() => cast.frameCount(), {+ message: 'the screencast delivers frames',+ timeout: 5000,+ })+ .toBeGreaterThan(0);+ // The page holds its main thread from nine tenths of the glide to past its+ // end, like a long task as a collapse ends.+ const blocked = blockMainThread(page, TAIL_BLOCK_MS, {+ during: below,+ minProgressMs: RECORDED_GLIDE_MS * 0.9,+ });+ await tapToggle(page);+ const block = await blocked;+ await treeAtRest(page);+ await expect(group).toHaveCount(0);+ // One more frame once the tree rests, while the control still moves.+ const atRest = cast.frameCount();+ await expect+ .poll(() => cast.frameCount(), {+ message: 'a frame of the tree at rest',+ timeout: 5000,+ })+ .toBeGreaterThan(atRest);+ const frames = await cast.stop();+ await control.remove();+ // The glide ends at most a tenth of it after the block begins. Each frame+ // two frames past that, while the page is held, is judged.+ const ended = block.from + RECORDED_GLIDE_MS * 0.1 + 34;+ const held = requireFrames(frames, {+ min: 3,+ during: 'the page is held past the end of the glide',+ where: frame => frame.t > ended && frame.t < block.to,+ });+ // Each held frame draws the tree as its frame at rest does: the rows below+ // at their place, no leaving row, the chevron turned.+ const box = await page.locator('[role="tree"]').boundingBox();+ if (box == null) {+ throw new Error('the tree has no box');+ }+ const off = await inkOffRest(page, held, frames[frames.length - 1], box);+ for (const [index, count] of off.entries()) {+ expect(+ count,+ JSON.stringify({frame: Math.round(held[index].t - block.from), off}),+ ).toBe(0);+ }+});+test('collapse under a finger: no row of the tree paints past its bottom edge onto the content after it', async ({page,}) => {diff --git a/packages/core/src/motion/animatedLayout.presented.test.ts b/packages/core/src/motion/animatedLayout.presented.test.tsindex 2c603638d9..9a69269d97 100644--- a/packages/core/src/motion/animatedLayout.presented.test.ts+++ b/packages/core/src/motion/animatedLayout.presented.test.ts@@ -6,7 +6,10 @@* Element.animate and stubbed layout rectangles (jsdom lays nothing out)* @output Checks that a running translate glide reports its element to the* presented hit-test registry. The cases cover its offset from where iOS- * WebKit hit-tests it, a touch-down's resolve and its end. A change's+ * WebKit hit-tests it, a touch-down's resolve and its end. Each motion+ * resolves once more as it settles: a glide, an inert element's, a reveal+ * that rides a glide and an indicator's transition. A cancelled or removed+ * one never does. A change's* glides cost one notice as they start and one as they end, even after a* glide in a removed frame ended. A fade or an inert element reports* nothing, and a glide whose element left its document loses its report@@ -16,6 +19,7 @@import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {+ applyLayoutChangeTransition,createAnimatedLayout,playLayoutChange,reportLayoutChange,@@ -41,12 +45,18 @@ interface Played {let played: Played[] = [];let media: Record<string, boolean> = {};+/** Animations get an effect a ride can replace frames on, when set. */+let withEffects = false;+/** Each element's animation start, when a test sets one. */+let startTimes = new Map<Element, number>();const originalAnimate = Element.prototype.animate;const originalMatchMedia = window.matchMedia;beforeEach(() => {played = [];media = {};+ withEffects = false;+ startTimes = new Map();Element.prototype.animate = function (this: Element,keyframes: Keyframe[] | PropertyIndexedKeyframes | null,@@ -54,12 +64,26 @@ beforeEach(() => {) {const cancel = vi.fn();const listeners: Record<string, (() => void)[]> = {};+ const timing = {...(options as KeyframeAnimationOptions)};+ const effect = {+ frames: keyframes as Keyframe[],+ setKeyframes(next: Keyframe[]) {+ effect.frames = next;+ },+ updateTiming(next: KeyframeAnimationOptions) {+ Object.assign(timing, next);+ },+ getTiming: () => timing,+ getKeyframes: () => effect.frames,+ };const animation = {cancel,addEventListener(type: string, listener: () => void) {(listeners[type] ??= []).push(listener);},currentTime: 100,+ startTime: startTimes.get(this) ?? null,+ ...(withEffects ? {effect} : {}),};played.push({element: this,@@ -353,6 +377,323 @@ describe('a glide in the presented hit-test registry (motion/presentation.ts)',expect(presentedElements().includes(b)).toBe(false);});+ /** Frames the page asks for, run on demand. */+ function holdFrames() {+ const queued: FrameRequestCallback[] = [];+ const realFrame = window.requestAnimationFrame.bind(window);+ const spy = vi+ .spyOn(window, 'requestAnimationFrame')+ .mockImplementation(callback => {+ queued.push(callback);+ return queued.length;+ });+ return {+ run: () => {+ for (const callback of queued.splice(0)) {+ callback(window.performance.now());+ }+ },+ pending: () => queued.length,+ /** Waits for `count` real frames; a page that draws none fails by name. */+ real: async (count: number) =>+ new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ reject(new Error(`holdFrames: ${count} real frames did not come`));+ }, 5000);+ let left = count;+ const tick = () => {+ left -= 1;+ if (left > 0) {+ realFrame(tick);+ return;+ }+ clearTimeout(timer);+ resolve();+ };+ realFrame(tick);+ }),+ /** Hands frames still asked for back to the real clock, so no loop dies. */+ restore: () => {+ spy.mockRestore();+ for (const callback of queued.splice(0)) {+ realFrame(callback);+ }+ },+ };+ }++ /** The glide's time from which it is drawn within 0.5 px of its place, ms. */+ const settleTime = (glide: Played) => {+ const ys = glide.keyframes.map(frame =>+ Math.abs(translateOf({...glide, keyframes: [frame]}).y),+ );+ let from = ys.length - 1;+ while (from > 0 && ys[from - 1] <= 0.5) {+ from -= 1;+ }+ const offset = glide.keyframes[from].offset ?? from / (ys.length - 1);+ return offset * Number(glide.options.duration);+ };++ /** A glide on row a, its frames held, and its time a test can set. */+ async function settlingGlide(rowHtml = '<div id="a"></div>') {+ // Two real frames first: a loop an earlier test left ends, so this+ // glide's loop starts on the held frames.+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ const frames = holdFrames();+ const {area, changed, phase} = setUp(+ `<div id="area"><div id="changed"></div>${rowHtml}</div>`,+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const glide = played.find(p => p.element === a) as Played;+ // The change's other motions end, so only this glide waits for a frame.+ for (const entry of played) {+ if (entry !== glide) {+ entry.finish?.();+ }+ }+ const timing = glide.animation as {currentTime: number};+ const settles = settleTime(glide);+ const written = () => a.style.getPropertyValue('--astryx-presented');+ return {a, frames, glide, timing, settles, written};+ }++ it('resolves once more in the first frame its glide is drawn within half a pixel of its place, so WebKit draws its last frame there', async () => {+ const {a, frames, glide, timing, settles, written} = await settlingGlide();+ const now = window.performance.now();+ const clock = vi.spyOn(window.performance, 'now').mockReturnValue(now);+ try {+ expect(settles).toBeGreaterThan(0);+ expect(settles).toBeLessThan(Number(glide.options.duration));+ // Drawn at its settle point, far from where the glide started, which+ // is where the engine hit-tests it until a resolve.+ (glide.animation as {startTime: number}).startTime = now - settles;+ expect(Math.abs(presentedOffsetOf(a).y)).toBeGreaterThan(10);+ // Short of that keyframe: no write, and the frame loop keeps reading.+ timing.currentTime = settles - 1;+ frames.run();+ expect(written()).toBe('');+ expect(frames.pending()).toBeGreaterThan(0);+ // The frame that reaches it writes once, the engine hit-tests it where+ // it is drawn, and the loop stops.+ timing.currentTime = settles;+ frames.run();+ const write = written();+ expect(write).not.toBe('');+ expect(presentedOffsetOf(a).y).toBeCloseTo(0, 6);+ timing.currentTime = settles + 50;+ frames.run();+ frames.run();+ expect(written()).toBe(write);+ expect(frames.pending()).toBe(0);+ } finally {+ clock.mockRestore();+ frames.restore();+ }+ });++ it('writes nothing for a glide cancelled before it settles, and stops reading its time', async () => {+ const {frames, glide, timing, settles, written} = await settlingGlide();+ try {+ timing.currentTime = settles - 1;+ frames.run();+ glide.cancelled?.();+ frames.run();+ frames.run();+ expect(frames.pending()).toBe(0);+ // Its time passing later writes nothing, from the held frames or from+ // a real frame loop, which three real frames let run.+ timing.currentTime = settles + 10;+ frames.run();+ await frames.real(3);+ frames.run();+ expect(written()).toBe('');+ } finally {+ frames.restore();+ }+ });++ it('writes nothing for a glide whose element leaves the document before it settles', async () => {+ const {a, frames, timing, settles, written} = await settlingGlide();+ try {+ timing.currentTime = settles - 1;+ frames.run();+ a.remove();+ timing.currentTime = settles + 10;+ frames.run();+ frames.run();+ expect(written()).toBe('');+ expect(frames.pending()).toBe(0);+ } finally {+ frames.restore();+ }+ });++ it("resolves an inert element's glide too, which reports nothing, and clears the write at its end", async () => {+ const {a, frames, glide, timing, settles, written} = await settlingGlide(+ '<div id="a" inert></div>',+ );+ try {+ expect(presentedElements().includes(a)).toBe(false);+ timing.currentTime = settles;+ frames.run();+ expect(written()).not.toBe('');+ glide.finish?.();+ expect(written()).toBe('');+ frames.run();+ expect(frames.pending()).toBe(0);+ } finally {+ frames.restore();+ }+ });++ it("resolves an indicator's transition once as it settles, read from the page's clock alone, and clears it at its end", async () => {+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ const frames = holdFrames();+ let start = 0;+ let elapsed = 0;+ const clock = vi+ .spyOn(window.performance, 'now')+ .mockImplementation(() => start + elapsed);+ try {+ const {area} = setUp(+ '<div id="area"><div id="changed"></div><span id="chevron"></span></div>',+ );+ const chevron = document.getElementById('chevron') as HTMLElement;+ const layout = createAnimatedLayout(() => area);+ applyLayoutChangeTransition(layout, chevron);+ const duration = Number.parseFloat(chevron.style.transitionDuration);+ expect(duration).toBeGreaterThan(0);+ // A start from which the end time, less the start, rounds short of the+ // duration, as a coarsened clock can land. A frame at the end ends it.+ start = 1000.1;+ for (let tries = 0; start + duration - start >= duration; tries += 1) {+ expect(tries).toBeLessThan(1000);+ start += 0.1;+ }+ applyLayoutChangeTransition(layout, chevron);+ const written = () =>+ chevron.style.getPropertyValue('--astryx-presented');+ // Before its curve comes within reach of its end: no write.+ elapsed = duration / 4;+ frames.run();+ expect(written()).toBe('');+ // Past its settle point: one write, and the loop keeps reading.+ elapsed = duration * 0.95;+ frames.run();+ expect(written()).not.toBe('');+ expect(frames.pending()).toBeGreaterThan(0);+ // In the frame at its end, the write goes and the loop stops.+ elapsed = duration;+ frames.run();+ expect(written()).toBe('');+ frames.run();+ expect(frames.pending()).toBe(0);+ } finally {+ clock.mockRestore();+ frames.restore();+ }+ });++ /** When `keyframes` over `duration` ms come within the record's reach. */+ const settleOf = (keyframes: ReadonlyArray<Keyframe>, duration: number) => {+ const numbers = (value: Keyframe[string]) =>+ [+ ...String(value ?? '').matchAll(/(-?[\d.]+(?:e[+-]?\d+)?)([a-z%]*)/gi),+ ].map(([, at, unit]) => ({at: Number(at), unit}));+ const last = keyframes[keyframes.length - 1];+ const styles = Object.keys(last).filter(+ key => !['offset', 'computedOffset', 'easing', 'composite'].includes(key),+ );+ const isNear = (frame: Keyframe) =>+ styles.every(key => {+ const ends = numbers(last[key]);+ return numbers(frame[key]).every(+ ({at, unit}, index) =>+ Math.abs(at - ends[index].at) <=+ (unit === 'px' || unit === '%' ? 0.5 : 0.005),+ );+ });+ let from = keyframes.length - 1;+ while (from > 0 && isNear(keyframes[from - 1])) {+ from -= 1;+ }+ return (keyframes[from].offset ?? from / (keyframes.length - 1)) * duration;+ };++ it("retimes the settle of a reveal whose ride replaces its frames: riding a glide that started 200 ms earlier, it resolves at its own ride's settle", async () => {+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ const frames = holdFrames();+ try {+ withEffects = true;+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="changed"></div><div id="a"></div></div>',+ );+ const a = document.getElementById('a') as HTMLElement;+ placeAt(a, {before: [0, 0, 400, 40], after: [0, 80, 400, 40]}, phase);+ // The row below glides from 200 ms before the reveal starts, as a glide+ // an earlier change started does.+ startTimes.set(a, -200);+ startTimes.set(changed, 0);+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const reveal = played.find(p => p.element === changed) as Played;+ const effect = (+ reveal.animation as {+ effect: {+ frames: Keyframe[];+ getTiming: () => KeyframeAnimationOptions;+ };+ }+ ).effect;+ const ridden = Number(effect.getTiming().duration);+ // The ride is the rest of the glide: shorter than the reveal's own curve.+ expect(ridden).toBe(Number(reveal.options.duration) - 200);+ expect(effect.frames).not.toBe(reveal.keyframes);+ const own = settleOf(reveal.keyframes, Number(reveal.options.duration));+ const settles = settleOf(effect.frames, ridden);+ expect(settles).toBeLessThan(own);+ // The change's other motions end, so only the reveal waits.+ for (const entry of played) {+ if (entry !== reveal) {+ entry.finish?.();+ }+ }+ const timing = reveal.animation as {currentTime: number};+ const written = () =>+ changed.style.getPropertyValue('--astryx-presented');+ timing.currentTime = settles - 1;+ frames.run();+ expect(written()).toBe('');+ // Its ride's settle frame writes, before the ride ends.+ timing.currentTime = settles;+ frames.run();+ expect(written()).not.toBe('');+ expect(settles).toBeLessThan(ridden);+ reveal.finish?.();+ expect(written()).toBe('');+ frames.run();+ expect(frames.pending()).toBe(0);+ } finally {+ frames.restore();+ }+ });+it('removes the report of a glide whose element left the document before it ended', async () => {const {area, changed, phase} = setUp('<div id="area"><div id="changed"></div><div id="a"></div><div id="b"></div></div>',diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex e6449a649b..3dc9adbb2d 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -339,6 +339,261 @@ function translatesOf(return points.length > 0 ? points : null;}+/** How near its end, px or percent, an animated value counts as there. */+const SETTLED_PX = 0.5;++/** How near its end an animated value with no unit, an opacity, counts. */+const SETTLED_RATIO = 0.005;++/** Keyframe members that time a keyframe rather than style it. */+const KEYFRAME_TIMING = new Set([+ 'offset',+ 'computedOffset',+ 'easing',+ 'composite',+]);++type KeyframeValue = string | number | null | undefined;++/** Whether a CSS value is within the settle tolerance of `end`. */+function isNearEnd(value: KeyframeValue, end: KeyframeValue): boolean {+ const numbers = (text: KeyframeValue) => [+ ...String(text ?? '').matchAll(/(-?\d*\.?\d+(?:e[+-]?\d+)?)([a-z%]*)/gi),+ ];+ const ats = numbers(value);+ const ends = numbers(end);+ return (+ ats.length === ends.length &&+ ats.every(([, at, unit], index) => {+ const tolerance = ['px', '%'].includes(unit.toLowerCase())+ ? SETTLED_PX+ : SETTLED_RATIO;+ return Math.abs(Number(at) - Number(ends[index][1])) <= tolerance;+ })+ );+}++/**+ * The offset from which linear `keyframes` stay near their last one, or null+ * when only the last one is.+ */+function settledOffset(keyframes: ReadonlyArray<Keyframe>): number | null {+ const last = keyframes[keyframes.length - 1];+ if (last == null) {+ return null;+ }+ const styles = Object.keys(last).filter(key => !KEYFRAME_TIMING.has(key));+ let from: number | null = null;+ for (let index = keyframes.length - 2; index >= 0; index -= 1) {+ const frame = keyframes[index];+ if (!styles.every(key => isNearEnd(frame[key], last[key]))) {+ break;+ }+ from = frame.offset ?? index / (keyframes.length - 1);+ }+ return from;+}++/**+ * When an animation's sampled linear frames come within reach of their end,+ * ms, or null. An eased two-keyframe fade, the Reduce Motion one, has none:+ * WebKit draws its end values at its end.+ */+function settleTime(+ keyframes: ReadonlyArray<Keyframe>,+ timing: KeyframeAnimationOptions,+): number | null {+ const duration = Number(timing.duration);+ const fraction =+ (timing.easing ?? 'linear') === 'linear' ? settledOffset(keyframes) : null;+ return fraction == null || !(duration > 0)+ ? null+ : (timing.delay ?? 0) + fraction * duration;+}++interface Settling {+ readonly element: Element;+ /** Reads one frame; true once it needs no more frames. */+ readonly frame: () => boolean;+}++/** Each window's motions that have not settled yet, read once a frame. */+const settling = new WeakMap<Window, Set<Settling>>();++/**+ * Reads `entry` in each frame until it is done or its element leaves its+ * document. One frame loop per window runs while any motion waits. Returns+ * the stop.+ */+function watchSettle(view: Window, entry: Settling): () => void {+ if (typeof view.requestAnimationFrame !== 'function') {+ return () => {};+ }+ let waiting = settling.get(view);+ if (waiting == null) {+ const entries = new Set<Settling>();+ waiting = entries;+ settling.set(view, entries);+ const frame = () => {+ for (const next of entries) {+ if (!next.element.isConnected || next.frame()) {+ entries.delete(next);+ }+ }+ if (entries.size === 0) {+ settling.delete(view);+ return;+ }+ view.requestAnimationFrame(frame);+ };+ view.requestAnimationFrame(frame);+ }+ const entries = waiting;+ entries.add(entry);+ return () => {+ entries.delete(entry);+ };+}++/** Each running animation's retime, for a ride that replaces its frames. */+const settleRetimes = new WeakMap<+ Animation,+ (keyframes: ReadonlyArray<Keyframe>, durationMs: number) => void+>();++/**+ * WebKit can draw a compositor animation's last frame with the values it last+ * resolved for the element (presentation.ts). Every frame of a long task over+ * its end can show them too. It resolved them at the start or at a later+ * style write. One resolve once the animation is drawn near its end makes that+ * frame its end. `onResolve` hears it, for a reported glide's hit test.+ * Review condition: re-measure on each WebKit release, and remove these+ * resolves once WebKit draws an ended compositor animation at its final+ * values.+ */+function settleAnimation(+ element: Element,+ animation: Animation,+ keyframes: ReadonlyArray<Keyframe>,+ options: KeyframeAnimationOptions,+ onResolve?: () => void,+): void {+ const view = element.ownerDocument.defaultView;+ if (view == null || !('style' in element)) {+ return;+ }+ const styled = element as Element & ElementCSSInlineStyle;+ let at = settleTime(keyframes, options);+ let isWritten = false;+ settleRetimes.set(animation, (next, durationMs) => {+ at = settleTime(next, {...options, duration: durationMs});+ });+ const stop = watchSettle(view, {+ element,+ frame: () => {+ if (at == null) {+ return true;+ }+ // The engine's own time when it has one; otherwise the clock against+ // the settle's moment, which a subtraction would round short of.+ const isSettled =+ animation.currentTime != null+ ? Number(animation.currentTime) >= at+ : animation.startTime != null &&+ view.performance.now() >= Number(animation.startTime) + at;+ if (!isSettled) {+ return false;+ }+ writePresentedResolve(styled);+ isWritten = true;+ onResolve?.();+ return true;+ },+ });+ // A reported glide's report clears its write; any other clears at its end.+ const end = () => {+ stop();+ settleRetimes.delete(animation);+ if (isWritten && onResolve == null) {+ clearPresentedResolve(styled);+ }+ };+ animation.addEventListener?.('finish', end);+ animation.addEventListener?.('cancel', end);+}++/** Retimes `animation`'s settle after a ride replaced its frames. */+function retimeSettle(+ animation: Animation,+ keyframes: ReadonlyArray<Keyframe>,+ durationMs: number,+): void {+ settleRetimes.get(animation)?.(keyframes, durationMs);+}++/** Each indicator's settle, stopped when the next change retimes it. */+const transitionSettles = new WeakMap<Element, () => void>();++/**+ * An indicator's CSS transition runs on the compositor too, so it resolves+ * once as it settles. Its time is read from the page's clock from now, when+ * the change starts it: reading the transition itself would flush style.+ */+function settleTransition(+ element: HTMLElement | SVGElement,+ progress: GlideProgress,+): void {+ transitionSettles.get(element)?.();+ transitionSettles.delete(element);+ const view = element.ownerDocument.defaultView;+ const {durationMs} = progress;+ // The first sample from which its curve stays near its end.+ const count = sampleCount(durationMs);+ let settled: number | null = null;+ for (let index = count - 2; index >= 0; index -= 1) {+ const at = (index / (count - 1)) * durationMs;+ if (Math.abs(progress.remaining(at)) > SETTLED_RATIO) {+ break;+ }+ settled = at;+ }+ if (view == null || settled == null || !(durationMs > 0)) {+ return;+ }+ // Its moments on the clock, so a frame that lands on one counts: a+ // subtraction from the frame's time can round short of it.+ const start = view.performance.now();+ const settleAt = start + settled;+ const endAt = start + durationMs;+ let isWritten = false;+ const stop = watchSettle(view, {+ element,+ frame: () => {+ const now = view.performance.now();+ if (!isWritten && now >= settleAt) {+ writePresentedResolve(element);+ isWritten = true;+ }+ if (now < endAt) {+ return false;+ }+ clear();+ return true;+ },+ });+ const clear = () => {+ transitionSettles.delete(element);+ if (isWritten) {+ clearPresentedResolve(element);+ isWritten = false;+ }+ };+ transitionSettles.set(element, () => {+ stop();+ clear();+ });+}+/*** Reports `element` to the presented hit-test registry while its `translate`* glide runs. iOS WebKit hit-tests the element where the glide started. So@@ -352,7 +607,7 @@ function presentGlide(keyframes: Keyframe[],options: KeyframeAnimationOptions,scale: {readonly x: number; readonly y: number},-): void {+): (() => void) | undefined {const view = element.ownerDocument.defaultView;const durationMs = Number(options.duration);const points =@@ -366,7 +621,7 @@ function presentGlide(!('style' in element) ||element.closest('[inert]') != null) {- return;+ return undefined;}const styled = element as Element & ElementCSSInlineStyle;const now = () => view.performance.now();@@ -440,6 +695,12 @@ function presentGlide(};animation.addEventListener?.('finish', end);animation.addEventListener?.('cancel', end);+ // Its settle's resolve moves where the engine hit-tests it, as a touch's.+ return () => {+ if (!isEnded && presentedGlides.get(element) === glide) {+ hitTested = drawnAt(now());+ }+ };}/**@@ -493,9 +754,11 @@ function safeAnimate(});}}- if (options.pseudoElement == null) {- presentGlide(element, animation, keyframes, options, scale);- }+ const onResolve =+ options.pseudoElement == null+ ? presentGlide(element, animation, keyframes, options, scale)+ : undefined;+ settleAnimation(element, animation, keyframes, options, onResolve);return animation;}@@ -2180,8 +2443,10 @@ function rideNeighbour(: offset.y - moved.y),);};- effect.setKeyframes(sampleOver(durationMs, t => frame(hidden(t))));+ const frames = sampleOver(durationMs, t => frame(hidden(t)));+ effect.setKeyframes(frames);effect.updateTiming?.({duration: durationMs});+ retimeSettle(animation, frames, durationMs);onRide(hidden, durationMs);});}@@ -2224,10 +2489,12 @@ function rideEdge(// on one clock.for (const slide of motion.slides) {const effect = slide.effect as KeyframeEffect | null;- effect?.setKeyframes?.(- sampleOver(durationMs, t => slideFrame(edge, hiddenAt(t))),+ const frames = sampleOver(durationMs, t =>+ slideFrame(edge, hiddenAt(t)),);+ effect?.setKeyframes?.(frames);effect?.updateTiming?.({duration: durationMs});+ retimeSettle(slide, frames, durationMs);}},);@@ -3752,12 +4019,14 @@ export function applyLayoutChangeTransition(}const area = handle == null ? null : areaOf(handle, element);if (area == null) {+ transitionSettles.get(element)?.();element.style.removeProperty('transition-duration');element.style.removeProperty('transition-timing-function');return;}const motion = layoutMotion(area);if (motion.kind !== 'glide') {+ transitionSettles.get(element)?.();element.style.setProperty('transition-duration', '0s');element.style.removeProperty('transition-timing-function');return;@@ -3770,6 +4039,7 @@ export function applyLayoutChangeTransition('transition-timing-function',motion.progress.easing,);+ settleTransition(element, motion.progress);}/**