Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Spinner): a turning ring wakes the main thread once in 100 turns (#9936)

Cindy Zhanged9b75b811ee
diff --git a/.changeset/spinner-iteration-wakes.md b/.changeset/spinner-iteration-wakes.md
new file mode 100644
index 0000000000..09564126cc
--- /dev/null
+++ b/.changeset/spinner-iteration-wakes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[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.
+
+@cixzhang
diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsx
index 0ef05a9adf..63d3ac9ea0 100644
--- a/packages/core/src/Spinner/Spinner.test.tsx
+++ b/packages/core/src/Spinner/Spinner.test.tsx
@@ -10,6 +10,7 @@
*/
import {describe, it, expect, vi, afterEach} from 'vitest';
+import {Profiler} from 'react';
import {render, screen} from '@testing-library/react';
import {Spinner} from './Spinner';
import {InternationalizationProvider} from '../i18n';
@@ -407,15 +408,31 @@ describe('Spinner ring', () => {
expect(declaredValue(rotor(), 'animation-iteration-count')).toBe(
'infinite',
);
- // Its keyframes turn it once, by transform and nothing else. (jsdom's
- // CSSOM lowercases the name in the rule but not in the at-rule.)
+ // Its keyframes turn it by whole turns, by transform and nothing else.
+ // (jsdom's CSSOM lowercases the name in the rule but not in the at-rule.)
const keyframes = new RegExp(
`@keyframes ${name}\\s*\\{([\\s\\S]*?\\})\\s*\\}`,
'i',
).exec(css)?.[1];
expect(keyframes).toMatch(/rotate\(0deg\)/);
- expect(keyframes).toMatch(/rotate\(360deg\)/);
expect(keyframes).not.toMatch(/stroke|width|height|top|left/);
+ // One iteration holds many turns, and its duration is that many periods,
+ // so each turn still takes one period. Chromium wakes the main thread at
+ // each iteration boundary while React listens for `animationiteration`.
+ const endDegrees = Math.max(
+ ...[...(keyframes ?? '').matchAll(/rotate\((\d+)deg\)/g)].map(m =>
+ Number(m[1]),
+ ),
+ );
+ const turns = endDegrees / 360;
+ expect(Number.isInteger(turns)).toBe(true);
+ expect(turns).toBeGreaterThanOrEqual(100);
+ const duration = declaredValue(rotor(), 'animation-duration') ?? '';
+ expect(duration).toMatch(
+ new RegExp(
+ `^calc\\(var\\(--_astryx-pre-tempo-duration-slow-min,.*\\) \\* ${turns}\\)$`,
+ ),
+ );
// Its own compositing layer from the first frame.
expect(declaredValue(rotor(), 'will-change')).toBe('transform');
// Nothing else in the spinner animates: not the arc, not the track.
@@ -427,6 +444,31 @@ describe('Spinner ring', () => {
expect(css).not.toMatch(/@keyframes[^{]*\{[^}]*stroke-dashoffset/);
});
+ it('renders once and never again while the ring turns', () => {
+ vi.useFakeTimers({
+ toFake: ['requestAnimationFrame', 'setTimeout', 'setInterval'],
+ });
+ let renders = 0;
+ const onRender = () => {
+ renders += 1;
+ };
+ try {
+ render(
+ <Profiler id="spinner" onRender={onRender}>
+ {Array.from({length: 20}, (_, i) => (
+ <Spinner key={i} data-testid={`spinner-${i}`} />
+ ))}
+ </Profiler>,
+ );
+ expect(renders).toBe(1);
+ // Ten seconds of frames and timers: the motion is CSS only.
+ vi.advanceTimersByTime(10_000);
+ expect(renders).toBe(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('keeps the track out of the rotor', () => {
render(<Spinner data-testid="spinner" />);
expect(rotor().contains(circles().arc)).toBe(true);
diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsx
index 23f9508513..b18bef2179 100644
--- a/packages/core/src/Spinner/Spinner.tsx
+++ b/packages/core/src/Spinner/Spinner.tsx
@@ -211,6 +211,16 @@ function syncRotationPhase(
// Animation
// =============================================================================
+/**
+ * Full turns in one iteration of the rotation.
+ *
+ * Chromium wakes the main thread at each iteration boundary while the
+ * document listens for `animationiteration`. React listens for it on every
+ * root. One iteration holds 100 turns, so the wake comes once in 100 turns.
+ * Each turn is 360 degrees, so the ring looks the same.
+ */
+const TURNS_PER_ITERATION = 100;
+
/**
* A `transform` animation runs on the compositor, so the ring keeps turning
* while a script runs. A `stroke-dashoffset` animation would repaint the arc
@@ -218,7 +228,7 @@ function syncRotationPhase(
*/
const rotation = stylex.keyframes({
'0%': {transform: 'rotate(0deg)'},
- '100%': {transform: 'rotate(360deg)'},
+ '100%': {transform: `rotate(${360 * TURNS_PER_ITERATION}deg)`},
});
// =============================================================================
@@ -307,8 +317,8 @@ const styles = stylex.create({
// broken. The status role and its name still say that work is busy.
animationDuration: {
// The loop reads the duration before a theme's tempo scales it.
- default: `var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})`,
- '@media (prefers-reduced-motion: reduce)': '3s',
+ default: `calc(var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']}) * ${TURNS_PER_ITERATION})`,
+ '@media (prefers-reduced-motion: reduce)': `calc(3s * ${TURNS_PER_ITERATION})`,
},
animationIterationCount: 'infinite',
animationName: rotation,
diff --git a/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts b/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts
index 6b53916e03..338bab7c38 100644
--- a/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts
+++ b/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts
@@ -132,6 +132,25 @@ async function checksums(
}
}
+/**
+ * The time of one turn, in ms, and the turns in one iteration. One iteration
+ * holds many turns, so the period is the iteration's duration divided by the
+ * turns its last keyframe makes.
+ */
+async function turnTiming(
+ rotor: ReturnType<Page['locator']>,
+): Promise<{period: number; turns: number}> {
+ return rotor.evaluate(element => {
+ const [animation] = element.getAnimations();
+ const effect = animation.effect as KeyframeEffect;
+ const frames = effect.getKeyframes();
+ const end = String(frames[frames.length - 1].transform);
+ const degrees = Number(/rotate\((-?[\d.]+)deg\)/.exec(end)?.[1]);
+ const turns = degrees / 360;
+ return {period: Number(effect.getTiming().duration) / turns, turns};
+ });
+}
+
/** The rotor's angle in degrees, from 0 up to 360. */
function angleOf(transform: string): number {
return (parseTransform(transform).rotate + 360) % 360;
@@ -184,13 +203,18 @@ test('the ring keeps turning while a script holds the main thread', async ({
test('turning paints nothing on the main thread', async ({page}) => {
await openSizes(page);
await page.waitForTimeout(200);
- // Four rings turn for a second. A paint animation repaints every frame; a
- // transform animation paints none.
+ // Four rings turn for two seconds. A paint animation repaints every frame;
+ // a transform animation paints none. React listens for
+ // `animationiteration`, so Chromium recalculates style a few times at each
+ // iteration boundary. One turn per iteration gives about 14 recalculations
+ // here. With many turns in one iteration, no boundary occurs, and the bound
+ // allows only unrelated single recalculations.
const trace = await traceRendering(page, async () =>
- page.waitForTimeout(1000),
+ page.waitForTimeout(2000),
);
expect(trace.paint).toBe(0);
expect(trace.layout).toBe(0);
+ expect(trace.styleRecalc).toBeLessThanOrEqual(2);
});
test('the arc turns clockwise at a constant rate, once per period', async ({
@@ -198,26 +222,27 @@ test('the arc turns clockwise at a constant rate, once per period', async ({
}) => {
const spinners = await openSizes(page);
const rotor = spinners.first().locator('span[aria-hidden="true"]');
- const samples = await rotor.evaluate(element => {
+ const {period, turns} = await turnTiming(rotor);
+ const samples = await rotor.evaluate((element, periodMs) => {
const [animation] = element.getAnimations();
animation.pause();
- const duration = Number(animation.effect?.getTiming().duration);
const out: {t: number; transform: string}[] = [];
for (let i = 0; i <= 8; i += 1) {
// Inside the period at both ends: 0, P/8 … P − 1 ms.
- const t = i === 8 ? duration - 1 : (duration * i) / 8;
+ const t = i === 8 ? periodMs - 1 : (periodMs * i) / 8;
animation.currentTime = t;
out.push({t, transform: getComputedStyle(element).transform});
}
return {
- duration,
+ duration: Number(animation.effect?.getTiming().duration),
cssDuration: getComputedStyle(element).animationDuration,
easing: animation.effect?.getTiming().easing,
out,
};
- });
+ }, period);
// The period is the `--duration-slow-min` token the theme resolves.
- expect(samples.duration).toBeGreaterThan(0);
+ expect(period).toBeGreaterThan(0);
+ expect(Number.isInteger(turns) && turns > 1).toBe(true);
expect(Number.parseFloat(samples.cssDuration) * 1000).toBeCloseTo(
samples.duration,
3,
@@ -225,7 +250,7 @@ test('the arc turns clockwise at a constant rate, once per period', async ({
expect(samples.easing).toBe('linear');
// Angle = 360 × t / P, clockwise (positive in CSS), at every sample.
for (const {t, transform} of samples.out) {
- const expected = ((360 * t) / samples.duration) % 360;
+ const expected = ((360 * t) / period) % 360;
const actual = angleOf(transform);
const error = Math.min(
Math.abs(actual - expected),
@@ -241,28 +266,27 @@ test('reduced motion slows the ring to 3 s per turn, as before, still clockwise
await page.emulateMedia({reducedMotion: 'reduce'});
const spinners = await openSizes(page);
const rotor = spinners.first().locator('span[aria-hidden="true"]');
- const samples = await rotor.evaluate(element => {
+ const {period} = await turnTiming(rotor);
+ const samples = await rotor.evaluate((element, periodMs) => {
const [animation] = element.getAnimations();
animation.pause();
- const duration = Number(animation.effect?.getTiming().duration);
const out: {t: number; transform: string}[] = [];
for (let i = 0; i < 4; i += 1) {
- const t = (duration * i) / 4;
+ const t = (periodMs * i) / 4;
animation.currentTime = t;
out.push({t, transform: getComputedStyle(element).transform});
}
return {
- duration,
iterations: animation.effect?.getTiming().iterations,
out,
};
- });
+ }, period);
// The reduced-motion period this component had before the change: slowed,
// never frozen (`Spinner.tsx`, `animationDuration` under the media query).
- expect(samples.duration).toBe(3000);
+ expect(period).toBeCloseTo(3000, 6);
expect(samples.iterations).toBe(Infinity);
for (const {t, transform} of samples.out) {
- const expected = (360 * t) / samples.duration;
+ const expected = (360 * t) / period;
const actual = angleOf(transform);
const error = Math.min(
Math.abs(actual - expected),
@@ -298,9 +322,7 @@ test('storyboard: one revolution, frame by frame @storyboard', async ({
const spinners = await openSizes(page);
const xl = spinners.nth(3);
const rotor = xl.locator('span[aria-hidden="true"]');
- const duration = await rotor.evaluate(element =>
- Number(element.getAnimations()[0].effect?.getTiming().duration),
- );
+ const {period: duration} = await turnTiming(rotor);
const {storyboard} = await animationStoryboard(page, {
name: 'spinner-ring-cycle',
clip: xl,
diff --git a/packages/core/src/theme/themeMotion.test.ts b/packages/core/src/theme/themeMotion.test.ts
index 71d9339ba9..f361bdda3d 100644
--- a/packages/core/src/theme/themeMotion.test.ts
+++ b/packages/core/src/theme/themeMotion.test.ts
@@ -539,7 +539,7 @@ describe('busy loops read the duration before tempo (spec:AST-108 FR4)', () => {
const read = (file: string) =>
fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
expect(read('Spinner/Spinner.tsx')).toContain(
- "`var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})`",
+ "var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})",
);
expect(read('Skeleton/Skeleton.tsx')).toContain(
"`var(--_astryx-pre-tempo-duration-medium-max, ${durationVars['--duration-medium-max']})`",