An open source design system that's fully customizable and agent ready
TypeScript
fix(Spinner): the ring keeps turning while JavaScript runs (#8177)
Christopher Chedeaufa3295a50a38
diff --git a/.changeset/spinner-compositor-ring.md b/.changeset/spinner-compositor-ring.mdnew file mode 100644index 0000000000..1e6fdbdbfc--- /dev/null+++ b/.changeset/spinner-compositor-ring.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Spinner keeps turning while a script runs. The ring used to move by repainting its arc on the main thread every frame, so it stopped for as long as the page ran JavaScript, which is exactly when a loading indicator is on screen. The arc now sits in its own layer that the browser turns on its compositor: through a 700 ms main-thread block it keeps turning at full rate, and it paints nothing per frame. The ring looks the same at rest and turns at the same speed; sizes, shades, the themeable vars and reduced motion are unchanged.++@vjeuxdiff --git a/docs/specs/components/Spinner/Spinner.spec.md b/docs/specs/components/Spinner/Spinner.spec.mdindex a997f449c6..1189308b7d 100644--- a/docs/specs/components/Spinner/Spinner.spec.md+++ b/docs/specs/components/Spinner/Spinner.spec.md@@ -14,6 +14,7 @@ verified_by:[packages/core/src/Spinner/Spinner.test.tsx,packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts,+ packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts,packages/core/src/theme/themingTargets.test.ts,apps/storybook/stories/Spinner.stories.tsx,]@@ -27,7 +28,7 @@ architecture:architecture:public-component-api,]contributing: []-system_specs: [spec:AST-009, spec:AST-086]+system_specs: [spec:AST-009, spec:AST-086, spec:AST-108/FR4]---# Spinner component contract@@ -83,7 +84,7 @@ Consumer migration instructions belong in consumer docs and release notes.- The status element, the ring drawn inside it, and the optional label belowit.-- Ring geometry per `size`, ring and track color per `shade`, the dash motion,+- Ring geometry per `size`, ring and track color per `shade`, the arc's turn,and the reduced-motion rate.- The five public theme variables and where they are declared.- The status element's accessible name, including the translated default.@@ -108,16 +109,16 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1 | Without a label, Spinner renders one inline-grid `span` status element that carries the `spinner` target, ref, `data-testid`, and passthrough props. With a label, a column `div` wrapper with `--spacing-2` gap carries the target, ref, `data-testid`, passthrough props, and styling inputs; the status `span` and then the label render inside it. | Current source and tests |-| FR2 | The status element's box is the ring diameter plus one stroke width on each side, set inline after the caller's `style`, so a caller `width` or `height` never resizes it while other caller styles still apply. The box does not shrink in a flex host. With no stylesheet, the box and ring draw at the size's default geometry. | Current source and tests |-| FR3 | The ring is an `aria-hidden` SVG of two concentric circles: a full track and an arc covering `--spinner-arc-fraction` of the circumference (0.375 by default), starting at twelve o'clock with round caps. The arc's dash moves around the stationary circle at `--duration-slow-min` per cycle, as the theme sets it before `tempo` scales it (`spec:AST-108` FR4), linear, indefinitely; under `prefers-reduced-motion: reduce` the cycle slows to 3 seconds and does not stop. | Current source and tests |-| FR4 | All mounted rings turn in the same phase, whenever each mounted. Where the browser cannot report running animations, Spinner does no phase work. | Current source and tests |-| FR5 | `default` paints `--color-accent` on `--color-track`; `subtle` paints `--color-text-secondary` on `--color-track`; `onMedia` paints `--color-on-dark` on itself at track opacity 77/255; `inherit` paints `currentColor` on itself at track opacity 0.3. | Current source and tests |-| FR6 | The five public variables are declared only on the element carrying the `spinner` target, per `size` and `shade`, so a theme rule on that target and its `size:` or `shade:` variants overrides them; the inner status element inherits them when a label moves the target to the wrapper. | Current source and tests |-| FR7 | A string label renders as bold body Text; a rich-node label renders as supplied. | Current source and tests |-| FR8 | `xstyle` and `className` reach the element carrying the target and merge after component styles; `style` merges after them except for the status box's `width` and `height` (FR2). | Current source and tests |+| ID | Invariant | Basis |+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1 | Without a label, Spinner renders one inline-grid `span` status element that carries the `spinner` target, ref, `data-testid`, and passthrough props. With a label, a column `div` wrapper with `--spacing-2` gap carries the target, ref, `data-testid`, passthrough props, and styling inputs; the status `span` and then the label render inside it. | Current source and tests |+| FR2 | The status element's box is the ring diameter plus one stroke width on each side, set inline after the caller's `style`, so a caller `width` or `height` never resizes it while other caller styles still apply. The box does not shrink in a flex host. With no stylesheet, the box and ring draw at the size's default geometry. | Current source and tests |+| FR3 | The ring is an `aria-hidden` track circle and an `aria-hidden` arc covering `--spinner-arc-fraction` of the circumference (0.375 by default), starting at twelve o'clock with round caps. The arc turns around the stationary track at `--duration-slow-min` per cycle, as the theme sets it before `tempo` scales it (`spec:AST-108` FR4), linear, indefinitely; under `prefers-reduced-motion: reduce` the cycle slows to 3 seconds and does not stop. | Current source and tests |+| FR4 | All mounted rings turn in the same phase, whenever each mounted. Where the browser cannot report running animations, Spinner does no phase work. | Current source and tests |+| FR5 | `default` paints `--color-accent` on `--color-track`; `subtle` paints `--color-text-secondary` on `--color-track`; `onMedia` paints `--color-on-dark` on itself at track opacity 77/255; `inherit` paints `currentColor` on itself at track opacity 0.3. | Current source and tests |+| FR6 | The five public variables are declared only on the element carrying the `spinner` target, per `size` and `shade`, so a theme rule on that target and its `size:` or `shade:` variants overrides them; the inner status element inherits them when a label moves the target to the wrapper. | Current source and tests |+| FR7 | A string label renders as bold body Text; a rich-node label renders as supplied. | Current source and tests |+| FR8 | `xstyle` and `className` reach the element carrying the target and merge after component styles; `style` merges after them except for the status box's `width` and `height` (FR2). | Current source and tests |### Allowed variation@@ -173,7 +174,7 @@ Consumer migration instructions belong in consumer docs and release notes.empty name; and with a `label`, a caller `aria-labelledby` lands on therole-less wrapper and names nothing.-- **AR2 — Decorative ring.** The SVG is `aria-hidden`.+- **AR2 — Decorative ring.** The ring is `aria-hidden`.- **AR3 — Translated default.** The default name comes from the translationcatalog and follows the active locale.- **AR4 — Reduced motion.** Motion slows under `prefers-reduced-motion:@@ -202,17 +203,17 @@ consumer anatomy names no parts, so no anatomy-theming block is declared.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ |-| FR1, FR7, FR8 | `Spinner.test.tsx` render, label, and data-testid tests | Unlabelled, string label, rich label | A lost label or test id fails. Gap: in both forms no test asserts which element carries the ref, `xstyle`, and `className`, or where the target lands in the labelled form. | `audit:Spinner/behavior` |-| FR2 | `Spinner.test.tsx` box-sizing suite; `Spinner.stories.tsx` NarrowFlexHost | Every size; caller `style` width; narrow flex host | A caller width winning, or a lost fallback frame, fails. Gap: no automated check fails if the box shrinks in a flex host; it is visible in the story. | `audit:Spinner/layout` |-| FR3, FR4, PR2 | `Spinner.test.tsx` ring suite, including the 135-degree sweep test | SVG structure, default dash and arc fraction, frame scheduling | A lost circle, a changed default dash or arc fraction, an extra frame, or unbatched pinning fails. Gap: the start-angle test checks only for no SVG `transform` attribute, so removing the CSS start rotation passes; the cycle duration, the 3-second reduced-motion rate, the themed arc fraction, and dropping an unmounted ring from pending phase work have no automated check. | `audit:Spinner/motion` |-| FR5, FR6 | `Spinner.test.tsx` theme-variable suite | Size-, shade-, and base-scoped overrides | A themed variable emitted on the wrong selector fails. Gap: no test fails if the component declares its defaults on the inner span of a labelled Spinner, and the shade tests assert presence and reflection only, so the default colors and track opacities have no automated check. | `audit:Spinner/theming` |-| PR1 | `Spinner.test.tsx` registration suite | Import, repeated evaluation | Doing the work on mount or throwing on a second evaluation fails. Gap: the suite runs only with a DOM, so server-side safety has no automated check. | `audit:Spinner/behavior` |-| AR1, AR3 | `Spinner.test.tsx` naming and localization tests | Default, explicit, string, and rich labels | A missing name, a string label repeated as `aria-label`, or an untranslated default fails. Gap: no test covers an empty `aria-label` or `label`, or a caller `aria-labelledby`. | `audit:Spinner/a11y` |-| AR4 | `Spinner.stories.tsx` with reduced motion emulated in a browser | Reduced motion | Gap: no automated check; a stopped ring is visible only in a rendered fixture. | `audit:Spinner/motion` |-| AR2 | Source review | Every state | Gap: no automated check fails if the ring SVG loses `aria-hidden`. | `audit:Spinner/a11y` |-| AR1, AR2 | `StatusMessage.a11y.chromium.spec.ts` Spinner states | Default label and visible string label, mounted | A changed role or name fails the accessibility-tree assertions. Gap: rich labels, empty names, the hidden ring, and channel delivery have no accessibility-tree check. | `audit:Spinner/a11y` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1, FR7, FR8 | `Spinner.test.tsx` render, label, and data-testid tests | Unlabelled, string label, rich label | A lost label or test id fails. Gap: in both forms no test asserts which element carries the ref, `xstyle`, and `className`, or where the target lands in the labelled form. | `audit:Spinner/behavior` |+| FR2 | `Spinner.test.tsx` box-sizing suite; `Spinner.stories.tsx` NarrowFlexHost | Every size; caller `style` width; narrow flex host | A caller width winning, or a lost fallback frame, fails. Gap: no automated check fails if the box shrinks in a flex host; it is visible in the story. | `audit:Spinner/layout` |+| FR3, FR4, PR2 | `Spinner.test.tsx` ring suite, including the 135-degree sweep test; `SpinnerMotion.a11y.chromium.spec.ts` | Track and rotor structure, default dash and arc fraction, frame scheduling; a 700 ms main-thread block, one period, several rings | A lost circle, a changed default dash or arc fraction, an extra frame, or unbatched pinning fails, and so does a ring that stops while a script runs, paints every frame, turns at another rate or direction, or drifts out of phase. Gap: the start-angle test checks only for no SVG `transform` attribute, so removing the CSS start rotation passes; the themed arc fraction and dropping an unmounted ring from pending phase work have no automated check. | `audit:Spinner/motion` |+| FR5, FR6 | `Spinner.test.tsx` theme-variable suite | Size-, shade-, and base-scoped overrides | A themed variable emitted on the wrong selector fails. Gap: no test fails if the component declares its defaults on the inner span of a labelled Spinner, and the shade tests assert presence and reflection only, so the default colors and track opacities have no automated check. | `audit:Spinner/theming` |+| PR1 | `Spinner.test.tsx` registration suite | Import, repeated evaluation | Doing the work on mount or throwing on a second evaluation fails. Gap: the suite runs only with a DOM, so server-side safety has no automated check. | `audit:Spinner/behavior` |+| AR1, AR3 | `Spinner.test.tsx` naming and localization tests | Default, explicit, string, and rich labels | A missing name, a string label repeated as `aria-label`, or an untranslated default fails. Gap: no test covers an empty `aria-label` or `label`, or a caller `aria-labelledby`. | `audit:Spinner/a11y` |+| AR4 | `SpinnerMotion.a11y.chromium.spec.ts` reduced-motion test | Reduced motion | A ring that stops, or turns at another rate than 3 seconds per cycle, fails. | `audit:Spinner/motion` |+| AR2 | Source review | Every state | Gap: no automated check fails if the track or the rotor loses `aria-hidden`. | `audit:Spinner/a11y` |+| AR1, AR2 | `StatusMessage.a11y.chromium.spec.ts` Spinner states | Default label and visible string label, mounted | A changed role or name fails the accessibility-tree assertions. Gap: rich labels, empty names, the hidden ring, and channel delivery have no accessibility-tree check. | `audit:Spinner/a11y` |## Decision logdiff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex f03efe1d9b..5d4d0a970e 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -1001,14 +1001,7 @@"spec:AST-085","spec:AST-085"],- "packages/core/src/Spinner/Spinner.tsx": [- "#3617",- "#5410",- "#6253",- "#6253",- "FR4",- "spec:AST-108"- ],+ "packages/core/src/Spinner/Spinner.tsx": ["#5410"],"packages/core/src/StatusDot/StatusDot.tsx": ["INV11","INV11",diff --git a/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts b/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.tsindex 0677aea370..4b07bc582e 100644--- a/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts+++ b/packages/core/src/CommandPalette/__tests__/CommandPalette.a11y.chromium.spec.ts@@ -332,8 +332,10 @@ async function capture(page: Page, scenario: Case) {const spinners = elements<HTMLElement>('.astryx-command-palette-input .astryx-spinner',);+ // The arc is the circle in the Spinner's turning rotor (an aria-hidden+ // span); the track circle sits in its own svg beside it.const spinnerArcs = elements<SVGCircleElement>(- '.astryx-command-palette-input .astryx-spinner circle:last-of-type',+ '.astryx-command-palette-input .astryx-spinner span[aria-hidden="true"] circle',);const shortcuts = elements<HTMLElement>('.astryx-command-palette-footer .astryx-kbd',diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsxindex 1267cd3255..0ef05a9adf 100644--- a/packages/core/src/Spinner/Spinner.test.tsx+++ b/packages/core/src/Spinner/Spinner.test.tsx@@ -15,6 +15,8 @@ import {Spinner} from './Spinner';import {InternationalizationProvider} from '../i18n';import {defineTheme} from '../theme/defineTheme';import {generateThemeCSS} from '../theme/generateThemeRules';+import {getAllInjectedCss} from '../__tests__/forcedColors';+import {declaredValue} from '../__tests__/stylexDeclarations';/** sm/md/lg/xl, as Spinner.tsx defines them. */const SIZES = {@@ -27,8 +29,19 @@ const SIZES = {const ring = (testId = 'spinner') =>screen.getByTestId(testId).querySelector('svg') as SVGSVGElement;+/** The track's svg and the arc's svg, in that order. */+const rings = (testId = 'spinner') => [+ ...screen.getByTestId(testId).querySelectorAll('svg'),+];++/** The box that turns: the arc's svg sits inside it, the track's does not. */+const rotor = (testId = 'spinner') =>+ rings(testId)[1].parentElement as HTMLSpanElement;+const circles = (testId = 'spinner') => {- const [track, arc] = [...ring(testId).querySelectorAll('circle')];+ const [track, arc] = [+ ...screen.getByTestId(testId).querySelectorAll('circle'),+ ];return {track, arc};};@@ -251,9 +264,13 @@ describe('Spinner ring', () => {it('draws the ring in SVG', () => {render(<Spinner data-testid="spinner" />);- const svg = ring();- expect(svg).not.toBeNull();- expect(svg.querySelectorAll('circle')).toHaveLength(2);+ // The track and the arc each have their own svg: the track stays put and+ // the arc's svg sits in the rotor that turns.+ const [trackSvg, arcSvg] = rings();+ expect(trackSvg.querySelectorAll('circle')).toHaveLength(1);+ expect(arcSvg.querySelectorAll('circle')).toHaveLength(1);+ expect(trackSvg.parentElement).toBe(screen.getByTestId('spinner'));+ expect(rotor().parentElement).toBe(screen.getByTestId('spinner'));expect(screen.getByTestId('spinner').querySelector('canvas')).toBeNull();});@@ -265,11 +282,17 @@ describe('Spinner ring', () => {);// No viewBox: one user unit is one px, so the attributes below mean px.// They are the no-stylesheet fallback; CSS sizes the frame from the box.+ // The track's are zero, so without a stylesheet the arc alone fills+ // the box rather than sitting beside a second disc.const frame = diameter + border * 2;- const svg = ring();- expect(svg.getAttribute('viewBox')).toBeNull();- expect(Number(svg.getAttribute('width'))).toBe(frame);- expect(Number(svg.getAttribute('height'))).toBe(frame);+ const [track, arc] = rings();+ for (const svg of [track, arc]) {+ expect(svg.getAttribute('viewBox')).toBeNull();+ }+ expect(Number(arc.getAttribute('width'))).toBe(frame);+ expect(Number(arc.getAttribute('height'))).toBe(frame);+ expect(Number(track.getAttribute('width'))).toBe(0);+ expect(Number(track.getAttribute('height'))).toBe(0);for (const c of [circles().track, circles().arc]) {expect(c.getAttribute('cx')).toBe('50%');expect(c.getAttribute('cy')).toBe('50%');@@ -302,13 +325,14 @@ describe('Spinner ring', () => {// because nothing tied them.it('sizes the frame from CSS, not from the size constant', () => {render(<Spinner data-testid="spinner" />);- const svg = ring();// No viewBox, and the circles centre on the box rather than on a centre// in user units — together that is what lets CSS size the frame from// `--_spinner-box-size`, the same composed var the span is sized from, so// a themed diameter moves both. The px attributes remain as the// no-stylesheet fallback and CSS outranks them whenever one is present.- expect(svg.getAttribute('viewBox')).toBeNull();+ for (const svg of rings()) {+ expect(svg.getAttribute('viewBox')).toBeNull();+ }for (const c of [circles().track, circles().arc]) {expect(c.getAttribute('cx')).toBe('50%');expect(c.getAttribute('cy')).toBe('50%');@@ -362,21 +386,62 @@ describe('Spinner ring', () => {);it('schedules no frame where the Web Animations API is absent', () => {- expect(SVGElement.prototype).not.toHaveProperty('getAnimations');+ expect(HTMLElement.prototype).not.toHaveProperty('getAnimations');const raf = vi.spyOn(window, 'requestAnimationFrame');render(<Spinner data-testid="spinner" />);expect(ring()).not.toBeNull();expect(raf).not.toHaveBeenCalled();});+ // The ring turns on the compositor: only the rotor moves, and only by+ // `transform`, a property the browser animates without the main thread. A+ // paint animation such as `stroke-dashoffset` would repaint the arc on the+ // main thread every frame. It would stop while a script runs;+ // `SpinnerMotion.a11y.chromium.spec.ts` holds the frames.+ it('turns the arc by rotating the rotor, with nothing else animated', () => {+ render(<Spinner data-testid="spinner" />);+ const css = getAllInjectedCss();+ const name = declaredValue(rotor(), 'animation-name');+ expect(name).toBeTruthy();+ expect(declaredValue(rotor(), 'animation-timing-function')).toBe('linear');+ 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.)+ 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/);+ // 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.+ for (const el of [+ ...screen.getByTestId('spinner').querySelectorAll('svg, circle'),+ ]) {+ expect(declaredValue(el, 'animation-name')).toBeNull();+ }+ expect(css).not.toMatch(/@keyframes[^{]*\{[^}]*stroke-dashoffset/);+ });++ it('keeps the track out of the rotor', () => {+ render(<Spinner data-testid="spinner" />);+ expect(rotor().contains(circles().arc)).toBe(true);+ expect(rotor().contains(circles().track)).toBe(false);+ expect(rotor().getAttribute('aria-hidden')).toBe('true');+ });+it('pins every ring to the timeline origin in a single frame', () => {const animations: {startTime: number | null}[] = [];- const getAnimations = vi.fn(function (this: SVGElement) {+ const getAnimations = vi.fn(function (this: HTMLElement) {const a = {startTime: null as number | null};animations.push(a);return [a];});- Object.defineProperty(SVGElement.prototype, 'getAnimations', {+ Object.defineProperty(HTMLElement.prototype, 'getAnimations', {value: getAnimations,configurable: true,writable: true,@@ -394,7 +459,7 @@ describe('Spinner ring', () => {const {container} = render(<>{Array.from({length: 5}, (_, i) => (- <Spinner key={i} />+ <Spinner key={i} data-testid={`spinner-${i}`} />))}</>,);@@ -404,10 +469,10 @@ describe('Spinner ring', () => {frames.forEach(cb => cb(0));expect(animations).toHaveLength(5);expect(animations.every(a => a.startTime === 0)).toBe(true);- // The dash animation lives on the arc <circle>, a descendant of the- // <svg> this ref sits on, not the <svg> itself (#6253) — subtree:true- // is what lets getAnimations() find it from here.- expect(getAnimations).toHaveBeenCalledWith({subtree: true});+ // The rotation lives on the rotor itself, the element the ref sits on.+ expect(getAnimations.mock.contexts).toEqual(+ Array.from({length: 5}, (_, i) => rotor(`spinner-${i}`)),+ );// The pin runs on the branch the other shade cases cannot reach, so the// no-read assertion is made here too.expect(@@ -417,7 +482,7 @@ describe('Spinner ring', () => {).toEqual([]);} finally {// @ts-expect-error — removing the stub restores jsdom's real surface- delete SVGElement.prototype.getAnimations;+ delete HTMLElement.prototype.getAnimations;}});});diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsxindex 9e29e06160..23f9508513 100644--- a/packages/core/src/Spinner/Spinner.tsx+++ b/packages/core/src/Spinner/Spinner.tsx@@ -10,7 +10,7 @@** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Spinner/Spinner.doc.mjs- * - /packages/core/src/Spinner/Spinner.test.tsx+ * - /packages/core/src/Spinner/Spinner.test.tsx and __tests__/SpinnerMotion.a11y.chromium.spec.ts (rotor timing)* - /packages/core/src/Spinner/index.ts* - /apps/storybook/stories/Spinner.stories.tsx* - /packages/cli/assets/templates/blocks/components/Spinner/ (showcase blocks)@@ -153,60 +153,57 @@ function registerSpinnerVars(): void {registerSpinnerVars();/**- * Pin every ring's dash motion to the document timeline's origin instead of- * its own start time, so spinners mounted seconds apart stay in phase.+ * Pin every ring's rotation to the document timeline's origin instead of its+ * own start time, so spinners mounted seconds apart stay in phase.*- * Setting `startTime` is exact where arithmetic on a clock read is not: a+ * Setting `startTime` is exact where arithmetic on a clock read is not. A* negative `animation-delay` computed at mount is only as good as the gap- * between reading the clock and the frame the animation starts in, which at- * 10x CPU throttling measured 116deg of drift (from when this animated a- * literal rotation; the same drift risk applies to the dash offset now).+ * between the clock read and the frame the animation starts in. At 10x CPU+ * throttling that gap measured 116 degrees of drift.*- * Rings are collected and pinned in one frame because `getAnimations()`- * resolves style and `startTime` dirties it again, so pinning them one at a- * time makes each mount re-force what the previous one invalidated — 53 style- * recalcs for 38 spinners against 19 batched.+ * Rotors are collected and pinned in one frame. `getAnimations()` resolves+ * style, and `startTime` dirties it again. So pinning them one at a time makes+ * each mount re-force what the previous one invalidated: 53 style recalcs for+ * 38 spinners, against 19 batched.*/-const pendingRings = new Set<SVGSVGElement>();+const pendingRotors = new Set<HTMLSpanElement>();let flushScheduled = false;-function pinRingsToTimelineOrigin(): void {+function pinRotorsToTimelineOrigin(): void {flushScheduled = false;const animations: Animation[] = [];- for (const svg of pendingRings) {- // The animation now runs on the arc <circle>, a descendant of the ring- // this ref sits on (#6253), so it needs subtree:true to be found here.- animations.push(...svg.getAnimations({subtree: true}));+ for (const rotor of pendingRotors) {+ animations.push(...rotor.getAnimations());}- pendingRings.clear();+ pendingRotors.clear();for (const animation of animations) {animation.startTime = 0;}}/**- * Ref callback for the ring: the one place a mounted ring touches the DOM.+ * Ref callback for the rotor: the one place a mounted ring touches the DOM.** It reads nothing back — the geometry is resolved by the cascade, not in JS.*/function syncRotationPhase(- svg: SVGSVGElement | null,+ rotor: HTMLSpanElement | null,): (() => void) | undefined {- if (svg == null) {+ if (rotor == null) {return undefined;}// jsdom implements no Web Animations, and this runs in every consumer's// component tests.- if (typeof svg.getAnimations !== 'function') {+ if (typeof rotor.getAnimations !== 'function') {return undefined;}- pendingRings.add(svg);+ pendingRotors.add(rotor);if (!flushScheduled) {flushScheduled = true;- requestAnimationFrame(pinRingsToTimelineOrigin);+ requestAnimationFrame(pinRotorsToTimelineOrigin);}return () => {- pendingRings.delete(svg);+ pendingRotors.delete(rotor);};}@@ -215,19 +212,13 @@ function syncRotationPhase(// =============================================================================/**- * Moves the dash around a stationary circle instead of rotating the whole- * ring. WebKit re-antialiases a rotating stroked shape's rounded cap- * (`strokeLinecap: 'round'`, below) slightly differently at each intermediate- * angle, which reads as a visible wobble on iOS Safari independent of- * compositing (#6253) — confirmed by a real-device test against this exact- * fix, since `willChange`/layer promotion alone (the earlier fix for #3617)- * only smooths the rotation's motion, not the per-frame stroke rasterization.- * A static circle with an animated `stroke-dashoffset` never rotates, so- * WebKit never re-rasterizes the cap at an intermediate angle at all.+ * A `transform` animation runs on the compositor, so the ring keeps turning+ * while a script runs. A `stroke-dashoffset` animation would repaint the arc+ * on the main thread every frame, so it would stop while a script runs.*/-const dashMotion = stylex.keyframes({- '0%': {strokeDashoffset: '0px'},- '100%': {strokeDashoffset: `calc(var(${RESOLVED_DIAMETER}) * -${PI})`},+const rotation = stylex.keyframes({+ '0%': {transform: 'rotate(0deg)'},+ '100%': {transform: 'rotate(360deg)'},});// =============================================================================@@ -283,6 +274,8 @@ const styles = stylex.create({ring: {backfaceVisibility: 'hidden',display: 'block',+ // The track and the rotor share the one grid cell, stacked and centred.+ gridArea: '1 / 1',// The frame is the box, read from the same composed var the span is sized// from — not from the size constant, which a theme cannot reach, and not// from a percentage, which needs the grid area to be a definite size in@@ -300,6 +293,27 @@ const styles = stylex.create({// which put the ring 1.5-3.3px off across the four sizes.overflow: 'visible',},+ // The rotor is the frame's size, so it turns about the ring's centre.+ rotor: {+ display: 'block',+ gridArea: '1 / 1',+ width: `var(${BOX_SIZE})`,+ height: `var(${BOX_SIZE})`,+ // Mobile Safari keeps a re-timed animation off the main thread only on an+ // element with its own layer. So the rotor declares one before the start+ // time is set (see `pinRotorsToTimelineOrigin`).+ willChange: 'transform',+ // Reduced motion slows the turn but never stops it: a still ring reads as+ // 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',+ },+ animationIterationCount: 'infinite',+ animationName: rotation,+ animationTimingFunction: 'linear',+ },circle: {fill: 'none',// The ring is centred on the box (cx/cy 50%), so the arc's start offset@@ -336,18 +350,6 @@ const styles = stylex.create({// `0` the way the registered length pair guards against, so it needs no// registration.arc: {- // Slow the motion dramatically under reduced-motion rather than freezing- // it (a frozen spinner reads as broken), matching ProgressBar's approach.- // The role="status" + "Loading" label still convey busy state (obs-6).- animationDuration: {- // The loop reads the duration before a theme's tempo scales it- // (spec:AST-108 FR4).- default: `var(--_astryx-pre-tempo-duration-slow-min, ${durationVars['--duration-slow-min']})`,- '@media (prefers-reduced-motion: reduce)': '3s',- },- animationIterationCount: 'infinite',- animationName: dashMotion,- animationTimingFunction: 'linear',stroke: 'var(--spinner-color)',transform: 'rotate(-90deg)',strokeDasharray: `calc(var(${RESOLVED_DIAMETER}) * ${PI} * var(--spinner-arc-fraction)) calc(var(${RESOLVED_DIAMETER}) * ${PI} * (1 - var(--spinner-arc-fraction)))`,@@ -569,10 +571,12 @@ export function Spinner({height: `var(${BOX_SIZE}, ${frameSize}px)`,},)}>+ {/* The track is zero-sized by attribute. With no stylesheet, the+ rotor's arc alone fills the box, instead of two discs side by side.+ `ring` sizes both to the box. */}<svg- ref={syncRotationPhase}- width={frameSize}- height={frameSize}+ width={0}+ height={0}aria-hidden="true"{...stylex.props(styles.ring)}><circle@@ -586,18 +590,28 @@ export function Spinner({trackOpacityStyles[shade],)}/>- <circle- cx="50%"- cy="50%"- r={diameter / 2}- strokeWidth={border}- // The size's own dash, for the render with no stylesheet. The rule- // above composes the same lengths from the resolved diameter, so a- // themed ring keeps this fraction of arc rather than this length.- strokeDasharray={`${arcLength} ${circumference - arcLength}`}- {...stylex.props(styles.circle, styles.arc)}- /></svg>+ <span+ ref={syncRotationPhase}+ aria-hidden="true"+ {...stylex.props(styles.rotor)}>+ <svg+ width={frameSize}+ height={frameSize}+ {...stylex.props(styles.ring)}>+ <circle+ cx="50%"+ cy="50%"+ r={diameter / 2}+ strokeWidth={border}+ // The size's own dash, for the render with no stylesheet. The rule+ // above composes the same lengths from the resolved diameter, so a+ // themed ring keeps this fraction of arc rather than this length.+ strokeDasharray={`${arcLength} ${circumference - arcLength}`}+ {...stylex.props(styles.circle, styles.arc)}+ />+ </svg>+ </span></span>);diff --git a/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts b/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.tsnew file mode 100644index 0000000000..fe9ee2f668--- /dev/null+++ b/packages/core/src/Spinner/__tests__/SpinnerMotion.a11y.chromium.spec.ts@@ -0,0 +1,332 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SpinnerMotion.a11y.chromium.spec.ts+ * @input Built Spinner stories in real Chromium (CDP screencast and tracing)+ * @output Browser evidence that the ring turns on the compositor and keeps+ * turning while a script runs, and a storyboard of one revolution+ * @position Chromium proof for Spinner's rotor+ *+ * SYNC: Keep the timings here equal to Spinner.tsx (`styles.rotor`).+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {+ animationStoryboard,+ blockMainThread,+ frameStats,+ parseTransform,+ startScreencast,+ timeline,+ traceRendering,+ type CastFrame,+} from '@astryxdesign/interaction-harness';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++const BLOCK_MS = 700;+const DPR = 2;++test.use({viewport: {width: 402, height: 420}, deviceScaleFactor: DPR});++/** The four sizes, sm → xl, each with its rotor. */+async function openSizes(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-spinner--sizes&viewMode=story`,+ );+ const spinners = page.locator('.astryx-spinner');+ await expect(spinners).toHaveCount(4);+ // Every rotor is running and has been pinned to the timeline origin.+ await page.waitForFunction(() => {+ const animations = document.getAnimations();+ return (+ animations.length >= 4 &&+ animations.every(a => a.playState === 'running' && a.startTime === 0)+ );+ });+ return spinners;+}++interface Box {+ x: number;+ y: number;+ width: number;+ height: number;+}++/** A checksum of each box in each frame, decoded in a scratch page. */+async function checksums(+ page: Page,+ frames: ReadonlyArray<CastFrame>,+ boxes: ReadonlyArray<Box>,+): Promise<number[][]> {+ const scratch = await page.context().newPage();+ const viewportWidth = page.viewportSize()?.width ?? 402;+ try {+ const out: number[][] = [];+ for (let i = 0; i < frames.length; i += 10) {+ const batch = frames.slice(i, i + 10).map(f => f.data);+ out.push(+ ...(await scratch.evaluate(+ async ({items, crops, vw}) => {+ const result: number[][] = [];+ for (const item of items) {+ const blob = await (+ await fetch(`data:image/png;base64,${item}`)+ ).blob();+ const bitmap = await createImageBitmap(blob);+ const scale = bitmap.width / vw;+ const sums: number[] = [];+ for (const box of crops) {+ const w = Math.ceil(box.width * scale);+ const h = Math.ceil(box.height * scale);+ const canvas = new OffscreenCanvas(w, h);+ const context = canvas.getContext('2d');+ if (context == null) {+ throw new Error('no 2d context');+ }+ context.drawImage(+ bitmap,+ Math.floor(box.x * scale),+ Math.floor(box.y * scale),+ w,+ h,+ 0,+ 0,+ w,+ h,+ );+ const {data} = context.getImageData(0, 0, w, h);+ let sum = 0;+ for (let p = 0; p < data.length; p += 4) {+ sum =+ (sum * 31 + data[p] * 3 + data[p + 1] * 5 + data[p + 2]) %+ 1000000007;+ }+ sums.push(sum);+ }+ result.push(sums);+ }+ return result;+ },+ {items: batch, crops: boxes, vw: viewportWidth},+ )),+ );+ }+ return out;+ } finally {+ await scratch.close();+ }+}++/** The rotor's angle in degrees, from 0 up to 360. */+function angleOf(transform: string): number {+ return (parseTransform(transform).rotate + 360) % 360;+}++test('the ring keeps turning while a script holds the main thread', async ({+ page,+}) => {+ const spinners = await openSizes(page);+ const boxes: Box[] = [];+ for (let i = 0; i < 4; i += 1) {+ const box = await spinners.nth(i).boundingBox();+ if (box == null) {+ throw new Error('no spinner box');+ }+ boxes.push(box);+ }+ const cast = await startScreencast(page);+ await page.waitForTimeout(300);+ const busy = await blockMainThread(page, BLOCK_MS);+ await page.waitForTimeout(200);+ const frames = await cast.stop();+ const sums = await checksums(page, frames, boxes);++ // Judge the block's inside, a frame clear of each edge.+ const from = busy.from + 20;+ const to = busy.to - 20;+ const inside = frames+ .map((frame, i) => ({t: frame.t, sums: sums[i]}))+ .filter(f => f.t >= from && f.t <= to);+ const expected = Math.floor((to - from) / (1000 / 60));+ // The compositor keeps presenting frames at display rate…+ expect(inside.length).toBeGreaterThanOrEqual(Math.floor(expected * 0.85));+ // …and every ring moves in nearly every one of them.+ for (let ring = 0; ring < 4; ring += 1) {+ const stats = frameStats(+ inside.map(f => ({t: f.t, value: f.sums[ring]})),+ {from, to},+ );+ expect(stats.changed, `ring ${ring} frames changed`).toBeGreaterThanOrEqual(+ Math.floor((inside.length - 1) * 0.9),+ );+ expect(+ stats.longestStallMs,+ `ring ${ring} longest stall`,+ ).toBeLessThanOrEqual(50);+ }+});++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.+ const trace = await traceRendering(page, async () =>+ page.waitForTimeout(1000),+ );+ expect(trace.paint).toBe(0);+ expect(trace.layout).toBe(0);+});++test('the arc turns clockwise at a constant rate, once per period', async ({+ page,+}) => {+ const spinners = await openSizes(page);+ const rotor = spinners.first().locator('span[aria-hidden="true"]');+ const samples = await rotor.evaluate(element => {+ 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;+ animation.currentTime = t;+ out.push({t, transform: getComputedStyle(element).transform});+ }+ return {+ duration,+ cssDuration: getComputedStyle(element).animationDuration,+ easing: animation.effect?.getTiming().easing,+ out,+ };+ });+ // The period is the `--duration-slow-min` token the theme resolves.+ expect(samples.duration).toBeGreaterThan(0);+ expect(Number.parseFloat(samples.cssDuration) * 1000).toBeCloseTo(+ samples.duration,+ 3,+ );+ 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 actual = angleOf(transform);+ const error = Math.min(+ Math.abs(actual - expected),+ 360 - Math.abs(actual - expected),+ );+ expect(error, `angle at ${t.toFixed(1)} ms`).toBeLessThan(0.5);+ }+});++test('reduced motion slows the ring to 3 s per turn, as before, still clockwise and still turning', async ({+ page,+}) => {+ 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 [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;+ animation.currentTime = t;+ out.push({t, transform: getComputedStyle(element).transform});+ }+ return {+ duration,+ iterations: animation.effect?.getTiming().iterations,+ out,+ };+ });+ // 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(samples.iterations).toBe(Infinity);+ for (const {t, transform} of samples.out) {+ const expected = (360 * t) / samples.duration;+ const actual = angleOf(transform);+ const error = Math.min(+ Math.abs(actual - expected),+ 360 - Math.abs(actual - expected),+ );+ expect(error, `angle at ${t} ms`).toBeLessThan(0.5);+ }+});++test('every ring on the page turns in phase', async ({page}) => {+ await openSizes(page);+ const angles = await page.evaluate(() =>+ Array.from(+ document.querySelectorAll('.astryx-spinner > span[aria-hidden="true"]'),+ ).map(rotor => {+ const [animation] = rotor.getAnimations();+ return {+ startTime: animation.startTime,+ currentTime: animation.currentTime,+ };+ }),+ );+ expect(angles).toHaveLength(4);+ for (const angle of angles) {+ expect(angle.startTime).toBe(0);+ expect(angle.currentTime).toBe(angles[0].currentTime);+ }+});++test('storyboard: one revolution, frame by frame @storyboard', async ({+ page,+}, testInfo) => {+ 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 {storyboard} = await animationStoryboard(page, {+ name: 'spinner-ring-cycle',+ clip: xl,+ scope: xl,+ columns: 12,+ cellScale: 2,+ times: timeline(duration - 1),+ measure: async () => ({+ angle: angleOf(+ await rotor.evaluate(element => getComputedStyle(element).transform),+ ),+ }),+ });+ // The trace is the assertion: every frame sits at 360 × t / P, so the ring+ // never stalls, jumps or reverses inside a period.+ for (const frame of storyboard.frames) {+ const expected = ((360 * frame.t) / duration) % 360;+ const actual = Number(frame.data.angle);+ const error = Math.min(+ Math.abs(actual - expected),+ 360 - Math.abs(actual - expected),+ );+ expect(error, `angle at ${frame.label}`).toBeLessThan(0.5);+ }+ await storyboard.write(testInfo, {+ story: 'core-spinner--sizes (xl)',+ duration,+ });+});diff --git a/packages/core/src/Tokenizer/__tests__/TokenizerEndLane.a11y.chromium.spec.ts b/packages/core/src/Tokenizer/__tests__/TokenizerEndLane.a11y.chromium.spec.tsindex 965b8302ab..6384de041c 100644--- a/packages/core/src/Tokenizer/__tests__/TokenizerEndLane.a11y.chromium.spec.ts+++ b/packages/core/src/Tokenizer/__tests__/TokenizerEndLane.a11y.chromium.spec.ts@@ -367,9 +367,10 @@ for (const direction of ['ltr', 'rtl'] as const) {const search = page.getByRole('combobox');const cdp = await page.context().newCDPSession(page);await cdp.send('Performance.enable');- // Style recalculations over a short window: a ticking ring animation- // recalculates every frame (about 30 in 500ms), an unrendered one does- // not. The idle allowance absorbs a stray one-off recalculation.+ // Style recalculations over a short window: an unrendered ring costs+ // none. The idle allowance absorbs a stray one-off recalculation. The+ // busy ring turns on the compositor, so it is checked by its running+ // animation rather than by recalculations.const recalcsOver = async (ms: number) => {const count = async () => {const {metrics} = await cdp.send('Performance.getMetrics');@@ -390,6 +391,9 @@ for (const direction of ['ltr', 'rtl'] as const) {return {hidden: spinner.getAttribute('aria-hidden') === 'true',width: spinner.getBoundingClientRect().width,+ turning: spinner+ .getAnimations({subtree: true})+ .some(animation => animation.playState === 'running'),};});const idle = await spinnerState();@@ -400,7 +404,7 @@ for (const direction of ['ltr', 'rtl'] as const) {await expect(search).toHaveAttribute('aria-busy', 'true');const busy = await spinnerState();expect(busy.hidden).toBe(false);- expect(await recalcsOver(500)).toBeGreaterThanOrEqual(10);+ expect(busy.turning).toBe(true);expect(busy.width).toBe(idle.width);});diff --git a/packages/core/src/__tests__/stylexDeclarations.ts b/packages/core/src/__tests__/stylexDeclarations.tsindex 4bcbc7464b..230a1b8f83 100644--- a/packages/core/src/__tests__/stylexDeclarations.ts+++ b/packages/core/src/__tests__/stylexDeclarations.ts@@ -30,7 +30,8 @@* the property.*/export function declaredValue(el: Element, property: string): string | null {- const classes = new Set(el.className.split(' '));+ // `classList`, not `className`: an svg element's `className` is not a string.+ const classes = new Set(Array.from(el.classList));let value: string | null = null;for (const sheet of Array.from(document.styleSheets)) {for (const rule of Array.from(sheet.cssRules)) {