Skip to content

Commit ed9b75b

Browse files
authored
fix(Spinner): a turning ring wakes the main thread once in 100 turns (#9936)
* fix(Spinner): a turning ring no longer wakes the main thread * test(Spinner): bound the style recalculations; read the pre-tempo duration inside the turn multiplier * fix(Spinner): say the wake comes once in 100 turns
1 parent e5ace7e commit ed9b75b

5 files changed

Lines changed: 108 additions & 27 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[fix] Spinner: a turning ring now wakes the main thread once every 100 turns instead of every turn. In a React app, Chromium recalculated style at the end of each turn, about seven times a second with one ring at a 525 ms turn. The ring looks and turns the same, and reduced motion still slows it to 3 seconds a turn.
6+
7+
@cixzhang

‎packages/core/src/Spinner/Spinner.test.tsx‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
*/
1111

1212
import {describe, it, expect, vi, afterEach} from 'vitest';
13+
import {Profiler} from 'react';
1314
import {render, screen} from '@testing-library/react';
1415
import {Spinner} from './Spinner';
1516
import {InternationalizationProvider} from '../i18n';
@@ -407,15 +408,31 @@ describe('Spinner ring', () => {
407408
expect(declaredValue(rotor(), 'animation-iteration-count')).toBe(
408409
'infinite',
409410
);
410-
// Its keyframes turn it once, by transform and nothing else. (jsdom's
411-
// CSSOM lowercases the name in the rule but not in the at-rule.)
411+
// Its keyframes turn it by whole turns, by transform and nothing else.
412+
// (jsdom's CSSOM lowercases the name in the rule but not in the at-rule.)
412413
const keyframes = new RegExp(
413414
`@keyframes ${name}\\s*\\{([\\s\\S]*?\\})\\s*\\}`,
414415
'i',
415416
).exec(css)?.[1];
416417
expect(keyframes).toMatch(/rotate\(0deg\)/);
417-
expect(keyframes).toMatch(/rotate\(360deg\)/);
418418
expect(keyframes).not.toMatch(/stroke|width|height|top|left/);
419+
// One iteration holds many turns, and its duration is that many periods,
420+
// so each turn still takes one period. Chromium wakes the main thread at
421+
// each iteration boundary while React listens for `animationiteration`.
422+
const endDegrees = Math.max(
423+
...[...(keyframes ?? '').matchAll(/rotate\((\d+)deg\)/g)].map(m =>
424+
Number(m[1]),
425+
),
426+
);
427+
const turns = endDegrees / 360;
428+
expect(Number.isInteger(turns)).toBe(true);
429+
expect(turns).toBeGreaterThanOrEqual(100);
430+
const duration = declaredValue(rotor(), 'animation-duration') ?? '';
431+
expect(duration).toMatch(
432+
new RegExp(
433+
`^calc\\(var\\(--_astryx-pre-tempo-duration-slow-min,.*\\) \\* ${turns}\\)$`,
434+
),
435+
);
419436
// Its own compositing layer from the first frame.
420437
expect(declaredValue(rotor(), 'will-change')).toBe('transform');
421438
// Nothing else in the spinner animates: not the arc, not the track.
@@ -427,6 +444,31 @@ describe('Spinner ring', () => {
427444
expect(css).not.toMatch(/@keyframes[^{]*\{[^}]*stroke-dashoffset/);
428445
});
429446

447+
it('renders once and never again while the ring turns', () => {
448+
vi.useFakeTimers({
449+
toFake: ['requestAnimationFrame', 'setTimeout', 'setInterval'],
450+
});
451+
let renders = 0;
452+
const onRender = () => {
453+
renders += 1;
454+
};
455+
try {
456+
render(
457+
<Profiler id="spinner" onRender={onRender}>
458+
{Array.from({length: 20}, (_, i) => (
459+
<Spinner key={i} data-testid={`spinner-${i}`} />
460+
))}
461+
</Profiler>,
462+
);
463+
expect(renders).toBe(1);
464+
// Ten seconds of frames and timers: the motion is CSS only.
465+
vi.advanceTimersByTime(10_000);
466+
expect(renders).toBe(1);
467+
} finally {
468+
vi.useRealTimers();
469+
}
470+
});
471+
430472
it('keeps the track out of the rotor', () => {
431473
render(<Spinner data-testid="spinner" />);
432474
expect(rotor().contains(circles().arc)).toBe(true);

‎packages/core/src/Spinner/Spinner.tsx‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,14 +211,24 @@ function syncRotationPhase(
211211
// Animation
212212
// =============================================================================
213213

214+
/**
215+
* Full turns in one iteration of the rotation.
216+
*
217+
* Chromium wakes the main thread at each iteration boundary while the
218+
* document listens for `animationiteration`. React listens for it on every
219+
* root. One iteration holds 100 turns, so the wake comes once in 100 turns.
220+
* Each turn is 360 degrees, so the ring looks the same.
221+
*/
222+
const TURNS_PER_ITERATION = 100;
223+
214224
/**
215225
* A `transform` animation runs on the compositor, so the ring keeps turning
216226
* while a script runs. A `stroke-dashoffset` animation would repaint the arc
217227
* on the main thread every frame, so it would stop while a script runs.
218228
*/
219229
const rotation = stylex.keyframes({
220230
'0%': {transform: 'rotate(0deg)'},
221-
'100%': {transform: 'rotate(360deg)'},
231+
'100%': {transform: `rotate(${360 * TURNS_PER_ITERATION}deg)`},
222232
});
223233

224234
// =============================================================================
@@ -307,8 +317,8 @@ const styles = stylex.create({
307317
// broken. The status role and its name still say that work is busy.
308318
animationDuration: {
309319
// The loop reads the duration before a theme's tempo scales it.
310-
default: `var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})`,
311-
'@media (prefers-reduced-motion: reduce)': '3s',
320+
default: `calc(var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']}) * ${TURNS_PER_ITERATION})`,
321+
'@media (prefers-reduced-motion: reduce)': `calc(3s * ${TURNS_PER_ITERATION})`,
312322
},
313323
animationIterationCount: 'infinite',
314324
animationName: rotation,

‎packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts‎

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,25 @@ async function checksums(
132132
}
133133
}
134134

135+
/**
136+
* The time of one turn, in ms, and the turns in one iteration. One iteration
137+
* holds many turns, so the period is the iteration's duration divided by the
138+
* turns its last keyframe makes.
139+
*/
140+
async function turnTiming(
141+
rotor: ReturnType<Page['locator']>,
142+
): Promise<{period: number; turns: number}> {
143+
return rotor.evaluate(element => {
144+
const [animation] = element.getAnimations();
145+
const effect = animation.effect as KeyframeEffect;
146+
const frames = effect.getKeyframes();
147+
const end = String(frames[frames.length - 1].transform);
148+
const degrees = Number(/rotate\((-?[\d.]+)deg\)/.exec(end)?.[1]);
149+
const turns = degrees / 360;
150+
return {period: Number(effect.getTiming().duration) / turns, turns};
151+
});
152+
}
153+
135154
/** The rotor's angle in degrees, from 0 up to 360. */
136155
function angleOf(transform: string): number {
137156
return (parseTransform(transform).rotate + 360) % 360;
@@ -184,48 +203,54 @@ test('the ring keeps turning while a script holds the main thread', async ({
184203
test('turning paints nothing on the main thread', async ({page}) => {
185204
await openSizes(page);
186205
await page.waitForTimeout(200);
187-
// Four rings turn for a second. A paint animation repaints every frame; a
188-
// transform animation paints none.
206+
// Four rings turn for two seconds. A paint animation repaints every frame;
207+
// a transform animation paints none. React listens for
208+
// `animationiteration`, so Chromium recalculates style a few times at each
209+
// iteration boundary. One turn per iteration gives about 14 recalculations
210+
// here. With many turns in one iteration, no boundary occurs, and the bound
211+
// allows only unrelated single recalculations.
189212
const trace = await traceRendering(page, async () =>
190-
page.waitForTimeout(1000),
213+
page.waitForTimeout(2000),
191214
);
192215
expect(trace.paint).toBe(0);
193216
expect(trace.layout).toBe(0);
217+
expect(trace.styleRecalc).toBeLessThanOrEqual(2);
194218
});
195219

196220
test('the arc turns clockwise at a constant rate, once per period', async ({
197221
page,
198222
}) => {
199223
const spinners = await openSizes(page);
200224
const rotor = spinners.first().locator('span[aria-hidden="true"]');
201-
const samples = await rotor.evaluate(element => {
225+
const {period, turns} = await turnTiming(rotor);
226+
const samples = await rotor.evaluate((element, periodMs) => {
202227
const [animation] = element.getAnimations();
203228
animation.pause();
204-
const duration = Number(animation.effect?.getTiming().duration);
205229
const out: {t: number; transform: string}[] = [];
206230
for (let i = 0; i <= 8; i += 1) {
207231
// Inside the period at both ends: 0, P/8 … P − 1 ms.
208-
const t = i === 8 ? duration - 1 : (duration * i) / 8;
232+
const t = i === 8 ? periodMs - 1 : (periodMs * i) / 8;
209233
animation.currentTime = t;
210234
out.push({t, transform: getComputedStyle(element).transform});
211235
}
212236
return {
213-
duration,
237+
duration: Number(animation.effect?.getTiming().duration),
214238
cssDuration: getComputedStyle(element).animationDuration,
215239
easing: animation.effect?.getTiming().easing,
216240
out,
217241
};
218-
});
242+
}, period);
219243
// The period is the `--duration-slow-min` token the theme resolves.
220-
expect(samples.duration).toBeGreaterThan(0);
244+
expect(period).toBeGreaterThan(0);
245+
expect(Number.isInteger(turns) && turns > 1).toBe(true);
221246
expect(Number.parseFloat(samples.cssDuration) * 1000).toBeCloseTo(
222247
samples.duration,
223248
3,
224249
);
225250
expect(samples.easing).toBe('linear');
226251
// Angle = 360 × t / P, clockwise (positive in CSS), at every sample.
227252
for (const {t, transform} of samples.out) {
228-
const expected = ((360 * t) / samples.duration) % 360;
253+
const expected = ((360 * t) / period) % 360;
229254
const actual = angleOf(transform);
230255
const error = Math.min(
231256
Math.abs(actual - expected),
@@ -241,28 +266,27 @@ test('reduced motion slows the ring to 3 s per turn, as before, still clockwise
241266
await page.emulateMedia({reducedMotion: 'reduce'});
242267
const spinners = await openSizes(page);
243268
const rotor = spinners.first().locator('span[aria-hidden="true"]');
244-
const samples = await rotor.evaluate(element => {
269+
const {period} = await turnTiming(rotor);
270+
const samples = await rotor.evaluate((element, periodMs) => {
245271
const [animation] = element.getAnimations();
246272
animation.pause();
247-
const duration = Number(animation.effect?.getTiming().duration);
248273
const out: {t: number; transform: string}[] = [];
249274
for (let i = 0; i < 4; i += 1) {
250-
const t = (duration * i) / 4;
275+
const t = (periodMs * i) / 4;
251276
animation.currentTime = t;
252277
out.push({t, transform: getComputedStyle(element).transform});
253278
}
254279
return {
255-
duration,
256280
iterations: animation.effect?.getTiming().iterations,
257281
out,
258282
};
259-
});
283+
}, period);
260284
// The reduced-motion period this component had before the change: slowed,
261285
// never frozen (`Spinner.tsx`, `animationDuration` under the media query).
262-
expect(samples.duration).toBe(3000);
286+
expect(period).toBeCloseTo(3000, 6);
263287
expect(samples.iterations).toBe(Infinity);
264288
for (const {t, transform} of samples.out) {
265-
const expected = (360 * t) / samples.duration;
289+
const expected = (360 * t) / period;
266290
const actual = angleOf(transform);
267291
const error = Math.min(
268292
Math.abs(actual - expected),
@@ -298,9 +322,7 @@ test('storyboard: one revolution, frame by frame @storyboard', async ({
298322
const spinners = await openSizes(page);
299323
const xl = spinners.nth(3);
300324
const rotor = xl.locator('span[aria-hidden="true"]');
301-
const duration = await rotor.evaluate(element =>
302-
Number(element.getAnimations()[0].effect?.getTiming().duration),
303-
);
325+
const {period: duration} = await turnTiming(rotor);
304326
const {storyboard} = await animationStoryboard(page, {
305327
name: 'spinner-ring-cycle',
306328
clip: xl,

‎packages/core/src/theme/themeMotion.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,7 @@ describe('busy loops read the duration before tempo (spec:AST-108 FR4)', () => {
539539
const read = (file: string) =>
540540
fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
541541
expect(read('Spinner/Spinner.tsx')).toContain(
542-
"`var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})`",
542+
"var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})",
543543
);
544544
expect(read('Skeleton/Skeleton.tsx')).toContain(
545545
"`var(--_astryx-pre-tempo-duration-medium-max, ${durationVars['--duration-medium-max']})`",

0 commit comments

Comments
 (0)