An open source design system that's fully customizable and agent ready
TypeScript
perf(core): motions one callback starts read stylesheets in one pass (#10728)
Christopher Chedeaudf4c958ec7d1
diff --git a/.changeset/motion-promotions-one-style-pass.md b/.changeset/motion-promotions-one-style-pass.mdnew file mode 100644index 0000000000..0276d73e13--- /dev/null+++ b/.changeset/motion-promotions-one-style-pass.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Motion: the motions that one callback starts on elements that came in the same task read their stylesheets' `will-change` in one style pass, after the callback. Before, each element forced a style pass of its own: eight for a list whose eight rows glide together.++@vjeuxdiff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.mdindex e499eead78..56b001cb48 100644--- a/docs/specs/components/List/List.spec.md+++ b/docs/specs/components/List/List.spec.md@@ -195,11 +195,7 @@ Consumer migration instructions belong in consumer docs and release notes.listener, state, Effect, or render pass. Deprecation warnings are dev-only.- **PR2 — Motion only where it applies.** FR11 adds no listener, observer,measurement, or animation under a fine pointer, and FR12 measures rows only- with a handle. Every motion runs on transform and opacity. Implementation- gap: where the primary pointer is coarse, a reorder mode move forces one- style pass for each row that glides for the first time. The shared animator- then reads the row's `will-change` (`architecture:react-component-runtime`- INV18).+ with a handle. Every motion runs on transform and opacity.## Accessibility contractdiff --git a/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.tsindex 5d44aa8680..3c2577b3f2 100644--- a/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts+++ b/packages/core/src/List/__tests__/ListReorderMode.interaction.browser.spec.ts@@ -390,16 +390,20 @@ test.describe('with a finger', () => {expect(first.events.has('keydown')).toBe(true);expect(first.rounds).toBeGreaterThan(0);// The reorder's own reads, in the key's move and in its commit, are one- // measurement pass at most. The shared animator reads a row's will-change- // on its first glide, a cost of its own. Two rows glide here for the first- // time, so it adds two passes at most.+ // measurement pass at most. On their first glide, the shared animator+ // reads the rows' stylesheets in one pass of its own, after the callback.+ const isAnimator = (pass: (typeof first.passes)[number]) =>+ pass.sources[0]?.includes('animator') === true;const moves = passesUnder(first.passes, ['step', 'commit']);- const animators = moves.filter(pass =>- pass.sources[0]?.includes('animator'),- );const firstReport = describePasses(first.passes);- expect(moves.length - animators.length, firstReport).toBeLessThanOrEqual(1);- expect(animators.length, firstReport).toBeLessThanOrEqual(2);+ expect(+ moves.filter(pass => !isAnimator(pass)).length,+ firstReport,+ ).toBeLessThanOrEqual(1);+ expect(+ first.passes.filter(isAnimator).length,+ firstReport,+ ).toBeLessThanOrEqual(1);// Once the glides end, a move back over the same rows counts every read.await waitForRest(row(page, 'Inbox'));await waitForRest(row(page, 'Sent'));diff --git a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.tsindex 0810f44360..2648b13fbe 100644--- a/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animator.interaction.browser.spec.ts@@ -1024,6 +1024,58 @@ test('no Layout or Paint runs while it animates', async ({expect(counts.Paint ?? 0).toBe(0);});+test('motions that one callback starts on new elements read their stylesheets in one style pass (architecture:react-component-runtime INV18)', async ({+ page,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'tracing is a Chromium protocol');+ await open(page);+ // Eight rows that one change glides at once, as a list's reorder does,+ // each with a stylesheet reason that its promotion keeps.+ await page.evaluate(async () => {+ const style = document.createElement('style');+ style.textContent =+ '.row { position: absolute; left: 0; width: 40px; height: 8px; background: #36c; will-change: opacity; }';+ document.head.append(style);+ for (let i = 0; i < 8; i++) {+ const row = document.createElement('div');+ row.className = 'row';+ row.style.top = `${120 + i * 12}px`;+ document.body.append(row);+ }+ // A frame lays the rows out, so no style pass waits before the call.+ await new Promise(resolve =>+ requestAnimationFrame(() => setTimeout(resolve, 0)),+ );+ });+ let call = {from: 0, to: 0};+ const trace = await traceRendering(page, async () => {+ call = await page.evaluate(async spring => {+ const from = performance.timeOrigin + performance.now();+ for (const row of document.querySelectorAll<HTMLElement>('.row')) {+ Motion.createMotionEngine(row).animate({x: 60}, {spring});+ }+ // The callback's microtasks run before its task ends.+ await Promise.resolve();+ return {from, to: performance.timeOrigin + performance.now()};+ }, SLOW);+ });+ const counts = countBetween(trace, call.from, call.to);+ const willChange = await page.evaluate(() =>+ [...document.querySelectorAll<HTMLElement>('.row')].map(+ row => row.style.willChange,+ ),+ );+ test.info().annotations.push({+ type: 'style passes in the callback that starts eight motions',+ description: JSON.stringify({counts, willChange}),+ });+ // Each row keeps its stylesheet's reason beside its promotion.+ expect(willChange).toEqual(Array(8).fill('opacity, translate'));+ // One pass reads every stylesheet; a read per row forced a pass per row.+ expect(counts.UpdateLayoutTree ?? 0).toBeLessThanOrEqual(1);+});+test('the calls from rest that one frame commits start at one time, however long the frame callbacks between them run', async ({page,}) => {diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex 406d4aa75d..8343c1bcd4 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -2136,6 +2136,8 @@ describe('promotion: a compositing layer while it moves', () => {const {animator, element} = setup();stylesheet = {'will-change': 'transform, opacity'};animator.animate({y: 40, opacity: 0.5}, {spring: springs.quickChange});+ // The stylesheet's reasons join once the callback's microtasks run.+ await Promise.resolve();expect(element.style.willChange).toBe('transform, translate, opacity');await advance(5000 + PROMOTION_LINGER_MS);expect(element.style.willChange).toBe('');@@ -2186,7 +2188,7 @@ describe('promotion: a compositing layer while it moves', () => {kept.remove();});- it("keeps the stylesheet's will-change when a node read nothing before it moves", () => {+ it("keeps the stylesheet's will-change when a node read nothing before it moves", async () => {// Put back after its read was skipped, a node reads its stylesheet's// reasons when a promotion needs them.stylesheet['will-change'] = 'transform, opacity';@@ -2198,17 +2200,43 @@ describe('promotion: a compositing layer while it moves', () => {});document.body.append(element);animator.set({y: 10});+ await Promise.resolve();expect(element.style.willChange).toBe('transform, opacity, translate');element.remove();});- it("keeps the stylesheet's will-change when an element attached in this task moves at once", () => {+ it("keeps the stylesheet's will-change when an element attached in this task moves at once", async () => {stylesheet['will-change'] = 'transform, opacity';const {animator, element} = setup();animator.animate({y: 100}, {spring: springs.settle});+ await Promise.resolve();expect(element.style.willChange).toBe('transform, opacity, translate');});+ it("reads the stylesheets of the motions one callback starts in one pass once it ends, not between one element's writes and the next's", async () => {+ // A list's reorder glides every row at once, each row's animator new.+ stylesheet['will-change'] = 'opacity';+ const rows = [setup(), setup(), setup()];+ // A bare spring, which reads no theme tempo.+ const spring = {response: 0.3, dampingRatio: 1};+ const readsOf = (node: Element) =>+ vi+ .mocked(window.getComputedStyle)+ .mock.calls.filter(([read]) => read === node).length;+ for (const {animator} of rows) {+ animator.animate({y: 40}, {spring});+ }+ for (const {element} of rows) {+ expect(readsOf(element)).toBe(0);+ expect(element.style.willChange).toBe('translate');+ }+ await Promise.resolve();+ for (const {element} of rows) {+ expect(readsOf(element)).toBe(1);+ expect(element.style.willChange).toBe('opacity, translate');+ }+ });+it('promotes during direct manipulation, until the writes stop', async () => {const {animator, element} = setup();animator.set({y: 10});diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 0d85a9c74e..b692d64ce6 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -803,6 +803,47 @@ function callTime(clock: () => number): number {return time;}+/**+ * Promotions that wait for their stylesheet's will-change, from every+ * animator, until the running callback's microtasks run.+ */+const sheetReads: SheetRead[] = [];++/** One element's wait in sheetReads. */+interface SheetRead {+ /** Takes the promotion off the element, so a read sees its stylesheet. */+ readonly lift: () => void;+ readonly read: () => void;+ /** Writes the promotion back with the stylesheet's reasons. */+ readonly write: () => void;+}++/**+ * Queues an element's stylesheet read for a microtask after the callback.+ * That microtask lifts every queued promotion, reads every stylesheet, and+ * then writes every promotion back. So motions that one callback starts force+ * one style pass, not one per element.+ */+function queueSheetRead(read: SheetRead) {+ if (sheetReads.length === 0) {+ queueMicrotask(flushSheetReads);+ }+ sheetReads.push(read);+}++function flushSheetReads() {+ const reads = sheetReads.splice(0);+ for (const read of reads) {+ read.lift();+ }+ for (const read of reads) {+ read.read();+ }+ for (const read of reads) {+ read.write();+ }+}+/*** 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@@ -1284,6 +1325,8 @@ export function createMotionEngine(let sheetWillChangeRead = false;/** The pending read of sheetWillChange, cancelled with its element. */let sheetReadTimer: ReturnType<typeof setTimeout> | null = null;+ /** The node whose promotion waits in sheetReads for its stylesheet. */+ let sheetReadQueuedFor: HTMLElement | null = null;let demoteTimer: ReturnType<typeof setTimeout> | null = null;/** A pseudo-element is promoted through a custom property on its host. */const promotionProperty =@@ -2359,13 +2402,16 @@ export function createMotionEngine(}if (ownWillChange == null) {ownWillChange = element.style.willChange;- // Without an inline value, the stylesheet's reasons stay alongside the- // promotion's. They were read in the task after the element was- // attached; a promotion that comes first (an element attached in this- // task that moves at once) reads them now.- if (ownWillChange === '' && !sheetWillChangeRead) {- readSheetWillChange(element);- }+ }+ // Without an inline value, the stylesheet's reasons stay alongside the+ // promotion's. They were read in the task after the element was attached.+ // A promotion that comes first (an element attached in this task that+ // moves at once) is written now. Its reasons join it once the callback's+ // microtasks run (queueSheetRead).+ if (ownWillChange === '' && !sheetWillChangeRead) {+ element.style.willChange = [...promoted].join(', ');+ queueSheetReadFor(element);+ return;}const base = ownWillChange !== '' ? ownWillChange : sheetWillChange;const own = base === 'auto' ? '' : base;@@ -2385,6 +2431,41 @@ export function createMotionEngine(sheetWillChangeRead = true;};+ /** Joins the stylesheet's reasons to a promotion once the callback ends. */+ const queueSheetReadFor = (element: HTMLElement) => {+ if (sheetReadQueuedFor === element) {+ return;+ }+ sheetReadQueuedFor = element;+ // Still waiting: the same node, still promoted, with no inline reason.+ const waits = () =>+ sheetReadQueuedFor === element &&+ target === element &&+ promoted.size > 0 &&+ ownWillChange === '';+ queueSheetRead({+ lift: () => {+ if (waits()) {+ element.style.willChange = '';+ }+ },+ read: () => {+ if (waits()) {+ readSheetWillChange(element);+ }+ },+ write: () => {+ if (sheetReadQueuedFor !== element) {+ return;+ }+ sheetReadQueuedFor = null;+ if (target === element && promoted.size > 0) {+ writePromotion(element);+ }+ },+ });+ };+/*** Reads sheetWillChange in a task of its own, so a later promotion reads no* style in its own task. Skipped while a promotion of ours is written,