Skip to content

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

TypeScript

fix(CircularProgress): a value change keeps moving while JavaScript runs (#8232)

Christopher Chedeau4426e15206de
diff --git a/packages/lab/src/CircularProgress/CircularProgress.test.tsx b/packages/lab/src/CircularProgress/CircularProgress.test.tsx
index 31d2c43f45..dd056066b0 100644
--- a/packages/lab/src/CircularProgress/CircularProgress.test.tsx
+++ b/packages/lab/src/CircularProgress/CircularProgress.test.tsx
@@ -1,9 +1,31 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import {CircularProgress} from './CircularProgress';
+/**
+ * The Web Animations timing objects the component probes the theme's easing
+ * with (`easingOf`). jsdom has none, so a test that stubs `animate` supplies
+ * these too: linear, so progress is the elapsed fraction.
+ */
+function stubLinearTiming() {
+ class LinearEffect {
+ time = 0;
+ getComputedTiming() {
+ return {progress: this.time};
+ }
+ }
+ class LinearProbe {
+ constructor(private effect: LinearEffect) {}
+ set currentTime(ms: number) {
+ this.effect.time = ms / 1000;
+ }
+ }
+ vi.stubGlobal('KeyframeEffect', LinearEffect);
+ vi.stubGlobal('Animation', LinearProbe);
+}
+
describe('CircularProgress', () => {
it('renders with default props', () => {
render(<CircularProgress value={50} label="Progress" />);
@@ -180,19 +202,376 @@ describe('CircularProgress', () => {
}
});
- it('computes stroke-dashoffset from value', () => {
+ it("turns the fill's halves and leading cap from the value", () => {
+ const turnsAt = (value: number) => {
+ const {container, unmount} = render(
+ <CircularProgress value={value} size="md" label="Progress" />,
+ );
+ const fill = container.querySelector(
+ '.astryx-circular-progress-fill',
+ ) as HTMLElement;
+ const [right, left] = Array.from(
+ fill.querySelectorAll<HTMLElement>(':scope > span > span'),
+ ).map(layer => `${layer.style.transform} ${layer.style.opacity}`);
+ const cap = fill.querySelector<HTMLElement>(':scope > span:last-child');
+ const start = fill.querySelector<SVGPathElement>(':scope > svg path');
+ const result = {
+ right,
+ left,
+ cap: cap?.style.transform,
+ caps: [cap?.style.opacity, start?.style.opacity],
+ };
+ unmount();
+ return result;
+ };
+ // The right half fills over the first half of the value, the left half
+ // over the second; the leading cap turns with the value.
+ // A half parked at the edge of its half is hidden (no hairline at 6).
+ expect(turnsAt(0)).toEqual({
+ right: 'rotate(0deg) 0',
+ left: 'rotate(180deg) 0',
+ cap: 'rotate(0deg)',
+ caps: ['0', '0'],
+ });
+ expect(turnsAt(25)).toEqual({
+ right: 'rotate(90deg) 1',
+ left: 'rotate(180deg) 0',
+ cap: 'rotate(90deg)',
+ caps: ['1', '1'],
+ });
+ expect(turnsAt(75)).toEqual({
+ right: 'rotate(180deg) 1',
+ left: 'rotate(270deg) 1',
+ cap: 'rotate(270deg)',
+ caps: ['1', '1'],
+ });
+ expect(turnsAt(100)).toEqual({
+ right: 'rotate(180deg) 1',
+ left: 'rotate(360deg) 1',
+ cap: 'rotate(360deg)',
+ caps: ['1', '1'],
+ });
+ });
+
+ it("draws each half as half the ring's stroke, under the fill theming target", () => {
const {container} = render(
- <CircularProgress value={25} max={100} size="md" label="Progress" />,
+ <CircularProgress value={25} size="md" label="Progress" />,
);
- // circumference = 2π * 22 ≈ 138.23; offset = circumference * (1 - 0.25)
const fill = container.querySelector('.astryx-circular-progress-fill');
expect(fill).not.toBeNull();
- expect(
- parseFloat(fill!.getAttribute('stroke-dasharray') ?? ''),
- ).toBeCloseTo(138.23, 1);
- expect(
- parseFloat(fill!.getAttribute('stroke-dashoffset') ?? ''),
- ).toBeCloseTo(103.67, 1);
+ expect(fill).toHaveAttribute('aria-hidden', 'true');
+ const halves = fill!.querySelectorAll('circle');
+ expect(halves).toHaveLength(2);
+ // circumference = 2π * 22 ≈ 138.23: half of it drawn, from 6 o'clock to 12.
+ for (const half of halves) {
+ const [dash, gap] = (half.getAttribute('stroke-dasharray') ?? '')
+ .split(' ')
+ .map(Number);
+ expect(dash).toBeCloseTo(138.23 / 2, 1);
+ expect(gap).toBeCloseTo(138.23, 1);
+ expect(half).toHaveAttribute('transform', 'rotate(90 24 24)');
+ // The color comes from the target's inherited stroke, never the part.
+ expect(half).not.toHaveAttribute('stroke');
+ }
+ });
+
+ it('animates a value change from where the arc is drawn, each half on time', () => {
+ const calls: {keyframes: Keyframe[]; options: KeyframeAnimationOptions}[] =
+ [];
+ stubLinearTiming();
+ const original = Element.prototype.animate;
+ const originalStyle = window.getComputedStyle;
+ Element.prototype.animate = function (
+ this: Element,
+ keyframes: Keyframe[],
+ options: KeyframeAnimationOptions,
+ ) {
+ calls.push({keyframes, options});
+ return {
+ cancel() {},
+ playState: 'running',
+ effect: {getComputedTiming: () => ({progress: 0})},
+ onfinish: null,
+ } as unknown as Animation;
+ } as typeof Element.prototype.animate;
+ window.getComputedStyle = ((element: Element) => {
+ const real = originalStyle(element);
+ if (element.classList.contains('astryx-circular-progress-fill')) {
+ return {
+ ...real,
+ transitionDuration: '400ms',
+ transitionTimingFunction: 'linear',
+ } as CSSStyleDeclaration;
+ }
+ return real;
+ }) as typeof window.getComputedStyle;
+ try {
+ const {rerender} = render(
+ <CircularProgress value={20} size="md" label="Progress" />,
+ );
+ expect(calls).toHaveLength(0);
+ rerender(<CircularProgress value={80} size="md" label="Progress" />);
+ expect(calls).toHaveLength(4);
+ const [right, left, cap, start] = calls;
+ for (const call of calls) {
+ expect(call.options.duration).toBe(400);
+ expect(call.options.easing).toBe('linear');
+ }
+ const angle = (frame: Keyframe) =>
+ Number(/rotate\(([-\d.]+)deg\)/.exec(String(frame.transform))?.[1]);
+ // From 20% (72deg) to 80% (288deg); linear, so the arc crosses 6
+ // o'clock half way through.
+ expect(angle(cap.keyframes[0])).toBeCloseTo(72, 5);
+ expect(angle(cap.keyframes.at(-1)!)).toBeCloseTo(288, 5);
+ const crossing = right.keyframes.findIndex(f => angle(f) === 180);
+ expect(right.keyframes[crossing].offset).toBeCloseTo(0.5, 5);
+ expect(angle(left.keyframes[crossing])).toBe(180);
+ expect(
+ left.keyframes.slice(0, crossing + 1).every(f => angle(f) === 180),
+ ).toBe(true);
+ expect(angle(left.keyframes.at(-1)!)).toBeCloseTo(288, 5);
+ // Hidden until the arc passes 6 o'clock, then shown at once.
+ expect(left.keyframes[crossing].opacity).toBe(0);
+ expect(left.keyframes[crossing + 1].opacity).toBe(1);
+ expect(
+ Number(left.keyframes[crossing + 1].offset) -
+ Number(left.keyframes[crossing].offset),
+ ).toBeLessThanOrEqual(1e-4);
+ expect(start.keyframes.every(f => f.opacity === 1)).toBe(true);
+ } finally {
+ Element.prototype.animate = original;
+ vi.unstubAllGlobals();
+ window.getComputedStyle = originalStyle;
+ }
+ });
+
+ it('steps the left half at once when the arc shrinks through 6 o\u2019clock', () => {
+ const calls: Keyframe[][] = [];
+ stubLinearTiming();
+ const original = Element.prototype.animate;
+ const originalStyle = window.getComputedStyle;
+ Element.prototype.animate = function (
+ this: Element,
+ keyframes: Keyframe[],
+ ) {
+ calls.push(keyframes);
+ return {
+ cancel() {},
+ playState: 'running',
+ effect: {getComputedTiming: () => ({progress: 0})},
+ onfinish: null,
+ } as unknown as Animation;
+ } as typeof Element.prototype.animate;
+ window.getComputedStyle = ((element: Element) => {
+ const real = originalStyle(element);
+ if (element.classList.contains('astryx-circular-progress-fill')) {
+ return {
+ ...real,
+ transitionDuration: '300ms',
+ transitionTimingFunction: 'linear',
+ } as CSSStyleDeclaration;
+ }
+ return real;
+ }) as typeof window.getComputedStyle;
+ try {
+ const {rerender} = render(
+ <CircularProgress value={80} size="md" label="Progress" />,
+ );
+ rerender(<CircularProgress value={20} size="md" label="Progress" />);
+ const [, left] = calls;
+ const angle = (frame: Keyframe) =>
+ Number(/rotate\(([-\d.]+)deg\)/.exec(String(frame.transform))?.[1]);
+ // Fully shown wherever it still draws part of the arc...
+ for (const frame of left) {
+ if (angle(frame) > 180) {
+ expect(frame.opacity, `at ${frame.offset}`).toBe(1);
+ }
+ }
+ // ...and hidden at once, never faded across a sample interval.
+ for (let i = 1; i < left.length; i += 1) {
+ if (left[i].opacity !== left[i - 1].opacity) {
+ expect(
+ Number(left[i].offset) - Number(left[i - 1].offset),
+ ).toBeLessThanOrEqual(1e-4);
+ }
+ }
+ expect(left.at(-1)!.opacity).toBe(0);
+ } finally {
+ Element.prototype.animate = original;
+ vi.unstubAllGlobals();
+ window.getComputedStyle = originalStyle;
+ }
+ });
+
+ it('restarts an interrupted eased change from where its arc is drawn', () => {
+ const calls: Keyframe[][] = [];
+ const original = Element.prototype.animate;
+ const originalStyle = window.getComputedStyle;
+ // An ease-in curve (t²) evaluated the way the component probes it.
+ class EaseInEffect {
+ time = 0;
+ getComputedTiming() {
+ return {progress: this.time * this.time};
+ }
+ }
+ class Probe {
+ constructor(private effect: EaseInEffect) {}
+ set currentTime(ms: number) {
+ this.effect.time = ms / 1000;
+ }
+ }
+ vi.stubGlobal('KeyframeEffect', EaseInEffect);
+ vi.stubGlobal('Animation', Probe);
+ Element.prototype.animate = function (
+ this: Element,
+ keyframes: Keyframe[],
+ ) {
+ calls.push(keyframes);
+ // Every running change is half way through its time.
+ return {
+ cancel() {},
+ playState: 'running',
+ effect: {getComputedTiming: () => ({progress: 0.5})},
+ onfinish: null,
+ } as unknown as Animation;
+ } as typeof Element.prototype.animate;
+ window.getComputedStyle = ((element: Element) => {
+ const real = originalStyle(element);
+ if (element.classList.contains('astryx-circular-progress-fill')) {
+ return {
+ ...real,
+ transitionDuration: '400ms',
+ transitionTimingFunction: 'ease-in',
+ } as CSSStyleDeclaration;
+ }
+ return real;
+ }) as typeof window.getComputedStyle;
+ try {
+ const {rerender} = render(
+ <CircularProgress value={0} size="md" label="Progress" />,
+ );
+ rerender(<CircularProgress value={100} size="md" label="Progress" />);
+ calls.length = 0;
+ rerender(<CircularProgress value={50} size="md" label="Progress" />);
+ const cap = calls[2];
+ const angle = (frame: Keyframe) =>
+ Number(/rotate\(([-\d.]+)deg\)/.exec(String(frame.transform))?.[1]);
+ // Half its time into 0% → 100% on ease-in, the arc is drawn at 25%
+ // (90deg), not at the 50% its time fraction would give.
+ expect(angle(cap[0])).toBeCloseTo(90, 5);
+ } finally {
+ Element.prototype.animate = original;
+ window.getComputedStyle = originalStyle;
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('stops a running change when the ring turns indeterminate, and draws the next value at once', () => {
+ const calls: Keyframe[][] = [];
+ let cancelled = 0;
+ stubLinearTiming();
+ const original = Element.prototype.animate;
+ const originalStyle = window.getComputedStyle;
+ Element.prototype.animate = function (
+ this: Element,
+ keyframes: Keyframe[],
+ ) {
+ calls.push(keyframes);
+ // Every change is half way through its time when the next render comes.
+ return {
+ cancel() {
+ cancelled += 1;
+ },
+ playState: 'running',
+ effect: {getComputedTiming: () => ({progress: 0.5})},
+ onfinish: null,
+ } as unknown as Animation;
+ } as typeof Element.prototype.animate;
+ window.getComputedStyle = ((element: Element) => {
+ const real = originalStyle(element);
+ if (element.classList.contains('astryx-circular-progress-fill')) {
+ return {
+ ...real,
+ transitionDuration: '400ms',
+ transitionTimingFunction: 'linear',
+ } as CSSStyleDeclaration;
+ }
+ return real;
+ }) as typeof window.getComputedStyle;
+ try {
+ const {rerender} = render(
+ <CircularProgress value={0} size="md" label="Progress" />,
+ );
+ rerender(<CircularProgress value={80} size="md" label="Progress" />);
+ expect(calls).toHaveLength(4);
+ rerender(
+ <CircularProgress
+ value={80}
+ isIndeterminate
+ size="md"
+ label="Progress"
+ />,
+ );
+ // The four layers' animations stop with the determinate ring.
+ expect(cancelled).toBe(4);
+ calls.length = 0;
+ // The indeterminate ring never drew the 80% it held, so the next value
+ // draws at once: nothing sweeps back from 80%.
+ rerender(<CircularProgress value={30} size="md" label="Progress" />);
+ expect(calls).toHaveLength(0);
+ // The change after that starts from the 30% now drawn (108deg).
+ rerender(<CircularProgress value={60} size="md" label="Progress" />);
+ expect(calls).toHaveLength(4);
+ const cap = calls[2];
+ const angle = (frame: Keyframe) =>
+ Number(/rotate\(([-\d.]+)deg\)/.exec(String(frame.transform))?.[1]);
+ expect(angle(cap[0])).toBeCloseTo(108, 5);
+ } finally {
+ Element.prototype.animate = original;
+ vi.unstubAllGlobals();
+ window.getComputedStyle = originalStyle;
+ }
+ });
+
+ it('releases a running change when it unmounts', () => {
+ let cancelled = 0;
+ stubLinearTiming();
+ const original = Element.prototype.animate;
+ const originalStyle = window.getComputedStyle;
+ Element.prototype.animate = function () {
+ return {
+ cancel() {
+ cancelled += 1;
+ },
+ playState: 'running',
+ effect: {getComputedTiming: () => ({progress: 0.5})},
+ onfinish: null,
+ } as unknown as Animation;
+ } as typeof Element.prototype.animate;
+ window.getComputedStyle = ((element: Element) => {
+ const real = originalStyle(element);
+ if (element.classList.contains('astryx-circular-progress-fill')) {
+ return {
+ ...real,
+ transitionDuration: '400ms',
+ transitionTimingFunction: 'linear',
+ } as CSSStyleDeclaration;
+ }
+ return real;
+ }) as typeof window.getComputedStyle;
+ try {
+ const {rerender, unmount} = render(
+ <CircularProgress value={0} size="md" label="Progress" />,
+ );
+ rerender(<CircularProgress value={80} size="md" label="Progress" />);
+ unmount();
+ // The change's cleanup cancels the four layers' animations.
+ expect(cancelled).toBe(4);
+ } finally {
+ Element.prototype.animate = original;
+ vi.unstubAllGlobals();
+ window.getComputedStyle = originalStyle;
+ }
});
it('handles zero max gracefully', () => {
diff --git a/packages/lab/src/CircularProgress/CircularProgress.tsx b/packages/lab/src/CircularProgress/CircularProgress.tsx
index b656f34358..1b28622da6 100644
--- a/packages/lab/src/CircularProgress/CircularProgress.tsx
+++ b/packages/lab/src/CircularProgress/CircularProgress.tsx
@@ -4,7 +4,8 @@
/**
* @file CircularProgress.tsx
- * @input Uses React, useId, stylex, SVG, color/spacing/duration/ease tokens
+ * @input Uses React (useId, refs, layout effects), stylex, SVG, Web
+ * Animations, color/spacing/duration/ease tokens
* @output Exports CircularProgress component, CircularProgressProps, CircularProgressSize, CircularProgressVariant types
* @position Core implementation; consumed by index.ts
*
@@ -15,7 +16,7 @@
* - /apps/storybook/stories/CircularProgress.stories.tsx (storybook stories)
*/
-import {useId, type ReactNode} from 'react';
+import {useId, useLayoutEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
@@ -55,6 +56,9 @@ export type CircularProgressVariant = keyof CircularProgressVariantMap;
export type CircularProgressSize = 'sm' | 'md' | 'lg';
+/** How far a turning layer's drawing reaches past the ring's box, in px. */
+const FILL_BLEED = 2;
+
const SIZE_CONFIG = {
sm: {diameter: 32, strokeWidth: 3},
md: {diameter: 48, strokeWidth: 4},
@@ -194,13 +198,75 @@ const styles = stylex.create({
fill: 'none',
stroke: colorVars['--color-track'],
},
+ // The determinate fill moves on the compositor so a value change keeps
+ // moving while a script runs (a `stroke-dashoffset` transition repaints on
+ // the main thread every frame and stops). Two half-rings, each a static
+ // half-circle stroke in a layer turned by `transform` and clipped to its
+ // half of the box, draw the arc: the right half turns from 0 to 180deg over
+ // the first half of the value, the left half over the second. Two round
+ // caps close the arc's ends: one fixed at 12 o'clock, one turning with the
+ // value. The ring is drawn clockwise in either direction, as before.
+ //
+ // The theme's duration and easing still time a change: they are declared
+ // here and read back when the value changes (`transition-property: none`,
+ // so nothing transitions on its own), in every motion setting, as the
+ // stroke's transition did.
fill: {
- fill: 'none',
- strokeLinecap: 'round',
- transitionProperty: 'stroke-dashoffset',
+ position: 'absolute',
+ inset: 0,
+ // Clip to the ring's box, as the stroked circle's svg did.
+ overflow: 'hidden',
+ pointerEvents: 'none',
+ transitionProperty: 'none',
transitionDuration: durationVars['--duration-medium'],
transitionTimingFunction: easeVars['--ease-standard'],
},
+ fillHalf: {
+ position: 'absolute',
+ top: 0,
+ width: '50%',
+ height: '100%',
+ overflow: 'hidden',
+ },
+ fillHalfRight: {
+ left: '50%',
+ },
+ fillHalfLeft: {
+ left: 0,
+ },
+ // A layer the size of the ring inside its half, so it turns about the
+ // ring's center.
+ fillTurn: {
+ position: 'absolute',
+ top: 0,
+ width: '200%',
+ height: '100%',
+ willChange: 'transform, opacity',
+ },
+ fillTurnRight: {
+ left: '-100%',
+ },
+ fillTurnLeft: {
+ left: 0,
+ },
+ fillCap: {
+ position: 'absolute',
+ inset: 0,
+ willChange: 'transform, opacity',
+ },
+ // A turning layer's drawing reaches a little past the ring's box, so its
+ // antialiased outer edge is drawn whole before the layer turns (the box,
+ // not the drawing, then clips it).
+ fillShape: {
+ display: 'block',
+ fill: 'none',
+ margin: -FILL_BLEED,
+ },
+ fillCapShape: {
+ display: 'block',
+ fill: 'none',
+ strokeLinecap: 'round',
+ },
fillIndeterminate: {
fill: 'none',
strokeLinecap: 'round',
@@ -299,6 +365,132 @@ function defaultFormatValueLabel(value: number, max: number): string {
return `${pct}%`;
}
+/**
+ * Each half-ring's turn and the leading cap's for a filled share `p` (0–1),
+ * and which parts show. A half-ring parked at the edge of its half (the right
+ * one at 0, the left one until the value passes half) is hidden, so its
+ * antialiased end never leaves a hairline at 6 o'clock.
+ */
+function fillTurns(p: number) {
+ const turn = 360 * p;
+ return {
+ right: Math.min(Math.max(turn, 0), 180),
+ left: Math.min(Math.max(turn, 180), 360),
+ cap: turn,
+ rightShown: p > 0 ? 1 : 0,
+ leftShown: p > 0.5 ? 1 : 0,
+ caps: p > 0 ? 1 : 0,
+ };
+}
+
+/** A CSS time (`410ms`, `0.41s`, or a list's first entry) in milliseconds. */
+function parseTime(value: string): number {
+ const first = value.split(',')[0]?.trim() ?? '';
+ const amount = Number.parseFloat(first);
+ if (!Number.isFinite(amount)) {
+ return 0;
+ }
+ return first.endsWith('ms') ? amount : amount * 1000;
+}
+
+/**
+ * The theme's easing as a function of time (0–1), evaluated by the browser
+ * itself through a detached animation, so any CSS easing works. It runs only
+ * where Web Animations exists (its caller returns first otherwise), on the
+ * fill's computed `transition-timing-function`: one easing, which a browser
+ * always reports as valid CSS.
+ */
+function easingOf(easing: string): (t: number) => number {
+ const effect = new KeyframeEffect(null, null, {
+ duration: 1000,
+ easing,
+ fill: 'both',
+ });
+ const probe = new Animation(effect);
+ return t => {
+ probe.currentTime = t * 1000;
+ return effect.getComputedTiming().progress ?? t;
+ };
+}
+
+/**
+ * Keyframes for a change from `from` to `to` (filled shares), sampled once a
+ * frame on the theme's easing, with an extra sample exactly where the arc
+ * crosses 12 or 6 o'clock so each half stops and starts on time.
+ */
+function fillKeyframes(
+ from: number,
+ to: number,
+ duration: number,
+ ease: (t: number) => number,
+) {
+ const count = Math.max(8, Math.ceil(duration / (1000 / 60)));
+ const grid = Array.from({length: count + 1}, (_, i) => i / count);
+ const at = (t: number) => from + (to - from) * ease(t);
+ // Where the eased path passes half (p = 0.5): a sample there, and one just
+ // after it, so the halves hand over on time and the left half's
+ // visibility steps rather than fades.
+ const crossings: number[] = [];
+ for (let i = 0; i < count; i++) {
+ const a = grid[i];
+ const b = grid[i + 1];
+ const fa = at(a) - 0.5;
+ const fb = at(b) - 0.5;
+ if (fa === 0) {
+ crossings.push(a);
+ } else if (fa * fb < 0) {
+ let low = a;
+ let high = b;
+ for (let k = 0; k < 24; k++) {
+ const mid = (low + high) / 2;
+ if ((at(low) - 0.5) * (at(mid) - 0.5) <= 0) {
+ high = mid;
+ } else {
+ low = mid;
+ }
+ }
+ crossings.push((low + high) / 2);
+ }
+ }
+ const times = [
+ ...new Set([
+ ...grid,
+ ...crossings,
+ ...crossings.map(c => c + 1e-4).filter(t => t < 1),
+ ]),
+ ].sort((x, y) => x - y);
+ const frames = times.map(t => ({t, ...fillTurns(t === 1 ? to : at(t))}));
+ // The sample at a crossing sits exactly on half, where the left half reads
+ // as hidden. Give it the side the arc is leaving instead, so the left half
+ // steps at once both ways: shrinking through half, it used to fade out
+ // from the sample before, while it still drew part of the arc (a lighter
+ // band between the end cap and 6 o'clock for a frame).
+ const onHalf = new Set(crossings);
+ for (let i = 1; i < frames.length; i += 1) {
+ if (onHalf.has(frames[i].t) || (frames[i].t === 1 && to === 0.5)) {
+ frames[i].leftShown = frames[i - 1].leftShown;
+ }
+ }
+ return {
+ right: frames.map(f => ({
+ offset: f.t,
+ transform: `rotate(${f.right}deg)`,
+ opacity: f.rightShown,
+ })),
+ left: frames.map(f => ({
+ offset: f.t,
+ transform: `rotate(${f.left}deg)`,
+ opacity: f.leftShown,
+ })),
+ cap: frames.map(f => ({
+ offset: f.t,
+ transform: `rotate(${f.cap}deg)`,
+ opacity: f.caps,
+ })),
+ start: frames.map(f => ({offset: f.t, opacity: f.caps})),
+ };
+}
+
/**
* A circular/radial progress indicator that shows completion as a ring.
*
@@ -348,7 +540,6 @@ export function CircularProgress({
const safeMax = Number.isFinite(max) ? max : 0;
const clampedValue = Math.min(Math.max(0, safeValue), safeMax);
const percentage = safeMax > 0 ? clampedValue / safeMax : 0;
- const dashoffset = circumference * (1 - percentage);
const valueText = formatValueLabel(clampedValue, safeMax);
const center = diameter / 2;
@@ -361,6 +552,110 @@ export function CircularProgress({
const fillVariant = isDisabled ? 'disabled' : variant;
const trackVariant = isDisabled ? 'neutral' : variant;
+ // A value change turns the fill's layers with Web Animations on the
+ // compositor, from wherever the arc is drawn now (mid-change, the running
+ // change's own curve says where) to the new value, on the theme's
+ // duration and easing. What renders is always the resting state, so a
+ // first render, a render without script, or a skipped animation shows the
+ // value.
+ const fillRef = useRef<HTMLSpanElement | null>(null);
+ const rightRef = useRef<HTMLSpanElement | null>(null);
+ const leftRef = useRef<HTMLSpanElement | null>(null);
+ const capRef = useRef<HTMLSpanElement | null>(null);
+ const startRef = useRef<SVGPathElement | null>(null);
+ // Where the arc is drawn: the value at rest, or, when a change is
+ // interrupted, the point its own curve has reached. A change's cleanup
+ // records it and releases the change's animations (react-component-runtime
+ // INV3), so the next change starts from there and an unmount or a switch to
+ // indeterminate leaves nothing running. While indeterminate no value is
+ // drawn (null): the ring draws its own arc, not the value it holds, so the
+ // next value draws at once instead of sweeping from that held value.
+ const drawn = useRef<number | null>(percentage);
+ useLayoutEffect(() => {
+ const from = drawn.current;
+ if (isIndeterminate) {
+ drawn.current = null;
+ return;
+ }
+ if (from === null || from === percentage) {
+ drawn.current = percentage;
+ return;
+ }
+ const fill = fillRef.current;
+ const layers = [
+ rightRef.current,
+ leftRef.current,
+ capRef.current,
+ startRef.current,
+ ];
+ drawn.current = percentage;
+ if (
+ fill == null ||
+ layers.some(layer => typeof layer?.animate !== 'function')
+ ) {
+ return;
+ }
+ const style = getComputedStyle(fill);
+ const duration = parseTime(style.transitionDuration);
+ if (duration <= 0) {
+ return;
+ }
+ const ease = easingOf(style.transitionTimingFunction);
+ const frames = fillKeyframes(from, percentage, duration, ease);
+ const timing: KeyframeAnimationOptions = {
+ duration,
+ easing: 'linear',
+ fill: 'backwards',
+ };
+ const [right, left, cap, start] = layers as [
+ HTMLElement,
+ HTMLElement,
+ HTMLElement,
+ SVGElement,
+ ];
+ const animations = [
+ right.animate(frames.right, timing),
+ left.animate(frames.left, timing),
+ cap.animate(frames.cap, timing),
+ start.animate(frames.start, timing),
+ ];
+ return () => {
+ const [first] = animations;
+ const progress =
+ first.playState !== 'finished'
+ ? Number(first.effect?.getComputedTiming().progress ?? 1)
+ : 1;
+ // `progress` is the change's linear time fraction; the arc is drawn on
+ // its easing, so the eased position is where it is.
+ drawn.current = from + (percentage - from) * ease(progress);
+ for (const animation of animations) {
+ animation.cancel();
+ }
+ };
+ }, [percentage, isIndeterminate]);
+ const turns = fillTurns(percentage);
+ // One half of the ring's stroke, from 6 o'clock clockwise to 12 (the left
+ // half) before its layer turns; butt ends, the caps are drawn apart.
+ const bleedBox = `${-FILL_BLEED} ${-FILL_BLEED} ${diameter + 2 * FILL_BLEED} ${diameter + 2 * FILL_BLEED}`;
+ const halfRing = (
+ <svg
+ width={diameter + 2 * FILL_BLEED}
+ height={diameter + 2 * FILL_BLEED}
+ viewBox={bleedBox}
+ {...stylex.props(styles.fillShape)}>
+ <circle
+ cx={center}
+ cy={center}
+ r={radius}
+ strokeWidth={strokeWidth}
+ strokeDasharray={`${circumference / 2} ${circumference}`}
+ transform={`rotate(90 ${center} ${center})`}
+ />
+ </svg>
+ );
+ // A round cap at 12 o'clock on the ring's centerline (a zero-length stroke).
+ const capPath = `M ${center} ${strokeWidth / 2} h 0`;
+
return (
<div
ref={ref}
@@ -419,22 +714,71 @@ export function CircularProgress({
r={radius}
strokeWidth={strokeWidth}
/>
- ) : (
- <circle
- {...mergeProps(
- themeProps('circular-progress-fill', {variant: fillVariant}),
- stylex.props(styles.fill, variantStyles[fillVariant]),
- )}
- cx={center}
- cy={center}
- r={radius}
- strokeWidth={strokeWidth}
- strokeDasharray={circumference}
- strokeDashoffset={dashoffset}
- />
- )}
+ ) : null}
</svg>
+ {isIndeterminate ? null : (
+ // The determinate fill (see `styles.fill`). Its stroke color is
+ // set on the theming target and inherited by every part.
+ <span
+ ref={fillRef}
+ aria-hidden="true"
+ {...mergeProps(
+ themeProps('circular-progress-fill', {variant: fillVariant}),
+ stylex.props(styles.fill, variantStyles[fillVariant]),
+ )}>
+ <span {...stylex.props(styles.fillHalf, styles.fillHalfRight)}>
+ <span
+ ref={rightRef}
+ {...stylex.props(styles.fillTurn, styles.fillTurnRight)}
+ style={{
+ transform: `rotate(${turns.right}deg)`,
+ opacity: turns.rightShown,
+ }}>
+ {halfRing}
+ </span>
+ </span>
+ <span {...stylex.props(styles.fillHalf, styles.fillHalfLeft)}>
+ <span
+ ref={leftRef}
+ {...stylex.props(styles.fillTurn, styles.fillTurnLeft)}
+ style={{
+ transform: `rotate(${turns.left}deg)`,
+ opacity: turns.leftShown,
+ }}>
+ {halfRing}
+ </span>
+ </span>
+ <svg
+ width={diameter}
+ height={diameter}
+ viewBox={`0 0 ${diameter} ${diameter}`}
+ {...stylex.props(styles.fillCap, styles.fillCapShape)}>
+ <path
+ ref={startRef}
+ d={capPath}
+ strokeWidth={strokeWidth}
+ style={{opacity: turns.caps}}
+ />
+ </svg>
+ <span
+ ref={capRef}
+ {...stylex.props(styles.fillCap)}
+ style={{
+ transform: `rotate(${turns.cap}deg)`,
+ opacity: turns.caps,
+ }}>
+ <svg
+ width={diameter + 2 * FILL_BLEED}
+ height={diameter + 2 * FILL_BLEED}
+ viewBox={bleedBox}
+ {...stylex.props(styles.fillCapShape, styles.fillShape)}>
+ <path d={capPath} strokeWidth={strokeWidth} />
+ </svg>
+ </span>
+ </span>
+ )}
+
{centerContent != null && (
<div {...stylex.props(styles.children)}>
{children != null ? (
diff --git a/packages/lab/src/CircularProgress/__tests__/CircularProgress.a11y.states.ts b/packages/lab/src/CircularProgress/__tests__/CircularProgress.a11y.states.ts
index 9362050488..71ab1de42b 100644
--- a/packages/lab/src/CircularProgress/__tests__/CircularProgress.a11y.states.ts
+++ b/packages/lab/src/CircularProgress/__tests__/CircularProgress.a11y.states.ts
@@ -99,8 +99,8 @@ export const CIRCULAR_PROGRESS_EXCLUSIONS = [
},
{
id: 'ring-geometry',
- owner: 'CircularProgress.test.tsx size and dash-offset tests',
+ owner: 'CircularProgress.test.tsx size and half-ring turn tests',
reason:
- 'Ring size, stroke, and the dash offset that draws the completed arc are paint geometry; this binding proves the programmatic value they illustrate.',
+ "Ring size, stroke, and the half-rings' turns that draw the completed arc are paint geometry; this binding proves the programmatic value they illustrate.",
},
] as const;
diff --git a/packages/lab/src/CircularProgress/__tests__/CircularProgressMotion.a11y.chromium.spec.ts b/packages/lab/src/CircularProgress/__tests__/CircularProgressMotion.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..10cd04c372
--- /dev/null
+++ b/packages/lab/src/CircularProgress/__tests__/CircularProgressMotion.a11y.chromium.spec.ts
@@ -0,0 +1,886 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CircularProgressMotion.a11y.chromium.spec.ts
+ * @input Built CircularProgress stories in real Chromium (Web Animations
+ * seeking, CDP screencast, tracing)
+ * @output Browser evidence that a determinate value change keeps moving while
+ * a script holds the main thread and paints nothing per frame, that the
+ * ring at rest draws what the stroked circle drew, and that the arc stays
+ * one piece as it crosses 6 o'clock. Writes a storyboard (contact sheet +
+ * JSON trace) to test-results/circular-progress-motion/.
+ * @position Chromium proof for CircularProgress's compositor fill; the iOS
+ * Safari side is a simulator recording attached to the pull request.
+ *
+ * SYNC: Keep in step with CircularProgress.tsx (`styles.fill` and the
+ * keyframes of a value change).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const EVIDENCE = path.resolve(
+ process.env.ASTRYX_MOTION_EVIDENCE ??
+ path.join('test-results', 'circular-progress-motion'),
+);
+const STORY = 'lab-circularprogress--default';
+const DPR = 3;
+// The lg ring: 64px across, a 5px stroke.
+const DIAMETER = 64;
+const STROKE = 5;
+
+test.use({viewport: {width: 240, height: 160}, deviceScaleFactor: DPR});
+
+type Box = {x: number; y: number; width: number; height: number};
+
+async function open(page: Page, value: number) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ await expect(page.getByRole('progressbar')).toBeVisible();
+ await setArgs(page, {value, size: 'lg'});
+ await page.waitForTimeout(800);
+}
+
+/** Re-renders the story with new args and resolves once it rendered. */
+async function setArgs(page: Page, updatedArgs: Record<string, unknown>) {
+ await page.evaluate(
+ async ({storyId, args}) =>
+ new Promise<void>(resolve => {
+ const channel = (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ emit: (event: string, payload: unknown) => void;
+ once: (event: string, handler: () => void) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__;
+ channel.once('storyRendered', () => resolve());
+ channel.emit('updateStoryArgs', {storyId, updatedArgs: args});
+ setTimeout(resolve, 1500);
+ }),
+ {storyId: STORY, args: updatedArgs},
+ );
+}
+
+/** Sets a value and pauses the change's animations the moment they start. */
+async function changeAndPause(page: Page, value: number) {
+ return page.evaluate(
+ async ({storyId, updatedArgs}) =>
+ new Promise<number>((resolve, reject) => {
+ const before = new Set(document.getAnimations());
+ const poll = () => {
+ const fresh = document
+ .getAnimations()
+ .filter(animation => !before.has(animation));
+ if (fresh.length >= 4) {
+ for (const animation of fresh) {
+ animation.pause();
+ }
+ resolve(fresh.length);
+ return;
+ }
+ requestAnimationFrame(poll);
+ };
+ (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ emit: (event: string, payload: unknown) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__.emit('updateStoryArgs', {
+ storyId,
+ updatedArgs,
+ });
+ requestAnimationFrame(poll);
+ setTimeout(() => reject(new Error('no animation started')), 3000);
+ }),
+ {storyId: STORY, updatedArgs: {value}},
+ );
+}
+
+/** Seeks every running change animation to `time` (ms). */
+async function seek(page: Page, time: number) {
+ await page.evaluate(t => {
+ for (const animation of document.getAnimations()) {
+ const duration = Number(animation.effect?.getTiming().duration);
+ animation.currentTime = Math.min(t, duration - 0.01);
+ }
+ }, time);
+}
+
+async function ringBox(page: Page): Promise<Box> {
+ const box = await page.getByRole('progressbar').boundingBox();
+ if (box == null) {
+ throw new Error('no ring');
+ }
+ return box;
+}
+
+/** The fill and track colors as rgb triples, read from the page. */
+async function colors(page: Page) {
+ return page.evaluate(() => {
+ const parse = (value: string) =>
+ (value.match(/[\d.]+/g) ?? []).slice(0, 3).map(Number);
+ const fill = document.querySelector(
+ '.astryx-circular-progress-fill',
+ ) as Element;
+ const track = document.querySelector(
+ '.astryx-circular-progress-track',
+ ) as Element;
+ return {
+ fill: parse(getComputedStyle(fill).stroke),
+ track: parse(getComputedStyle(track).stroke),
+ };
+ });
+}
+
+/**
+ * For each degree clockwise from 12 o'clock, whether the ring's centerline is
+ * drawn in the fill color in the given screenshot (PNGs of the ring box).
+ */
+async function inkByDegree(
+ page: Page,
+ shots: string[],
+ palette: {fill: number[]; track: number[]},
+): Promise<boolean[][]> {
+ const scratch = await page.context().newPage();
+ try {
+ return await scratch.evaluate(
+ async ({items, fill, track, diameter, stroke}) => {
+ const out: boolean[][] = [];
+ for (const item of items) {
+ const bitmap = await createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ );
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const {data, width} = context.getImageData(
+ 0,
+ 0,
+ bitmap.width,
+ bitmap.height,
+ );
+ const scale = bitmap.width / diameter;
+ const r = ((diameter - stroke) / 2) * scale;
+ const c = (diameter / 2) * scale;
+ const d = (a: number[], b: number[]) =>
+ Math.abs(a[0] - b[0]) +
+ Math.abs(a[1] - b[1]) +
+ Math.abs(a[2] - b[2]);
+ const row: boolean[] = [];
+ for (let degree = 0; degree < 360; degree += 1) {
+ const angle = (degree * Math.PI) / 180;
+ const x = Math.round(c + r * Math.sin(angle));
+ const y = Math.round(c - r * Math.cos(angle));
+ const i = (y * width + x) * 4;
+ const pixel = [data[i], data[i + 1], data[i + 2]];
+ row.push(d(pixel, fill) < d(pixel, track));
+ }
+ out.push(row);
+ }
+ return out;
+ },
+ {items: shots, ...palette, diameter: DIAMETER, stroke: STROKE},
+ );
+ } finally {
+ await scratch.close();
+ }
+}
+
+/**
+ * How many separate pieces are inked around the ring, and the degree where
+ * the piece starting at 12 o'clock ends (the arc's leading end; -1 if 12
+ * o'clock is not inked). The start cap reaches a few degrees back past 12,
+ * so pieces are counted around the circle.
+ */
+function span(row: boolean[]): {pieces: number; last: number} {
+ if (row.every(Boolean)) {
+ return {pieces: 1, last: 359};
+ }
+ let pieces = 0;
+ for (let degree = 0; degree < 360; degree += 1) {
+ if (row[degree] && !row[(degree + 359) % 360]) {
+ pieces += 1;
+ }
+ }
+ let last = -1;
+ if (row[0]) {
+ last = 0;
+ while (last < 359 && row[last + 1]) {
+ last += 1;
+ }
+ }
+ return {pieces, last};
+}
+
+test('a value change keeps moving while a script holds the main thread', async ({
+ page,
+}) => {
+ await open(page, 10);
+ const box = await ringBox(page);
+ const palette = await colors(page);
+ const cdp = await page.context().newCDPSession(page);
+ const raw: {t: number; data: string}[] = [];
+ const acks: Promise<unknown>[] = [];
+ const ackFailures: string[] = [];
+ cdp.on('Page.screencastFrame', frame => {
+ raw.push({
+ t: (frame.metadata.timestamp ?? Date.now() / 1000) * 1000,
+ data: frame.data,
+ });
+ acks.push(
+ cdp
+ .send('Page.screencastFrameAck', {sessionId: frame.sessionId})
+ .catch((error: unknown) => {
+ ackFailures.push(String(error));
+ }),
+ );
+ });
+ await cdp.send('Page.startScreencast', {
+ format: 'png',
+ maxWidth: 240 * DPR,
+ maxHeight: 160 * DPR,
+ everyNthFrame: 1,
+ });
+ await page.waitForTimeout(300);
+ // A value change, one presented frame, then 700 ms of script.
+ const busy = await page.evaluate(
+ async ({storyId}) =>
+ new Promise<{from: number; to: number}>(resolve => {
+ const before = new Set(document.getAnimations());
+ const poll = () => {
+ if (document.getAnimations().filter(a => !before.has(a)).length < 4) {
+ requestAnimationFrame(poll);
+ return;
+ }
+ requestAnimationFrame(() =>
+ setTimeout(() => {
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 700;
+ while (performance.now() < end) {
+ // hold
+ }
+ resolve({from, to: performance.timeOrigin + performance.now()});
+ }),
+ );
+ };
+ (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ emit: (event: string, payload: unknown) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__.emit('updateStoryArgs', {
+ storyId,
+ updatedArgs: {value: 90},
+ });
+ requestAnimationFrame(poll);
+ }),
+ {storyId: STORY},
+ );
+ await page.waitForTimeout(300);
+ await cdp.send('Page.stopScreencast');
+ await Promise.all(acks);
+ await cdp.detach();
+ // A lost acknowledgement stalls the screencast and thins the frames.
+ expect(ackFailures).toEqual([]);
+ // Crop each frame to the ring, then read how far the arc reaches.
+ const scratch = await page.context().newPage();
+ let crops: string[];
+ try {
+ crops = await scratch.evaluate(
+ async ({items, ring}) => {
+ const out: string[] = [];
+ for (const item of items) {
+ const bitmap = await createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ );
+ const scale = bitmap.width / 240;
+ const canvas = new OffscreenCanvas(
+ Math.round(ring.width * scale),
+ Math.round(ring.height * scale),
+ );
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(
+ bitmap,
+ Math.round(ring.x * scale),
+ Math.round(ring.y * scale),
+ canvas.width,
+ canvas.height,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height,
+ );
+ const blob = await canvas.convertToBlob({type: 'image/png'});
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ out.push(btoa(binary));
+ }
+ return out;
+ },
+ {items: raw.map(f => f.data), ring: box},
+ );
+ } finally {
+ await scratch.close();
+ }
+ const rows = await inkByDegree(page, crops, palette);
+ const frames = rows.map((row, i) => ({t: raw[i].t, ...span(row)}));
+ const inside = frames.filter(
+ f => f.t >= busy.from + 20 && f.t <= busy.to - 20,
+ );
+ // The change lasts the theme's 410 ms, so it moves through most of the
+ // block, one piece the whole way, and lands at 90%.
+ const reaches = new Set(inside.map(f => f.last));
+ expect(reaches.size).toBeGreaterThanOrEqual(10);
+ for (const frame of inside) {
+ expect(frame.pieces, `pieces at ${frame.t}`).toBe(1);
+ }
+ for (let i = 1; i < inside.length; i += 1) {
+ expect(inside[i].last).toBeGreaterThanOrEqual(inside[i - 1].last - 1);
+ }
+ expect(
+ Math.abs(frames[frames.length - 1].last - 0.9 * 360),
+ ).toBeLessThanOrEqual(6);
+});
+
+test('a value change lays out and paints nothing per frame', async ({
+ page,
+ browser,
+}) => {
+ await open(page, 20);
+ // Stretch the theme's duration so the trace sits wholly inside the change.
+ await page.evaluate(() =>
+ (
+ document.querySelector('.astryx-circular-progress-fill') as HTMLElement
+ ).style.setProperty('--duration-medium', '3000ms'),
+ );
+ await setArgs(page, {value: 80});
+ await page.waitForTimeout(200);
+ await browser.startTracing(page, {
+ categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'],
+ });
+ await page.waitForTimeout(1000);
+ const moving = await page.evaluate(() =>
+ document.getAnimations().some(a => a.playState === 'running'),
+ );
+ const trace = JSON.parse((await browser.stopTracing()).toString()) as {
+ traceEvents: {
+ name: string;
+ ph: string;
+ pid: number;
+ tid: number;
+ args?: {name?: string};
+ }[];
+ };
+ const mainThreads = new Set(
+ trace.traceEvents
+ .filter(e => e.ph === 'M' && e.name === 'thread_name')
+ .filter(e => e.args?.name === 'CrRendererMain')
+ .map(e => `${e.pid}:${e.tid}`),
+ );
+ const count = (name: string) =>
+ trace.traceEvents.filter(
+ e => e.name === name && mainThreads.has(`${e.pid}:${e.tid}`),
+ ).length;
+ // A full second of the change: nothing lays out or paints. A
+ // stroke-dashoffset transition repainted every frame (36 paints in 410 ms).
+ expect(moving).toBe(true);
+ expect(count('Layout')).toBe(0);
+ expect(count('Paint')).toBe(0);
+});
+
+test('at rest the ring draws what the stroked circle drew', async ({
+ page,
+}, testInfo) => {
+ await open(page, 0);
+ const palette = await colors(page);
+ // The stroked circle the fill used to be, drawn beside the ring with the
+ // same colors: a round-capped arc from 12 o'clock.
+ const values = [0, 1, 10, 25, 49, 50, 51, 75, 99, 100];
+ const results: {value: number; iou: number}[] = [];
+ const pairs: {ours: string; reference: string}[] = [];
+ for (const value of values) {
+ await setArgs(page, {value});
+ await page.waitForTimeout(600);
+ await page.evaluate(
+ ({p, fill, track, diameter, stroke}) => {
+ document.getElementById('reference')?.remove();
+ const r = (diameter - stroke) / 2;
+ const c = diameter / 2;
+ const circumference = 2 * Math.PI * r;
+ const holder = document.createElement('div');
+ holder.id = 'reference';
+ holder.style.cssText =
+ 'position:fixed;left:160px;top:40px;width:64px;height:64px;background:inherit';
+ holder.innerHTML = `<svg width="${diameter}" height="${diameter}" viewBox="0 0 ${diameter} ${diameter}" style="display:block;transform:rotate(-90deg)"><circle cx="${c}" cy="${c}" r="${r}" fill="none" stroke="rgb(${track.join(',')})" stroke-width="${stroke}"/><circle cx="${c}" cy="${c}" r="${r}" fill="none" stroke="rgb(${fill.join(',')})" stroke-width="${stroke}" stroke-linecap="round" stroke-dasharray="${circumference}" stroke-dashoffset="${circumference * (1 - p)}"/></svg>`;
+ document.body.appendChild(holder);
+ },
+ {p: value / 100, ...palette, diameter: DIAMETER, stroke: STROKE},
+ );
+ const ours = (await page.getByRole('progressbar').screenshot()).toString(
+ 'base64',
+ );
+ const reference = (
+ await page.locator('#reference svg').screenshot()
+ ).toString('base64');
+ pairs.push({ours, reference});
+ const scratch = await page.context().newPage();
+ try {
+ const iou = await scratch.evaluate(
+ async ({a, b, fill, track}) => {
+ const decode = async (item: string) => {
+ const bitmap = await createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ );
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ return context.getImageData(0, 0, bitmap.width, bitmap.height);
+ };
+ const [x, y] = await Promise.all([decode(a), decode(b)]);
+ const d = (data: Uint8ClampedArray, i: number, c: number[]) =>
+ Math.abs(data[i] - c[0]) +
+ Math.abs(data[i + 1] - c[1]) +
+ Math.abs(data[i + 2] - c[2]);
+ let both = 0;
+ let either = 0;
+ for (let i = 0; i < x.data.length; i += 4) {
+ const inX = d(x.data, i, fill) < d(x.data, i, track) / 2;
+ const inY = d(y.data, i, fill) < d(y.data, i, track) / 2;
+ if (inX && inY) {
+ both += 1;
+ }
+ if (inX || inY) {
+ either += 1;
+ }
+ }
+ return either === 0 ? 1 : both / either;
+ },
+ {a: ours, b: reference, ...palette},
+ );
+ results.push({value, iou});
+ } finally {
+ await scratch.close();
+ }
+ }
+ await testInfo.attach('ring-parity.json', {
+ body: JSON.stringify(results),
+ contentType: 'application/json',
+ });
+ // Evidence: the stroked circle (top) and the ring (bottom) at each value.
+ const sheet = await page.context().newPage();
+ try {
+ const png = await sheet.evaluate(async items => {
+ const decode = async (item: string) =>
+ createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ );
+ const rows = await Promise.all(
+ items.map(async ({ours, reference}) => ({
+ ours: await decode(ours),
+ reference: await decode(reference),
+ })),
+ );
+ const w = rows[0].ours.width + 12;
+ const h = rows[0].ours.height + 12;
+ const canvas = new OffscreenCanvas(rows.length * w, 2 * h);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.fillStyle = '#fff';
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ rows.forEach(({ours, reference}, i) => {
+ context.drawImage(reference, i * w + 6, 6);
+ context.drawImage(ours, i * w + 6, h + 6);
+ });
+ const blob = await canvas.convertToBlob({type: 'image/png'});
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return btoa(binary);
+ }, pairs);
+ fs.mkdirSync(EVIDENCE, {recursive: true});
+ fs.writeFileSync(
+ path.join(EVIDENCE, 'circular-progress-parity.png'),
+ Buffer.from(png, 'base64'),
+ );
+ fs.writeFileSync(
+ path.join(EVIDENCE, 'circular-progress-parity.json'),
+ JSON.stringify(results, null, 1),
+ );
+ } finally {
+ await sheet.close();
+ }
+ for (const {value, iou} of results) {
+ expect(iou, `IoU at ${value}%`).toBeGreaterThanOrEqual(0.97);
+ }
+});
+
+test("a shrinking change keeps the arc solid as it crosses 6 o'clock", async ({
+ page,
+}) => {
+ // 80% back to 20%, on the theme's easing: the left half-ring must be fully
+ // opaque whenever it draws part of the arc (turned past 180deg), and hide
+ // at once as the arc passes 6 o'clock. It used to fade out over the sample
+ // before the crossing, drawing a lighter band between the end cap and 6
+ // o'clock for a frame.
+ await open(page, 80);
+ // Linear over 300 ms, so the crossing falls exactly on one of the
+ // animation's samples (where the old code read the arc as already hidden).
+ await page.addStyleTag({
+ content:
+ '.astryx-circular-progress-fill{transition-timing-function:linear!important;transition-duration:300ms!important}',
+ });
+ await changeAndPause(page, 20);
+ const duration = await page.evaluate(() =>
+ Number(document.getAnimations()[0]?.effect?.getTiming().duration),
+ );
+ expect(duration).toBe(300);
+ const samples: {time: number; angle: number; opacity: number}[] = [];
+ for (let t = 0; t <= duration; t += duration / 300) {
+ await seek(page, t);
+ samples.push({
+ time: t,
+ ...(await page.evaluate(() => {
+ const [, left] = Array.from(
+ document.querySelectorAll<HTMLElement>(
+ '.astryx-circular-progress-fill > span > span',
+ ),
+ );
+ const style = getComputedStyle(left);
+ const m = new DOMMatrix(style.transform);
+ const angle = ((Math.atan2(m.b, m.a) * 180) / Math.PI + 360) % 360;
+ return {angle, opacity: Number(style.opacity)};
+ })),
+ });
+ }
+ const showing = samples.filter(s => s.angle > 180.5);
+ expect(showing.length).toBeGreaterThan(0);
+ for (const {time, angle, opacity} of showing) {
+ expect(
+ opacity,
+ `at ${time.toFixed(1)} ms, turned ${angle.toFixed(1)}deg`,
+ ).toBe(1);
+ }
+ // It ends hidden, below half.
+ expect(samples[samples.length - 1].opacity).toBe(0);
+});
+
+test("below half nothing of the left half-ring shows at 6 o'clock", async ({
+ page,
+}) => {
+ // The left half-ring parks 4deg short of 6 o'clock until the value passes
+ // half, inside the right half, which its own half clips away: no hairline
+ // or sliver may show just left of 6 o'clock, at any size.
+ await open(page, 0);
+ const palette = await colors(page);
+ for (const size of ['sm', 'md', 'lg'] as const) {
+ // (Below 45% the end cap stays clear of the center line.)
+ for (const value of [1, 10, 25, 40]) {
+ await setArgs(page, {value, size});
+ await page.waitForTimeout(400);
+ const shot = (await page.getByRole('progressbar').screenshot()).toString(
+ 'base64',
+ );
+ const scratch = await page.context().newPage();
+ try {
+ const stray = await scratch.evaluate(
+ async ({item, fill, track}) => {
+ const bitmap = await createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ );
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const {data, width, height} = context.getImageData(
+ 0,
+ 0,
+ bitmap.width,
+ bitmap.height,
+ );
+ const d = (i: number, c: number[]) =>
+ Math.abs(data[i] - c[0]) +
+ Math.abs(data[i + 1] - c[1]) +
+ Math.abs(data[i + 2] - c[2]);
+ // The ring's bottom band, from a quarter of the way in to just
+ // left of the center line: where a parked half-ring's end would
+ // leak.
+ let count = 0;
+ const center = width / 2;
+ for (let y = Math.floor(height * 0.8); y < height; y += 1) {
+ for (let x = Math.floor(width * 0.25); x < center - 1; x += 1) {
+ const i = (y * width + x) * 4;
+ if (d(i, fill) < d(i, track)) {
+ count += 1;
+ }
+ }
+ }
+ return count;
+ },
+ {item: shot, ...palette},
+ );
+ expect(stray, `${size} at ${value}%`).toBe(0);
+ } finally {
+ await scratch.close();
+ }
+ }
+ }
+});
+
+test("the arc stays one piece as it crosses 6 o'clock", async ({page}) => {
+ await open(page, 20);
+ const palette = await colors(page);
+ await changeAndPause(page, 80);
+ const duration = await page.evaluate(() =>
+ Number(document.getAnimations()[0]?.effect?.getTiming().duration),
+ );
+ const shots: string[] = [];
+ const times: number[] = [];
+ for (let t = 0; t <= duration; t += duration / 40) {
+ await seek(page, t);
+ times.push(t);
+ shots.push(
+ (await page.getByRole('progressbar').screenshot()).toString('base64'),
+ );
+ }
+ const rows = await inkByDegree(page, shots, palette);
+ const reaches: number[] = [];
+ rows.forEach((row, i) => {
+ const {pieces, last} = span(row);
+ expect(pieces, `pieces at ${Math.round(times[i])} ms`).toBe(1);
+ reaches.push(last);
+ });
+ // It starts at 20% and ends at 80%, passing 6 o'clock on the way.
+ expect(Math.abs(reaches[0] - 72)).toBeLessThanOrEqual(6);
+ expect(Math.abs(reaches[reaches.length - 1] - 288)).toBeLessThanOrEqual(6);
+ expect(reaches.some(r => r > 170 && r < 190)).toBe(true);
+});
+
+/**
+ * Sets a value and returns how many Web Animations the page started in the
+ * half second after it (counted as `animate()` calls, so a short animation
+ * that has already finished still counts).
+ */
+async function animationsStartedBy(page: Page, value: number) {
+ return page.evaluate(
+ async ({storyId, updatedArgs}) =>
+ new Promise<number>(resolve => {
+ let started = 0;
+ const native = Element.prototype.animate;
+ Element.prototype.animate = function (...args) {
+ started += 1;
+ return native.apply(this, args);
+ };
+ (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ emit: (event: string, payload: unknown) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__.emit('updateStoryArgs', {
+ storyId,
+ updatedArgs,
+ });
+ setTimeout(() => {
+ Element.prototype.animate = native;
+ resolve(started);
+ }, 500);
+ }),
+ {storyId: STORY, updatedArgs: {value}},
+ );
+}
+
+for (const pointer of ['a mouse', 'a finger'] as const) {
+ test.describe(`under reduced motion, with ${pointer}`, () => {
+ test.use(
+ pointer === 'a finger'
+ ? {hasTouch: true, isMobile: true}
+ : {hasTouch: false, isMobile: false},
+ );
+
+ test('a new value moves over the theme\u2019s duration, as without', async ({
+ page,
+ }) => {
+ // Progress indicators sit outside design:reduced-motion's scope; a
+ // change times its four layers by the theme's duration in either motion
+ // setting, as the stroke's transition did.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await open(page, 10);
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(pointer === 'a finger');
+ expect(await animationsStartedBy(page, 90)).toBe(4);
+ await page.emulateMedia({reducedMotion: 'no-preference'});
+ expect(await animationsStartedBy(page, 30)).toBe(4);
+ });
+ });
+}
+
+test('a change keeps the theme\u2019s duration and easing', async ({page}) => {
+ await open(page, 20);
+ const palette = await colors(page);
+ // The tokens the stroked circle's transition used, still declared on the
+ // fill and read back when a change starts.
+ const theme = await page.evaluate(() => {
+ const fill = document.querySelector(
+ '.astryx-circular-progress-fill',
+ ) as HTMLElement;
+ const style = getComputedStyle(fill);
+ return {
+ duration: style.transitionDuration,
+ easing: style.transitionTimingFunction,
+ };
+ });
+ await changeAndPause(page, 80);
+ const timing = await page.evaluate(easing => {
+ const [first] = document.getAnimations();
+ const duration = Number(first?.effect?.getTiming().duration);
+ // The theme's easing, evaluated by the browser through a detached animation.
+ const probe = new Animation(
+ new KeyframeEffect(null, null, {duration: 1000, easing, fill: 'both'}),
+ );
+ const eased = [0.25, 0.5, 0.75].map(t => {
+ probe.currentTime = t * 1000;
+ return probe.effect?.getComputedTiming().progress ?? t;
+ });
+ return {duration, eased};
+ }, theme.easing);
+ const tokenMs =
+ Number.parseFloat(theme.duration) *
+ (theme.duration.endsWith('ms') ? 1 : 1000);
+ expect(timing.duration).toBeCloseTo(tokenMs, 0);
+ // The arc reaches where the theme's easing puts it at each quarter.
+ const shots: string[] = [];
+ for (const t of [0.25, 0.5, 0.75]) {
+ await seek(page, t * timing.duration);
+ shots.push(
+ (await page.getByRole('progressbar').screenshot()).toString('base64'),
+ );
+ }
+ const rows = await inkByDegree(page, shots, palette);
+ // The leading round cap reaches half the stroke past the arc's end.
+ const cap = (STROKE / 2 / ((DIAMETER - STROKE) / 2)) * (180 / Math.PI);
+ rows.forEach((row, i) => {
+ const expected = 360 * (0.2 + 0.6 * timing.eased[i]) + cap;
+ const {last} = span(row);
+ expect(
+ Math.abs(last - expected),
+ `quarter ${i + 1}: ${last}°`,
+ ).toBeLessThanOrEqual(4);
+ });
+});
+
+test('storyboard: 20% to 80% @storyboard', async ({page}, testInfo) => {
+ await open(page, 20);
+ await changeAndPause(page, 80);
+ const duration = await page.evaluate(() =>
+ Number(document.getAnimations()[0]?.effect?.getTiming().duration),
+ );
+ const step = 1000 / 60;
+ const shots: {t: number; png: string}[] = [];
+ for (let t = 0; t <= duration + step; t += step * 2) {
+ await seek(page, t);
+ shots.push({
+ t: Math.round(t * 10) / 10,
+ png: (await page.getByRole('progressbar').screenshot()).toString(
+ 'base64',
+ ),
+ });
+ }
+ fs.mkdirSync(EVIDENCE, {recursive: true});
+ const sheet = await page.context().newPage();
+ try {
+ const png = await sheet.evaluate(
+ async items => {
+ const decoded = await Promise.all(
+ items.map(async item =>
+ createImageBitmap(
+ await (await fetch(`data:image/png;base64,${item}`)).blob(),
+ ),
+ ),
+ );
+ const w = decoded[0].width + 12;
+ const h = decoded[0].height + 12;
+ const columns = 8;
+ const canvas = new OffscreenCanvas(
+ columns * w,
+ Math.ceil(decoded.length / columns) * h,
+ );
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.fillStyle = '#fff';
+ context.fillRect(0, 0, canvas.width, canvas.height);
+ decoded.forEach((bitmap, i) =>
+ context.drawImage(
+ bitmap,
+ (i % columns) * w + 6,
+ Math.floor(i / columns) * h + 6,
+ ),
+ );
+ const blob = await canvas.convertToBlob({type: 'image/png'});
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return btoa(binary);
+ },
+ shots.map(s => s.png),
+ );
+ fs.writeFileSync(
+ path.join(EVIDENCE, 'circular-progress-move.png'),
+ Buffer.from(png, 'base64'),
+ );
+ fs.writeFileSync(
+ path.join(EVIDENCE, 'circular-progress-move.json'),
+ JSON.stringify(
+ {story: STORY, from: 20, to: 80, duration, frames: shots.map(s => s.t)},
+ null,
+ 1,
+ ),
+ );
+ await testInfo.attach('circular-progress-move.png', {
+ path: path.join(EVIDENCE, 'circular-progress-move.png'),
+ contentType: 'image/png',
+ });
+ } finally {
+ await sheet.close();
+ }
+});