An open source design system that's fully customizable and agent ready
TypeScript
perf(SnapPaging): a settle samples its curve once, not once per item (#10568)
Christopher Chedeau2d7a3bcb90d5
diff --git a/.changeset/snap-paging-settle-copies.md b/.changeset/snap-paging-settle-copies.mdnew file mode 100644index 0000000000..45c03a6ea5--- /dev/null+++ b/.changeset/snap-paging-settle-copies.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Under snap paging, a Carousel's release bakes the settle's keyframes once, not once per item, and plays the settle only on the items that can show. With 9 items the release takes about a third less main-thread time, and with 30 items about two thirds less.++@vjeuxdiff --git a/apps/storybook/stories/Carousel.stories.tsx b/apps/storybook/stories/Carousel.stories.tsxindex 8d078cfd5f..307545b75b 100644--- a/apps/storybook/stories/Carousel.stories.tsx+++ b/apps/storybook/stories/Carousel.stories.tsx@@ -501,10 +501,12 @@ function PagingCarousel({layout,count,mode,+ hasLoop = false,}: {layout: '1-up' | '3-up';count: number;mode: PagingMode;+ hasLoop?: boolean;}) {// One value: Carousel keeps the value it first attached, and a new `pages`// applies from the next flick.@@ -514,6 +516,7 @@ function PagingCarousel({<div {...stylex.props(styles.pagingFrame)}><Carouselgap={layout === '1-up' ? 0 : 2}+ hasLoop={hasLoop}hasSnap={hasSnap}aria-label="Numbered items">{Array.from({length: count}, (_, i) => (@@ -541,7 +544,7 @@ const pagingArgTypes = {},};-type PagingStory = StoryObj<{mode: PagingMode}>;+type PagingStory = StoryObj<{mode: PagingMode; hasLoop?: boolean}>;export const SnapPagingOneUp: PagingStory = {name: 'Snap Paging: One Item per View',@@ -554,7 +557,9 @@ export const SnapPagingThreeUp: PagingStory = {name: 'Snap Paging: Three Items per View',argTypes: pagingArgTypes,args: {mode: 'paging'},- render: ({mode}) => <PagingCarousel layout="3-up" count={9} mode={mode} />,+ render: ({mode, hasLoop}) => (+ <PagingCarousel layout="3-up" count={9} mode={mode} hasLoop={hasLoop} />+ ),};export const SnapPagingPartialLastPage: PagingStory = {diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.tsindex 516e80e996..95dfa96023 100644--- a/packages/core/src/SnapPaging/SnapPaging.ts+++ b/packages/core/src/SnapPaging/SnapPaging.ts@@ -16,7 +16,11 @@ import {useRef, useState} from 'react';import {createPager, type PagerAnimator} from '../hooks/usePager';import {isRtlElement} from '../hooks/isRtlElement';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';-import {animatorFor, type MotionHandle} from '../motion/animator';+import {+ animatorFor,+ type MotionCurve,+ type MotionHandle,+} from '../motion/animator';import {observeMutations} from '../utils/sharedMutationObserver';import {observeResize} from '../utils/sharedResizeObserver';import {@@ -95,6 +99,13 @@ function viewPages(return pages;}+/**+ * How often a settle's curve is read to find how far it moves the row. Its+ * extremes lie at its ends, which are read exactly, or where it turns and+ * moves slowly.+ */+const SHOWS_SAMPLES_PER_S = 120;+/** One handle for the same motion on every child. */function combined(handles: ReadonlyArray<MotionHandle>): MotionHandle {const [lead] = handles;@@ -140,6 +151,13 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {let heldWidth = 0;// The row's own inline snap type, back at the hand-back.let ownSnapType = '';+ // Each child's start and end along the row, in the position's terms, and+ // the row's outer width, read at the takeover.+ let spans: {start: number; end: number}[] = [];+ let heldOuterWidth = 0;+ // The children the running settle leaves out. Each keeps the translate it+ // had when the settle began.+ let leftOut: HTMLElement[] = [];const children = () =>Array.from(element.children).filter((child): child is HTMLElement => child instanceof HTMLElement,@@ -197,15 +215,52 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {return (end - start) / rowScale(element, element.getBoundingClientRect());}+ // Each child's start and end along the row, in the position's terms, with+ // the row shown at `at`. Every child carries the same translate.+ function spansOf(+ items: ReadonlyArray<HTMLElement>,+ at: number,+ ): {start: number; end: number}[] {+ const box = element.getBoundingClientRect();+ const scale = rowScale(element, box);+ const rtl = isRtl();+ return items.map(child => {+ const rect = child.getBoundingClientRect();+ const start =+ (rtl ? box.right - rect.right : rect.left - box.left) / scale + at;+ return {start, end: start + rect.width / scale};+ });+ }++ // A child the settle left out takes the lead's translate before a+ // measure. Its box then reads as the other children's do.+ function alignLeftOut(): void {+ const first = children()[0];+ if (leftOut.length === 0 || first == null) {+ return;+ }+ const x = animatorFor(first).get('x');+ for (const child of leftOut) {+ const animator = animatorFor(child);+ if (animator.get('x') !== x) {+ animator.set({x});+ }+ }+ leftOut = [];+ }+// A resize while the row is held moves its travel with the row's width and// the children's span. A frame of the hold reads the result, not the row.function remeasure(): void {if (!isMoving) {return;}+ alignLeftOut();const nextSpan = span();const nextWidth = element.clientWidth;const native = nativePosition();+ spans = spansOf(children(), position());+ heldOuterWidth = element.offsetWidth;// WebKit truncates a fractional scroll offset, so the travel stays a whole// number of pixels, as the scroll width is. It rounds once, from the// takeover, so a resize over many frames adds up no rounding.@@ -237,6 +292,7 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {}function stops(): number[] {+ alignLeftOut();return pages().stops;}@@ -269,12 +325,15 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {const items = children();const rowSpan = span();const rowWidth = element.clientWidth;+ const itemSpans = spansOf(items, offset);heldOffset = offset;heldTravel = rowTravel;takeoverTravel = rowTravel;heldSpan = rowSpan;heldWidth = rowWidth;heldSign = rowSign;+ heldOuterWidth = element.offsetWidth;+ spans = itemSpans;lead = items[0] ?? null;isMoving = true;// A snap type would snap the row again as its children move.@@ -300,6 +359,7 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {animator.set({x: 0});child.style.removeProperty('translate');}+ leftOut = [];isMoving = false;beforeSnap?.();if (ownSnapType === '') {@@ -315,6 +375,26 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {}}+ // Whether the child at `index` can show in the row's view at any point of+ // the track curve `curve`, read from the curve's own values. A child that+ // cannot keeps its place, and the hand-back places every child.+ function showsDuring(curve: MotionCurve): (index: number) => boolean {+ let from = Infinity;+ let to = -Infinity;+ const steps = Math.max(1, Math.ceil(curve.duration * SHOWS_SAMPLES_PER_S));+ for (let i = 0; i <= steps; i++) {+ const at = -heldSign * curve.at((curve.duration * i) / steps);+ from = Math.min(from, at);+ to = Math.max(to, at);+ }+ return index => {+ const span = spans[index];+ return (+ span == null || (span.end > from && span.start < to + heldOuterWidth)+ );+ };+ }+const animator: PagerAnimator = {get(property, time) {const first = children()[0];@@ -339,6 +419,9 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {for (const child of children()) {animatorFor(child).set(shifted, options);}+ if (values.x != null) {+ leftOut = [];+ }},stop(properties) {if (!isMoving) {@@ -347,6 +430,13 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {for (const child of children()) {animatorFor(child).stop(properties);}+ // Each child's animation stops on its own clock, and a child the+ // settle left out kept its place. Every child of a held row moves to+ // where the lead stopped.+ if (isMoving && (properties == null || properties.includes('x'))) {+ place(position());+ leftOut = [];+ }},play(curves, options) {takeOver();@@ -359,11 +449,20 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {...curves,x: {...x, at: (t: number) => x.at(t) + offset},};- const items = children();- const handles = (items.length > 0 ? items : [element]).map(child =>- animatorFor(child).play(shifted, options),+ const [first, ...rest] = children();+ if (first == null) {+ return animatorFor(element).play(shifted, options);+ }+ // The first child always plays: the row's position is read from it.+ const shows = x == null ? () => true : showsDuring(x);+ const players = [first];+ leftOut = [];+ for (const [index, child] of rest.entries()) {+ (shows(index + 1) ? players : leftOut).push(child);+ }+ return combined(+ players.map(child => animatorFor(child).play(shifted, options)),);- return combined(handles);},};diff --git a/packages/core/src/SnapPaging/__tests__/SnapPagingSettle.interaction.browser.spec.ts b/packages/core/src/SnapPaging/__tests__/SnapPagingSettle.interaction.browser.spec.tsnew file mode 100644index 0000000000..a78bf77105--- /dev/null+++ b/packages/core/src/SnapPaging/__tests__/SnapPagingSettle.interaction.browser.spec.ts@@ -0,0 +1,558 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SnapPagingSettle.interaction.browser.spec.ts+ * @input The built Carousel snap-paging stories, real touch input and edge+ * presses through the interaction harness. A count of the keyframe bakes+ * the page starts, and a per-frame read of each item's translate, its+ * animations and its layer+ * @output Proof that a settle samples its curve once: one element bakes it.+ * Every item that can show plays its own animation, on a layer of its own,+ * from the lead's start and at the lead's translate. That holds through a settle across pages, a touch that catches one,+ * a second press, and a row resized under a held finger. An item out of+ * view through the whole settle gets no animation, and a caught row puts+ * every item at the lead's translate+ * @position Browser proof for snap paging's settle, run by+ * `pnpm test:interaction`+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ drag,+ openStory,+ requireFrames,+ tap,+ touchDriver,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++async function open(page: Page, args: Record<string, string> = {}) {+ await openStory(page, storybook(), 'core-carousel--snap-paging-three-up', {+ mode: 'paging',+ ...args,+ });+ const scroller = page.getByRole('region').getByRole('group').first();+ return {scroller};+}++/**+ * Whether the paging still moves the items: an item carries its translate+ * or runs an animation. A settle from rest can run with no inline translate.+ */+const isTakenOver = async (scroller: Locator) =>+ scroller.evaluate(el =>+ Array.from(el.children).some(+ child =>+ (child as HTMLElement).style.translate !== '' ||+ child.getAnimations().length > 0,+ ),+ );++async function settled(scroller: Locator) {+ await expect+ .poll(async () => isTakenOver(scroller), {+ message: 'the row hands back to native scroll',+ timeout: 2_000,+ })+ .toBe(false);+}++/** A flick toward the row's end: 80 px over 80 ms. */+async function flick(page: Page, scroller: Locator) {+ const box = await scroller.boundingBox();+ if (box == null) {+ throw new Error('no scroller');+ }+ const y = box.y + box.height / 2;+ const from = {x: box.x + box.width / 2 + 40, y};+ const driver = await touchDriver(page);+ await driver.play(drag(from, {x: from.x - 80, y}, {durationMs: 80}));+}++/**+ * Counts the animations `Element.animate` starts on each item from now on,+ * by item index.+ */+async function countAnimates(scroller: Locator) {+ await scroller.evaluate(el => {+ const counts = new Map<number, number>();+ const animate = Element.prototype.animate;+ Element.prototype.animate = function (this: Element, ...args) {+ const index = Array.prototype.indexOf.call(el.children, this);+ if (index >= 0) {+ counts.set(index, (counts.get(index) ?? 0) + 1);+ }+ return animate.apply(this, args);+ };+ (window as unknown as {__animates: Map<number, number>}).__animates =+ counts;+ });+ return async () =>+ scroller.evaluate(() => [+ ...(window as unknown as {__animates: Map<number, number>}).__animates,+ ]);+}++type Frame = {+ readonly t: number;+ readonly kept: boolean;+ readonly position: number;+ readonly running: boolean;+};++type Miss = {frame: number; item: number; x: number; lead: number};++type Watch = {+ frames: Frame[];+ /** An item in view with no animation of its own while the lead settles. */+ missing: Miss[];+ /** An item that animates without a layer of its own. */+ unpromoted: Miss[];+ /** An item that animates from another start than the lead's. */+ late: {frame: number; item: number; start: number; lead: number}[];+ /** An item in view away from the lead's translate. */+ apart: Miss[];+ animated: number[] | null;+ touch: {start: number | null; end: number | null};+};++/**+ * Watches every frame until the row is handed back. While the lead item+ * settles, each item in view, as the lead places it, has its own animation+ * or rests at the settle's end. Each animating item carries its layer and+ * starts when the lead starts. Each item in view sits at the lead's+ * translate.+ * Each frame records where the row shows and whether the lead settles. The+ * watch also records which items had an animation on the settle's first+ * frame, and when a touch went down and lifted.+ */+async function watchShown(scroller: Locator) {+ await scroller.evaluate(el => {+ const log: Watch = {+ frames: [],+ missing: [],+ unpromoted: [],+ late: [],+ apart: [],+ animated: null,+ touch: {start: null, end: null},+ };+ (window as unknown as {__shown: Watch}).__shown = log;+ el.addEventListener(+ 'touchstart',+ () => {+ log.touch.start ??= performance.now();+ },+ {capture: true, passive: true},+ );+ el.addEventListener(+ 'touchend',+ () => {+ log.touch.end = performance.now();+ },+ {capture: true, passive: true},+ );+ const xOf = (child: Element) =>+ Number.parseFloat(getComputedStyle(child).translate) || 0;+ const runningOf = (child: Element) =>+ child+ .getAnimations()+ .find(animation => animation.playState === 'running') ?? null;+ const sample = () => {+ const items = Array.from(el.children);+ const isHeld = items.some(+ child =>+ (child as HTMLElement).style.translate !== '' ||+ child.getAnimations().length > 0,+ );+ if (isHeld) {+ // WebKit reads an accelerated animation at the time of each read, so+ // the lead is read before and after the items. A frame whose lead+ // moved between its two reads is not kept. Every translate is read+ // before any box.+ const before = xOf(items[0]);+ const xs = items.map(xOf);+ const lead = xOf(items[0]);+ const box = el.getBoundingClientRect();+ const kept = Math.abs(lead - before) <= 0.01;+ const settle = runningOf(items[0]);+ const lastFrame = (settle?.effect as KeyframeEffect | null | undefined)+ ?.getKeyframes()+ .at(-1);+ const endX =+ lastFrame == null+ ? null+ : Number.parseFloat(String(lastFrame.translate));+ log.frames.push({+ t: performance.now(),+ kept,+ position: Math.abs(el.scrollLeft) - lead,+ running: settle != null,+ });+ const frame = log.frames.length;+ items.forEach((child, item) => {+ const rect = child.getBoundingClientRect();+ const x = xs[item];+ // Where the item shows if it moves with the lead.+ const left = rect.left + lead - x;+ const isInView = left + rect.width > box.left && left < box.right;+ const own = runningOf(child);+ if (own != null) {+ if (!getComputedStyle(child).willChange.includes('translate')) {+ log.unpromoted.push({frame, item, x, lead});+ }+ const start = Number(own.startTime);+ const leadStart = Number(settle?.startTime);+ if (+ own.startTime != null &&+ settle?.startTime != null &&+ start !== leadStart+ ) {+ log.late.push({frame, item, start, lead: leadStart});+ }+ if (kept && isInView && Math.abs(x - lead) > 0.01) {+ log.apart.push({frame, item, x, lead});+ }+ } else if (kept && isInView) {+ if (endX != null && Math.abs(x - endX) > 0.01) {+ log.missing.push({frame, item, x, lead});+ } else if (endX == null && Math.abs(x - lead) > 0.01) {+ log.apart.push({frame, item, x, lead});+ }+ }+ });+ if (log.animated == null && settle != null) {+ log.animated = items.flatMap((child, item) =>+ child.getAnimations().length > 0 ? [item] : [],+ );+ }+ }+ if (isHeld || log.frames.length === 0) {+ requestAnimationFrame(sample);+ }+ };+ requestAnimationFrame(sample);+ });+ return async () =>+ scroller.evaluate(() => (window as unknown as {__shown: Watch}).__shown);+}++/** Every item the row shows moved with the lead, on a layer of its own. */+function expectInStep(log: Watch) {+ expect(log.missing, JSON.stringify(log.missing.slice(0, 8))).toEqual([]);+ expect(log.unpromoted, JSON.stringify(log.unpromoted.slice(0, 8))).toEqual(+ [],+ );+ expect(log.late, JSON.stringify(log.late.slice(0, 8))).toEqual([]);+ expect(log.apart, JSON.stringify(log.apart.slice(0, 8))).toEqual([]);+}++/**+ * Resolves on the first frame where the lead item's settle runs from the+ * start the browser gave it, or false after 2 s. A settle created in the+ * press's task has no start until a frame commits it. With `moved`, the+ * lead must also show `moved` px of the settle.+ */+async function settleRuns(scroller: Locator, moved = 0) {+ return scroller.evaluate(+ async (el, distance) =>+ new Promise<boolean>(resolve => {+ const lead = el.firstElementChild as HTMLElement;+ const xOf = () =>+ Number.parseFloat(getComputedStyle(lead).translate) || 0;+ const from = xOf();+ const timer = setTimeout(() => resolve(false), 2000);+ const check = () => {+ if (+ lead+ .getAnimations()+ .some(a => a.playState === 'running' && a.startTime != null) &&+ Math.abs(xOf() - from) >= distance+ ) {+ clearTimeout(timer);+ resolve(true);+ } else {+ requestAnimationFrame(check);+ }+ };+ requestAnimationFrame(check);+ }),+ moved,+ );+}++/**+ * Resizes the row's frame by `by` px at the first touch move after the row is+ * held. The returned read says whether the resize ran.+ */+async function resizeWhenHeld(scroller: Locator, by: number) {+ await scroller.evaluate((el, px) => {+ const frame = el.closest('[role="region"]')?.parentElement;+ if (frame == null) {+ throw new Error('no frame');+ }+ const record = window as unknown as {__resized: boolean};+ record.__resized = false;+ el.addEventListener(+ 'touchmove',+ () => {+ const isHeld = Array.from(el.children).some(+ child => (child as HTMLElement).style.translate !== '',+ );+ if (isHeld && !record.__resized) {+ record.__resized = true;+ frame.style.width = `${frame.clientWidth + px}px`;+ }+ },+ {passive: true},+ );+ }, by);+ return async () =>+ scroller.evaluate(+ () => (window as unknown as {__resized: boolean}).__resized,+ );+}++/** A slow drag of `px` toward the row's end, held still before the lift. */+async function hold(page: Page, scroller: Locator, px: number) {+ const box = await scroller.boundingBox();+ if (box == null) {+ throw new Error('no scroller');+ }+ const y = box.y + box.height / 2;+ const from = {x: box.x + box.width / 2 + px / 2, y};+ const driver = await touchDriver(page);+ await driver.play(+ drag(from, {x: from.x - px, y}, {durationMs: 200, restMs: 150}),+ );+}++test('a settle bakes its curve once: only the lead item bakes keyframes', async ({+ page,+}) => {+ const {scroller} = await open(page);+ const animates = await countAnimates(scroller);+ await flick(page, scroller);+ await settled(scroller);+ // Every item that can show plays the settle, and the lead's call bakes+ // its keyframes. The other calls copy them, so none of them calls+ // `animate`.+ expect(await animates()).toEqual([[0, 1]]);+});++test('every item the row shows moves with the lead through a one-view settle, and an item out of view gets no animation', async ({+ page,+}) => {+ const {scroller} = await open(page);+ const shown = await watchShown(scroller);+ await flick(page, scroller);+ await settled(scroller);+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the settle',+ where: frame => frame.kept,+ });+ expectInStep(log);+ // One view on from the start: items 0 to 5 can show; 6 to 8 stay out.+ expect(log.animated).toEqual([0, 1, 2, 3, 4, 5]);+});++test('a press past the last page goes back to the first: every item it sweeps through the view moves with the lead', async ({+ page,+}) => {+ const {scroller} = await open(page, {hasLoop: '!true'});+ const next = page.getByRole('button', {name: 'Scroll right'});+ // Edge presses step about one view each, until the row reaches its end.+ const atEnd = async () =>+ scroller.evaluate(+ el => Math.abs(el.scrollLeft) >= el.scrollWidth - el.clientWidth - 1,+ );+ for (let i = 0; i < 6 && !(await atEnd()); i++) {+ await next.click();+ await settled(scroller);+ }+ expect(await atEnd()).toBe(true);+ const shown = await watchShown(scroller);+ // At the end, the press wraps to the start. Items 3 to 5 show only on the+ // way.+ await next.click();+ await settled(scroller);+ expect(await scroller.evaluate(el => Math.abs(el.scrollLeft))).toBeLessThan(+ 1,+ );+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the settle',+ where: frame => frame.kept,+ });+ expectInStep(log);+ expect(log.animated).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+});++test('a touch that catches the settle stops every item where the lead shows it', async ({+ page,+}) => {+ const {scroller} = await open(page);+ const box = await scroller.boundingBox();+ if (box == null) {+ throw new Error('no scroller');+ }+ const offset = async () => scroller.evaluate(el => Math.abs(el.scrollLeft));+ const next = page.getByRole('button', {name: 'Scroll right'});+ // A press that nothing catches shows where the press's settle ends.+ await next.click();+ await settled(scroller);+ const end = await offset();+ await page.getByRole('button', {name: 'Scroll left'}).click();+ await settled(scroller);+ expect(await offset()).toBeLessThan(1);+ const shown = await watchShown(scroller);+ await next.click();+ // The touch lands once the row shows some of the settle, so where it stops+ // lies strictly between the settle's start and its end.+ expect(await settleRuns(scroller, 4), 'the press starts its settle').toBe(+ true,+ );+ // A still touch stops the move where it shows, by the pager's catch time+ // at the latest. Its lift settles the row on a stop.+ const driver = await touchDriver(page);+ await driver.play(+ tap({x: box.x + box.width / 2, y: box.y + box.height / 2}, {holdMs: 250}),+ );+ await settled(scroller);+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the settle',+ where: frame => frame.kept,+ });+ expectInStep(log);+ // From the catch to the lift, the settle is cancelled. The row stays where+ // the touch stopped it, between the settle's start and its end.+ const {start, end: lift} = log.touch;+ if (start == null || lift == null) {+ throw new Error('the page saw no touch');+ }+ const before = log.frames.filter(frame => frame.t < start).at(-1);+ expect(before?.running, 'the touch lands while the settle runs').toBe(true);+ const held = requireFrames(log.frames, {+ min: 2,+ during: 'the hold after the catch',+ where: frame => frame.t > start + 120 && frame.t < lift,+ });+ for (const frame of held) {+ expect(frame.running, 'the catch cancels the settle').toBe(false);+ expect(frame.position).toBeGreaterThan(1);+ expect(frame.position).toBeLessThan(end - 1);+ }+ expect(+ new Set(held.map(frame => frame.position.toFixed(2))).size,+ 'the row holds still under the touch',+ ).toBe(1);+});++test('a second flick in a settle measures every item where it is drawn, and rests on a view page', async ({+ page,+}) => {+ const {scroller} = await open(page);+ // The three-up story's view pages start at every third item, the last one+ // at the row's end.+ const pages = await scroller.evaluate(el => {+ const items = Array.from(el.children) as HTMLElement[];+ const travel = el.scrollWidth - el.clientWidth;+ return items+ .filter((_, index) => index % 3 === 0)+ .map(item => Math.min(item.offsetLeft - items[0].offsetLeft, travel));+ });+ await flick(page, scroller);+ // The second flick lands once the row shows half of the first settle.+ expect(await settleRuns(scroller, 150), 'the first flick settles').toBe(true);+ await flick(page, scroller);+ await settled(scroller);+ const at = await scroller.evaluate(el => Math.abs(el.scrollLeft));+ expect(+ pages.some(stop => Math.abs(stop - at) < 1),+ JSON.stringify({at, pages}),+ ).toBe(true);+});++test('a second press in a settle moves every item with the lead', async ({+ page,+}) => {+ const {scroller} = await open(page);+ const next = page.getByRole('button', {name: 'Scroll right'});+ const shown = await watchShown(scroller);+ await next.click();+ expect(await settleRuns(scroller), 'the first press starts its settle').toBe(+ true,+ );+ await next.click();+ await settled(scroller);+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the two presses',+ where: frame => frame.kept,+ });+ expectInStep(log);+});++test('a row widened under a held finger: its settle moves every item the wider row shows', async ({+ page,+}) => {+ const {scroller} = await open(page);+ // 90 px wider, the row shows item 4 near the start, which the takeover's+ // view could not.+ const resized = await resizeWhenHeld(scroller, 90);+ const shown = await watchShown(scroller);+ await hold(page, scroller, 80);+ await settled(scroller);+ expect(await resized(), 'the row widens while the finger holds it').toBe(+ true,+ );+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the hold and its settle',+ where: frame => frame.kept,+ });+ expectInStep(log);+ expect(log.animated).toContain(4);+});++test('a row narrowed under a held finger, its items a share of its width: its settle moves every item it shows', async ({+ page,+}) => {+ const {scroller} = await open(page);+ // Items 40 % of the row wide: the narrowing moves every item's start, and+ // item 2 comes into view near the start.+ await scroller.evaluate(el => {+ for (const child of Array.from(el.children)) {+ (child as HTMLElement).style.width = '40%';+ }+ });+ const resized = await resizeWhenHeld(scroller, -100);+ const shown = await watchShown(scroller);+ await hold(page, scroller, 40);+ await settled(scroller);+ expect(await resized(), 'the row narrows while the finger holds it').toBe(+ true,+ );+ const log = await shown();+ requireFrames(log.frames, {+ min: 3,+ during: 'the hold and its settle',+ where: frame => frame.kept,+ });+ expectInStep(log);+ expect(log.animated).toContain(2);+});diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex b370c23743..33ec8e26e9 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -4076,6 +4076,97 @@ describe('play: any closed-form curve', () => {}});+ it('calls in one task that play the same curve share one bake', async () => {+ stubMedia(false, false);+ let reads = 0;+ const curve = {+ duration: 0.4,+ at: (t: number) => {+ reads += 1;+ return 300 * t * t;+ },+ velocity: (t: number) => 600 * t,+ };+ const animators = [0, 1, 2].map(() =>+ createMotionEngine(document.createElement('div'), {+ now: () => clock,+ requestFrame,+ }),+ );+ animators[0].play({x: curve});+ const firstReads = reads;+ animators[1].play({x: curve});+ animators[2].play({x: curve});+ const [first, second, third] = live('translate');+ // The later calls play the first call's keyframes: the curve is sampled+ // once. Each later call reads it only for its own start and end.+ expect(second.keyframes).toBe(first.keyframes);+ expect(third.keyframes).toBe(first.keyframes);+ expect(firstReads).toBeGreaterThan(40);+ expect((reads - firstReads) / 2).toBeLessThanOrEqual(4);+ // A call in a later task bakes again.+ await Promise.resolve();+ const later = createMotionEngine(document.createElement('div'), {+ now: () => clock,+ requestFrame,+ });+ later.play({x: curve});+ expect(live('translate').at(-1)?.keyframes).not.toBe(first.keyframes);+ });++ it('a call whose other values differ keeps its own keyframes, at the shared times', () => {+ stubMedia(false, false);+ let reads = 0;+ const curve = {+ duration: 0.4,+ at: (t: number) => {+ reads += 1;+ return 300 * t * t;+ },+ velocity: (t: number) => 600 * t,+ };+ const plain = createMotionEngine(document.createElement('div'), {+ now: () => clock,+ requestFrame,+ });+ const lifted = createMotionEngine(document.createElement('div'), {+ now: () => clock,+ requestFrame,+ });+ lifted.set({y: 5});+ plain.play({x: curve});+ const firstReads = reads;+ lifted.play({x: curve});+ const [own, other] = live('translate');+ expect(other.keyframes).not.toBe(own.keyframes);+ expect(other.keyframes.map(frame => frame.offset)).toEqual(+ own.keyframes.map(frame => frame.offset),+ );+ for (const [i, frame] of other.keyframes.entries()) {+ const [x, y] = parse(frame.translate);+ expect(x).toBe(parse(own.keyframes[i].translate)[0]);+ expect(y).toBe(5);+ }+ // Its values are read once each, at the times the first call sampled.+ expect(reads - firstReads).toBeLessThan(firstReads);+ });++ it('a curve played and rebased in one task bakes the shifted keyframes', () => {+ const {animator} = setup();+ const curve = {+ duration: 0.4,+ at: (t: number) => 120 * t,+ velocity: () => 120,+ };+ animator.play({x: curve});+ animator.rebase({x: -16});+ // The curve plays 0 to 48. Shifted by -16, it plays -16 to 32.+ const [animation] = live('translate');+ const xs = animation.keyframes.map(frame => parse(frame.translate)[0]);+ expect(xs[0]).toBeCloseTo(-16, 6);+ expect(xs.at(-1)).toBeCloseTo(32, 6);+ });+it('finishes true at its end, false when interrupted', async () => {const {animator} = setup();const done = animator.play({diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 002d2779c3..8fe4e30e07 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -521,6 +521,11 @@ interface Segment {speed(t: number): number;/** Times (ms after the start) where the value jumps; `at` is right-continuous. */readonly jumps: ReadonlyArray<number>;+ /**+ * The curve a `play` call gave, which other calls in its task can share. A+ * segment whose values move from that curve's has none.+ */+ readonly source?: MotionCurve;/** A Reduce Motion fade: an interruption finishes it instead of freezing it. */readonly isFade?: true;readonly owner: HandleState;@@ -784,6 +789,62 @@ function frameTime(frame: number | undefined, clock: () => number): number {return read.time;}+/**+ * What the calls of the running task have baked. A call that plays the same+ * curve objects reuses them: a row of items that one curve moves samples it+ * once. Cleared at the next microtask checkpoint.+ */+interface TaskBakes {+ /** Sample times, from the bake's start, by curve, offset and tolerance. */+ readonly times: {readonly key: unknown[]; readonly times: number[]}[];+ /** Keyframes, by curves, offsets and the channel's rest values. */+ readonly keyframes: {+ readonly key: unknown[];+ readonly keyframes: Keyframe[];+ effect: AnimationEffect | null;+ }[];+}++let taskBakes: TaskBakes | null = null;++function bakesOfTask(): TaskBakes {+ if (taskBakes == null) {+ const bakes: TaskBakes = {times: [], keyframes: []};+ taskBakes = bakes;+ queueMicrotask(() => {+ if (taskBakes === bakes) {+ taskBakes = null;+ }+ });+ }+ return taskBakes;+}++function isSameKey(a: unknown[], b: unknown[]): boolean {+ return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));+}++/** Whether the engine can copy an effect with its parsed keyframes. */+function isCopyable(effect: AnimationEffect | null): effect is KeyframeEffect {+ return (+ typeof KeyframeEffect === 'function' &&+ typeof Animation === 'function' &&+ effect instanceof KeyframeEffect+ );+}++/**+ * Plays a copy of `effect` on `element`, as `element.animate` would play the+ * same keyframes and timing, without parsing them again.+ */+function copyAnimation(effect: KeyframeEffect, element: Element): Animation {+ const copy = new KeyframeEffect(effect);+ copy.target = element;+ const animation = new Animation(copy, element.ownerDocument.timeline);+ animation.play();+ return animation;+}+/** Above this many keyframes the tolerance is relaxed. */const MAX_KEYFRAMES = 1200;/**@@ -1405,6 +1466,62 @@ export function createMotionEngine(}};+ /**+ * What identifies a channel's keyframes across calls of one task: each+ * moving property's curve object, offset and length, and each other+ * property's rest value. Null when a moving property has no shared curve+ * (a spring, a rebase, a jump).+ */+ const taskBakeKey = (+ channel: Channel,+ moving: MotionProperty[],+ from: number,+ end: number,+ devicePixel: number,+ ): unknown[] | null => {+ const key: unknown[] = [channel, end - from, devicePixel];+ for (const property of CHANNELS[channel]) {+ const segment = segments.get(property);+ if (!moving.includes(property)) {+ key.push(property, resting[property]);+ } else if (segment?.source != null && segment.jumps.length === 0) {+ key.push(property, segment.source, segment.start - from);+ key.push(segment.duration);+ } else {+ return null;+ }+ }+ return key;+ };++ /** `sampleTimes`, shared by the calls of a task that play one curve. */+ const sharedSampleTimes = (+ property: MotionProperty,+ from: number,+ end: number,+ tolerance: number,+ ): number[] => {+ const segment = segments.get(property);+ if (segment?.source == null || segment.jumps.length > 0) {+ return sampleTimes(property, from, end, tolerance);+ }+ const key: unknown[] = [+ segment.source,+ segment.start - from,+ segment.duration,+ end - from,+ tolerance,+ ];+ const {times} = bakesOfTask();+ const known = times.find(entry => isSameKey(entry.key, key));+ if (known != null) {+ return known.times.map(t => t + from);+ }+ const sampled = sampleTimes(property, from, end, tolerance);+ times.push({key, times: sampled.map(t => t - from)});+ return sampled;+ };+const sampleTimes = (property: MotionProperty,from: number,@@ -1701,6 +1818,16 @@ export function createMotionEngine(// Read where the keyframes are baked: a page moved to another screen// bakes its next motion for that screen.const devicePixel = 1 / Math.max(1, globalThis.devicePixelRatio || 1);+ // An earlier call of this task that played the same curves from the same+ // offset, over the same rest values, baked these keyframes already.+ const bakeKey =+ pseudoElement == null+ ? taskBakeKey(channel, moving, from, end, devicePixel)+ : null;+ const baked =+ bakeKey == null+ ? undefined+ : bakesOfTask().keyframes.find(bake => isSameKey(bake.key, bakeKey));const collect = (scale: number) => {const times = new Set<number>([from, end]);for (const property of moving) {@@ -1708,61 +1835,76 @@ export function createMotionEngine(SAMPLE_TOLERANCE[property] *scale *(property === 'x' || property === 'y' ? devicePixel : 1);- for (const t of sampleTimes(property, from, end, tolerance)) {+ for (const t of sharedSampleTimes(property, from, end, tolerance)) {times.add(t);}}return times;};- let scale = 1;- let all = collect(scale);- while (all.size > MAX_KEYFRAMES && scale < 64) {- scale *= 2;- all = collect(scale);- }- // Jumps become two keyframes at one offset: the value just before, then- // the value after. A jump on the last frame (fade out, then move) too.- const jumpTimes = new Set<number>();- for (const property of moving) {- const segment = segments.get(property) as Segment;- for (const j of segment.jumps) {- const t = segment.start + j;- if (t > from && t <= end) {- jumpTimes.add(t);- all.add(t);+ const span = end - from + END_HOLD_MS;+ const bakeKeyframes = (): Keyframe[] => {+ let scale = 1;+ let all = collect(scale);+ while (all.size > MAX_KEYFRAMES && scale < 64) {+ scale *= 2;+ all = collect(scale);+ }+ // Jumps become two keyframes at one offset: the value just before,+ // then the value after. A jump on the last frame (fade out, then move)+ // too.+ const jumpTimes = new Set<number>();+ for (const property of moving) {+ const segment = segments.get(property) as Segment;+ for (const j of segment.jumps) {+ const t = segment.start + j;+ if (t > from && t <= end) {+ jumpTimes.add(t);+ all.add(t);+ }}}- }- const times = [...all].sort((a, b) => a - b);- const span = end - from + END_HOLD_MS;- const keyframes: Keyframe[] = [];- for (const t of times) {- const offset = (t - from) / span;- if (jumpTimes.has(t)) {- keyframes.push({+ const times = [...all].sort((a, b) => a - b);+ const frames: Keyframe[] = [];+ for (const t of times) {+ const offset = (t - from) / span;+ if (jumpTimes.has(t)) {+ frames.push({+ offset,+ [channel]: format(channel, p => valueBefore(p, t)),+ });+ }+ frames.push({offset,- [channel]: format(channel, p => valueBefore(p, t)),+ [channel]: format(channel, p =>+ t >= end ? finalValue(p) : curveAt(p, t),+ ),});}- keyframes.push({- offset,- [channel]: format(channel, p =>- t >= end ? finalValue(p) : curveAt(p, t),- ),+ frames.push({offset: 1, [channel]: format(channel, finalValue)});+ return frames;+ };+ const keyframes = baked?.keyframes ?? bakeKeyframes();+ promote(channel);+ const animation =+ baked != null && isCopyable(baked.effect)+ ? copyAnimation(baked.effect, target)+ : target.animate(keyframes, {+ duration: span,+ // The last keyframes hold the end state (END_HOLD_MS); filling both+ // ways also keeps it where an engine honors the fill on its compositor.+ // The main thread retires the animation once it runs after the end,+ // writing the end inline in that task, so that changes no pixel.+ fill: 'both',+ easing: 'linear',+ ...(pseudoElement != null ? {pseudoElement} : {}),+ });+ if (bakeKey != null && baked == null) {+ bakesOfTask().keyframes.push({+ key: bakeKey,+ keyframes,+ effect: animation.effect,});}- keyframes.push({offset: 1, [channel]: format(channel, finalValue)});- promote(channel);- const animation = target.animate(keyframes, {- duration: span,- // The last keyframes hold the end state (END_HOLD_MS); filling both- // ways also keeps it where an engine honors the fill on its compositor.- // The main thread retires the animation once it runs after the end,- // writing the end inline in that task, so that changes no pixel.- fill: 'both',- easing: 'linear',- ...(pseudoElement != null ? {pseudoElement} : {}),- });if (waiting != null) {// From rest: no start time, so the browser starts the animation when// it commits it (StartGroup); the keyframes are sampled from `from`,@@ -3884,6 +4026,7 @@ export function createMotionEngine(speed: t => curve.velocity(t / 1000),jumps: [],owner,+ source: curve,};}const group = beginGroup(@@ -4154,6 +4297,7 @@ export function createMotionEngine(}replace({...segment,+ source: undefined,target: segment.target + delta,at: t => segment.at(t) + delta,});