From 5f9b697883524afe6bc607fedf6557eadbb204f5 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 3 Dec 2026 05:19:43 -0800 Subject: [PATCH 1/9] [Component Audit] Spinner: an empty name falls back to "Loading", and each shade and part is tested --- .changeset/spinner-audit.md | 7 + apps/storybook/stories/Spinner.stories.tsx | 11 +- packages/core/src/Spinner/Spinner.doc.mjs | 21 +- packages/core/src/Spinner/Spinner.test.tsx | 135 ++++- packages/core/src/Spinner/Spinner.tsx | 113 ++-- .../SpinnerAudit.a11y.chromium.spec.ts | 552 ++++++++++++++++++ 6 files changed, 755 insertions(+), 84 deletions(-) create mode 100644 .changeset/spinner-audit.md create mode 100644 packages/core/src/Spinner/__tests__/SpinnerAudit.a11y.chromium.spec.ts diff --git a/.changeset/spinner-audit.md b/.changeset/spinner-audit.md new file mode 100644 index 0000000000000..a8fa6e94efb39 --- /dev/null +++ b/.changeset/spinner-audit.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Spinner: an empty or blank `aria-label` or string `label` no longer leaves the loading indicator with no accessible name. The indicator falls back to the next name in its order: a non-empty string label, then the translated "Loading". The docs say when to hide a Spinner with `aria-hidden`. + +@cixzhang diff --git a/apps/storybook/stories/Spinner.stories.tsx b/apps/storybook/stories/Spinner.stories.tsx index fc4ba6a338d28..3952759d6dc3f 100644 --- a/apps/storybook/stories/Spinner.stories.tsx +++ b/apps/storybook/stories/Spinner.stories.tsx @@ -65,6 +65,10 @@ export const Shades: Story = { render: () => ( + + + +
({announce: vi.fn()})); vi.mock('../hooks/useAnnounce', () => ({useAnnounce: () => announce})); @@ -229,8 +231,8 @@ describe('Spinner', () => { // The themed geometry resolves in the cascade — jsdom implements no layout // and no custom-property registration, so no test here can reach what a - // theme actually draws; that is verified in a browser and the numbers are in - // the PR. What IS a contract a unit test can hold is the routing: a theme + // theme actually draws; a browser spec verifies that. What IS a contract a + // unit test can hold is the routing: a theme // writes an override against the documented key, and it has to come out on // the selector the component reads from. describe('a theme reaches the spinner through its public vars', () => { @@ -269,7 +271,7 @@ describe('Spinner', () => { ); }); - it('scopes a themed arc fraction to that size variant (#5819)', () => { + it('scopes a themed arc fraction to that size variant', () => { expect( cssFor({spinner: {'size:xl': {'--spinner-arc-fraction': '0.75'}}}), ).toContain( @@ -335,12 +337,9 @@ describe('Spinner ring', () => { }, ); - // The regression this file could not have caught: #5214 made the RING - // themeable and left the frame at the size's own constant, so a themed - // diameter left the svg larger than the box it sits in. The overflowing grid - // item then aligned to start rather than centre — measured in Chromium at - // 1.5 to 3.3px off across the four sizes. Nothing asserted the two agreed, - // because nothing tied them. + // A frame sized from the size constant stays larger than the box when a + // theme changes the diameter. The overflowing grid item then aligns to start + // rather than centre, 1.5 to 3.3px off across the four sizes in Chromium. it('sizes the frame from CSS, not from the size constant', () => { render(); // No viewBox, and the circles centre on the box rather than on a centre @@ -363,6 +362,7 @@ describe('Spinner ring', () => { // centre in user units — the centre is `50%`, so there is no user-unit // number to name, and the offset has to survive a themed diameter. expect(circles().arc.getAttribute('transform')).toBeNull(); + expect(declaredValue(circles().arc, 'transform')).toBe('rotate(-90deg)'); }); // The authored dash is the size's own absolute pattern, and stays that way: @@ -841,3 +841,120 @@ describe('shared announcement lifecycle', () => { expect(announce).toHaveBeenCalledExactlyOnceWith('Loading', 'polite'); }); }); + +describe('Spinner accessible name', () => { + it.each([ + ['an empty aria-label', {'aria-label': ''}], + ['a blank aria-label', {'aria-label': ' '}], + ['an empty string label', {label: ''}], + ['a blank string label', {label: ' '}], + ])('falls back to the translated default for %s', (_, props) => { + render(); + expect(screen.getByRole('progressbar')).toHaveAccessibleName('Loading'); + }); + + it('names the indicator from a string label when the aria-label is empty', () => { + render(); + const indicator = screen.getByRole('progressbar'); + expect(indicator).toHaveAccessibleName('Saving'); + expect(indicator).not.toHaveAttribute('aria-label'); + }); +}); + +const ownershipStyles = stylex.create({ + margin: {marginInlineStart: '7px'}, +}); + +describe('Spinner element ownership', () => { + it('puts the ref, target, className and xstyle on the indicator without a label', () => { + const ref = createRef(); + render( + , + ); + const indicator = screen.getByRole('progressbar'); + expect(ref.current).toBe(indicator); + expect(indicator).toHaveClass('astryx-spinner', 'app-spinner'); + expect(declaredValue(indicator, 'margin-inline-start')).toBe('7px'); + }); + + it('puts the ref, target, className and xstyle on the wrapper with a label', () => { + const ref = createRef(); + render( + , + ); + const indicator = screen.getByRole('progressbar'); + const wrapper = ref.current as HTMLElement; + expect(wrapper).not.toBe(indicator); + expect(wrapper.contains(indicator)).toBe(true); + expect(wrapper).toHaveClass('astryx-spinner', 'app-spinner'); + expect(indicator).not.toHaveClass('astryx-spinner'); + expect(indicator).not.toHaveClass('app-spinner'); + expect(declaredValue(wrapper, 'margin-inline-start')).toBe('7px'); + expect(declaredValue(indicator, 'margin-inline-start')).toBeNull(); + }); + + it('declares the public vars on the wrapper, not the indicator, with a label', () => { + render(); + const wrapper = screen.getByTestId('spinner'); + const indicator = screen.getByRole('progressbar'); + expect(declaredValue(wrapper, '--spinner-diameter')).toBe('28px'); + expect(declaredValue(wrapper, '--spinner-color')).toBe( + colorVars['--color-accent'], + ); + for (const name of [ + '--spinner-diameter', + '--spinner-stroke-width', + '--spinner-arc-fraction', + '--spinner-color', + '--spinner-track-color', + ]) { + expect(declaredValue(indicator, name)).toBeNull(); + } + }); + + it('hides the track and the turning arc from assistive technology', () => { + render(); + const [trackSvg] = rings(); + expect(trackSvg).toHaveAttribute('aria-hidden', 'true'); + expect(rotor()).toHaveAttribute('aria-hidden', 'true'); + }); +}); + +describe('Spinner shade paint', () => { + it.each([ + ['default', colorVars['--color-accent'], colorVars['--color-track'], '1'], + [ + 'subtle', + colorVars['--color-text-secondary'], + colorVars['--color-track'], + '1', + ], + [ + 'onMedia', + colorVars['--color-on-dark'], + colorVars['--color-on-dark'], + String(77 / 255), + ], + ['inherit', 'currentColor', 'currentColor', '0.3'], + ] as const)( + 'paints the %s shade with its arc and track colors and track opacity', + (shade, arc, track, opacity) => { + render(); + const indicator = screen.getByTestId('spinner'); + expect(declaredValue(indicator, '--spinner-color')).toBe(arc); + expect(declaredValue(indicator, '--spinner-track-color')).toBe(track); + expect( + Number(declaredValue(circles().track, 'stroke-opacity')), + ).toBeCloseTo(Number(opacity), 3); + }, + ); +}); diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsx index 6dbff308040ba..fac7b70c31ce8 100644 --- a/packages/core/src/Spinner/Spinner.tsx +++ b/packages/core/src/Spinner/Spinner.tsx @@ -61,10 +61,9 @@ const SIZES = { }; /** - * Opacity the track is drawn at, per shade. `77 / 255` is the `4D` the onMedia - * track used to append to the token's hex — the same composite, but applied as - * `stroke-opacity` to a color off the cascade, so it no longer depends on the - * token being hex notation and it applies to a themed color too. + * Opacity the track is drawn at, per shade. It is `stroke-opacity` over the + * shade's color, so it does not depend on the color notation and it also + * applies to a themed color. */ const TRACK_OPACITY: Record = { default: 1, @@ -193,25 +192,11 @@ const styles = stylex.create({ // a precedence over the box that it has never had. [BOX_SIZE]: `calc(var(${RESOLVED_DIAMETER}) + var(${RESOLVED_STROKE}) * 2)`, - // The box is the ring's size, and a host does not get to take that away. - // - // `overflow: hidden` used to sit here, carried over from the canvas ring - // this component no longer draws. It clipped nothing — the painted circle - // is inscribed in the box, so hiding and showing the overflow render - // byte-identical pixels at every size, every shade, the labelled case and - // every rotation angle. What it did do is remove the floor under this box: - // a flex item whose overflow is not `visible` has an automatic minimum - // size of zero, so a narrow flex host was free to compress the box while - // the ring kept drawing at the size its own attributes ask for, and then - // the clip cut the ring off at the box edge. Ordinary rows hit it — a - // spinner beside a label in a 140px row lost 4px of its ring, one beside a - // `flex: 1 0 100px` sibling lost half of it — with nothing reporting a - // problem, because a sliced ring still spins. - // - // `flex-shrink: 0` then states the invariant directly rather than leaving - // it to the automatic minimum size, which a host takes away again the - // moment it sets `min-width: 0` on its items. A spinner that does not fit - // overflows its host visibly instead of being silently sliced. + // A flex host must not compress the box: the ring draws at its own size, + // so a compressed box cuts the ring off at its edge. The box keeps + // `overflow: visible` and does not shrink, so a spinner that does not fit + // overflows its host visibly. A host that sets `min-width: 0` on its items + // removes the automatic minimum size, so `flex-shrink: 0` is necessary. flexShrink: 0, }, ring: { @@ -286,28 +271,19 @@ const styles = stylex.create({ track: {stroke: 'var(--spinner-track-color)'}, }); -// What each named `size` and `shade` resolve to. Both groups DECLARE the four -// public vars, on the element that carries the `spinner` theme target, and -// everything downstream reads them — so a theme's `@layer astryx-theme` rule -// against `.astryx-spinner[data-size="xl"]` overrides the default the same way it does for -// `--tree-list-indent` or `--button-focus-offset`, e.g. +// What each named `size` and `shade` resolve to. Both groups declare the +// public vars on the element that carries the `spinner` theme target, and +// everything downstream reads them. So a theme rule on +// `.astryx-spinner[data-size="xl"]` overrides the default, for example // spinner: { 'size:xl': { '--spinner-diameter': '40px' } }. // -// Declaring is only safe because #5410 moved the compiled StyleX CSS inside -// `@layer astryx-base`. Before it, StyleX emitted custom-property -// declarations at priority 0 and therefore OUTSIDE its layers, and an -// unlayered declaration beats every layer — so a StyleX-declared -// `--spinner-diameter: 10px` shadowed the theme's own rule no matter how -// specific the theme got. An earlier revision of this component worked around -// that by never declaring the public var and reading it with the default as a -// `var()` fallback; that is no longer necessary, and the fallback shape has a -// cost of its own — with nothing declaring the var, -// `theme-var-reachability.js` cannot find an element to check, so a documented -// var reads as unreachable. -// Arc fraction is not itself size-dependent, but it declares alongside the -// two vars that are, on the same per-size condition (`!hasLabel` gate at the -// call site) — it needs a home on whichever element carries the theme -// target, and this is the object already wired to be there. +// The compiled StyleX CSS is inside `@layer astryx-base`, so a theme layer +// overrides these declarations. Declaring the vars, rather than reading them +// with a `var()` fallback, also lets `theme-var-reachability.js` find the +// element that carries each documented var. +// +// The arc fraction does not change with size. It is declared with the size +// vars because they are on the element that carries the theme target. const sizeStyles = stylex.create({ sm: { '--spinner-diameter': `${SIZES.sm.diameter}px`, @@ -350,9 +326,8 @@ const shadeStyles = stylex.create({ }, }); -// The track's alpha is a property, not a color: it composites over whatever -// color the shade or the theme supplies. `77 / 255` is the `4D` the onMedia -// token's hex used to carry. +// The track's alpha is a property, not a color: it composites over the color +// that the shade or the theme supplies. const trackOpacityStyles = stylex.create({ default: {strokeOpacity: TRACK_OPACITY.default}, subtle: {strokeOpacity: TRACK_OPACITY.subtle}, @@ -397,9 +372,9 @@ export interface SpinnerProps extends BaseProps { * Visible content displayed below the spinner. * Accepts a string or ReactNode for rich content. * - * When `label` is a string, the visible text also provides the accessible - * name of the progressbar (via aria-labelledby, avoiding a duplicate - * announcement) unless `aria-label` is explicitly set. + * When `label` is a non-empty string, the visible text also provides the + * accessible name of the progressbar (via aria-labelledby, avoiding a + * duplicate announcement) unless a non-empty `aria-label` is set. * * @example * ``` @@ -414,6 +389,10 @@ export interface SpinnerProps extends BaseProps { 'data-testid'?: string; } +function hasText(value: string | undefined): value is string { + return value != null && value.trim() !== ''; +} + // ============================================================================= // Component // ============================================================================= @@ -452,20 +431,20 @@ export function Spinner({ const spinnerRef = useRef(null); const rootRef = useMemo(() => mergeRefs(spinnerRef, ref), [ref]); - // When a visible string label renders (and no explicit aria-label is set), - // name the progressbar from the visible Text via aria-labelledby instead - // of duplicating the same string as aria-label — the duplicate would be - // announced twice by screen readers (WCAG 4.1.2). - const namedByVisibleLabel = - hasLabel && typeof label === 'string' && ariaLabel == null; + // An empty or blank string gives no accessible name, so the next source + // in the order applies. + const callerAriaLabel = hasText(ariaLabel) ? ariaLabel : undefined; + const stringLabel = + typeof label === 'string' && hasText(label) ? label : undefined; + + // A visible string label names the indicator through aria-labelledby. The + // same string as aria-label too makes screen readers say it twice. + const namedByVisibleLabel = stringLabel != null && callerAriaLabel == null; - // Resolve accessible name: explicit aria-label > string label > the - // localized default. The fallback is AT-facing text, so it goes through the - // translation runtime like visible text does. + // The translated default is assistive-technology text, so it comes from + // the catalog. const resolvedAriaLabel = - ariaLabel ?? - (typeof label === 'string' ? label : undefined) ?? - t('@astryx.spinner.loading'); + callerAriaLabel ?? stringLabel ?? t('@astryx.spinner.loading'); // Only a standalone Spinner announces. A Core component that composes it // owns the task and silences it through the internal SpinnerOwnerContext; @@ -513,13 +492,11 @@ export function Spinner({ !hasLabel && xstyle, ), hasLabel ? undefined : className, - // The box is sized here, after the caller's `style`, exactly as it was - // before the geometry became themeable: the component's own size wins - // over a `style={{width}}` a caller passes, and the precedence between - // the two is unchanged by this PR. What the value is made of has - // changed — it is the composed var rather than a number — so a themed - // diameter moves the box with the ring. The fallback is the size's own - // frame, for the render where no stylesheet has declared the var. + // The box is sized after the caller's `style`, so the component's + // own size wins over a caller's `style={{width}}`. The value is the + // composed var, so a themed diameter moves the box with the ring. The + // fallback is the size's own frame, for a render where no stylesheet + // declares the var. { ...(hasLabel ? {} : style), width: `var(${BOX_SIZE}, ${frameSize}px)`, diff --git a/packages/core/src/Spinner/__tests__/SpinnerAudit.a11y.chromium.spec.ts b/packages/core/src/Spinner/__tests__/SpinnerAudit.a11y.chromium.spec.ts new file mode 100644 index 0000000000000..9be7c3a50cf4c --- /dev/null +++ b/packages/core/src/Spinner/__tests__/SpinnerAudit.a11y.chromium.spec.ts @@ -0,0 +1,552 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// @pr-a11y audit Spinner + +/** + * @file SpinnerAudit.a11y.chromium.spec.ts + * @input Exact-head Spinner stories: the default ring, every size, every + * shade, string and rich labels, and narrow flex hosts, in light and dark + * and both directions + * @output Screenshots and fail-closed sensor receipts for the Spinner + * whole-component audit + * @position Component-owned Night Watch browser evidence; CI runs it only for + * a Spinner audit pull request + */ +import {createHash} from 'node:crypto'; +import {execFileSync} from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import AxeBuilder from '@axe-core/playwright'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium'; +import { + DEFAULT_STORYBOOK_DIR, + serveStorybook, + type StaticServer, +} from '@astryxdesign/a11y-spec/storybook'; +import {resetAuditEvidence} from '@astryxdesign/a11y-spec/evidence'; + +const EVIDENCE = path.resolve('test-results/spinner-audit-evidence'); +const STORIES = { + default: 'core-spinner--default', + sizes: 'core-spinner--sizes', + shades: 'core-spinner--shades', + label: 'core-spinner--with-label', + narrow: 'core-spinner--narrow-flex-host', +} as const; + +/** Ring diameter and stroke per size; the box adds one stroke on each side. */ +const SIZES = { + sm: {diameter: 10, border: 2}, + md: {diameter: 14, border: 3}, + lg: {diameter: 18, border: 3}, + xl: {diameter: 28, border: 4}, +} as const; + +/** The arc color token and the track opacity each shade draws with. */ +const SHADES = { + default: {arc: 'var(--color-accent)', trackOpacity: 1}, + subtle: {arc: 'var(--color-text-secondary)', trackOpacity: 1}, + inherit: {arc: 'currentColor', trackOpacity: 0.3}, + onMedia: {arc: 'var(--color-on-dark)', trackOpacity: 77 / 255}, +} as const; + +type Mode = 'light' | 'dark'; +/** Every case runs in the Storybook default theme. */ +type Theme = 'neutral'; +type Direction = 'ltr' | 'rtl'; +type Viewport = {width: number; height: number}; +type Check = (condition: boolean, message: string) => void; +type FrameSink = (state: string, observed: unknown) => Promise; + +type AuditCase = { + key: string; + group: keyof typeof STORIES; + mode: Mode; + theme: Theme; + direction: Direction; + viewport: Viewport; + run: ( + page: Page, + check: Check, + frame: FrameSink, + direction: Direction, + ) => Promise; +}; + +const DESKTOP = {width: 900, height: 700}; + +test.describe.configure({retries: 0}); + +let OUTPUT = EVIDENCE; +let server: StaticServer; +let checkoutSha: string; +let storybookSha: string; + +/** The part of Storybook's preview this spec reads: the story render's phase. */ +interface StorybookPreviewWindow extends Window { + __STORYBOOK_PREVIEW__?: {currentRender?: {phase?: string}}; +} + +async function settle(page: Page) { + await holdMotionStill(page); + await page.evaluate(async () => document.fonts.ready); + await page.evaluate( + async () => + new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); +} + +async function pageSensors(page: Page) { + return page.evaluate(() => { + const root = document.querySelector('#storybook-root .astryx-spinner'); + return { + mode: + document.documentElement.getAttribute('data-theme') ?? + document.documentElement.style.getPropertyValue('color-scheme'), + direction: root == null ? null : getComputedStyle(root).direction, + viewport: {width: innerWidth, height: innerHeight}, + dpr: devicePixelRatio, + fonts: document.fonts.status, + reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches, + forcedColors: matchMedia('(forced-colors: active)').matches, + storybookError: document.body.classList.contains('sb-show-errordisplay'), + }; + }); +} + +async function checkAxe(page: Page, check: Check) { + const results = await new AxeBuilder({page}) + .include('body') + .exclude('#storybook-docs') + .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']) + .analyze(); + const violations = results.violations.flatMap(violation => + violation.nodes.map( + node => + `${violation.id} ${node.target.join(' ')}: ${node.failureSummary}`, + ), + ); + check(violations.length === 0, `axe: ${violations.join(' | ')}`); + check(results.passes.length > 0, 'axe checked nothing'); + return {violations, passes: results.passes.length}; +} + +/** + * Every progressbar in the story root: its name source, box, ring parts, + * resolved arc and track paint, and the contrast of the arc against the + * nearest painted backdrop. + */ +async function readSpinners(page: Page) { + return page.evaluate(() => { + const parse = (value: string) => { + const m = value.match(/rgba?\(([^)]+)\)/); + if (m == null) { + return null; + } + const [r, g, b, a = '1'] = m[1].split(/[\s,/]+/).filter(Boolean); + return {r: Number(r), g: Number(g), b: Number(b), a: Number(a)}; + }; + const luminance = ({r, g, b}: {r: number; g: number; b: number}) => { + const lin = (c: number) => { + const s = c / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b); + }; + const backdropOf = (element: Element) => { + for ( + let node: Element | null = element; + node != null; + node = node.parentElement + ) { + const color = parse(getComputedStyle(node).backgroundColor); + if (color != null && color.a > 0) { + return color; + } + } + return parse(getComputedStyle(document.body).backgroundColor); + }; + const resolve = (host: Element, value: string) => { + const probe = document.createElement('span'); + probe.style.color = value; + host.appendChild(probe); + const color = getComputedStyle(probe).color; + probe.remove(); + return color; + }; + return Array.from( + document.querySelectorAll('#storybook-root [role="progressbar"]'), + ).map(element => { + const box = element.getBoundingClientRect(); + const target = element.closest('.astryx-spinner'); + const [track, arc] = Array.from(element.querySelectorAll('circle')); + const svgs = Array.from(element.querySelectorAll('svg')); + const rotor = svgs[1]?.parentElement ?? null; + const labelledBy = element.getAttribute('aria-labelledby'); + const label = + labelledBy == null ? null : document.getElementById(labelledBy); + const labelBox = label?.getBoundingClientRect() ?? null; + const arcColor = arc == null ? null : getComputedStyle(arc).stroke; + const backdrop = backdropOf(element); + const fg = arcColor == null ? null : parse(arcColor); + const contrast = + fg == null || backdrop == null + ? null + : (() => { + const a = fg.a; + const mixed = { + r: fg.r * a + backdrop.r * (1 - a), + g: fg.g * a + backdrop.g * (1 - a), + b: fg.b * a + backdrop.b * (1 - a), + }; + const l1 = luminance(mixed); + const l2 = luminance(backdrop); + return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); + })(); + return { + size: target?.getAttribute('data-size') ?? null, + shade: target?.getAttribute('data-shade') ?? null, + targetIsIndicator: target === element, + ariaLabel: element.getAttribute('aria-label'), + labelledByText: label == null ? null : (label.textContent ?? '').trim(), + hasValueNow: element.hasAttribute('aria-valuenow'), + box: { + left: box.left, + right: box.right, + top: box.top, + bottom: box.bottom, + width: box.width, + height: box.height, + }, + labelBox: + labelBox == null ? null : {top: labelBox.top, width: labelBox.width}, + ringHidden: + svgs.length === 2 && + svgs[0].getAttribute('aria-hidden') === 'true' && + rotor?.getAttribute('aria-hidden') === 'true', + arcColor, + resolvedTokens: { + accent: resolve(element, 'var(--color-accent)'), + textSecondary: resolve(element, 'var(--color-text-secondary)'), + onDark: resolve(element, 'var(--color-on-dark)'), + currentColor: getComputedStyle(element).color, + }, + trackOpacity: + track == null ? null : Number(getComputedStyle(track).strokeOpacity), + backdrop, + contrast, + }; + }); + }); +} + +type SpinnerRead = Awaited>[number]; + +function expectedArcColor(spinner: SpinnerRead): string | null { + const byShade: Record = { + default: spinner.resolvedTokens.accent, + subtle: spinner.resolvedTokens.textSecondary, + onMedia: spinner.resolvedTokens.onDark, + inherit: spinner.resolvedTokens.currentColor, + }; + return spinner.shade == null ? null : (byShade[spinner.shade] ?? null); +} + +/** Box, ring, paint and name checks every unlabelled or labelled ring shares. */ +function checkRing(check: Check, spinner: SpinnerRead, what: string) { + const size = spinner.size as keyof typeof SIZES | null; + check(size != null && size in SIZES, `${what}: size ${spinner.size}`); + if (size != null && size in SIZES) { + const {diameter, border} = SIZES[size]; + const frame = diameter + border * 2; + check( + Math.abs(spinner.box.width - frame) <= 0.5 && + Math.abs(spinner.box.height - frame) <= 0.5, + `${what}: box ${spinner.box.width}x${spinner.box.height}, expected ${frame}`, + ); + } + check(!spinner.hasValueNow, `${what}: has aria-valuenow`); + check(spinner.ringHidden, `${what}: the track or the rotor is not hidden`); + const shade = spinner.shade as keyof typeof SHADES | null; + check(shade != null && shade in SHADES, `${what}: shade ${spinner.shade}`); + if (shade != null && shade in SHADES) { + check( + spinner.arcColor === expectedArcColor(spinner), + `${what}: arc ${spinner.arcColor}, expected ${expectedArcColor(spinner)} (${SHADES[shade].arc})`, + ); + check( + spinner.trackOpacity != null && + Math.abs(spinner.trackOpacity - SHADES[shade].trackOpacity) < 0.01, + `${what}: track opacity ${spinner.trackOpacity}`, + ); + } +} + +const cases: AuditCase[] = []; + +function add(group: keyof typeof STORIES, run: AuditCase['run']): void { + for (const mode of ['light', 'dark'] as const) { + for (const direction of ['ltr', 'rtl'] as const) { + cases.push({ + key: `${group}__${mode}__${direction}`, + group, + mode, + theme: 'neutral', + direction, + viewport: DESKTOP, + run, + }); + } + } +} + +// The default ring: one named progressbar that carries the target. +add('default', async (page, check, frame) => { + const spinners = await readSpinners(page); + check(spinners.length === 1, `${spinners.length} progressbars`); + const [spinner] = spinners; + if (spinner != null) { + checkRing(check, spinner, 'default'); + check(spinner.targetIsIndicator, 'the indicator carries no target'); + check(spinner.ariaLabel === 'Loading', `name "${spinner.ariaLabel}"`); + check( + spinner.contrast != null && spinner.contrast >= 3, + `arc contrast ${spinner.contrast}`, + ); + } + const axe = await checkAxe(page, check); + await frame('rest', {spinners, axe}); +}); + +// Every size draws the documented box. +add('sizes', async (page, check, frame) => { + const spinners = await readSpinners(page); + check( + spinners.map(s => s.size).join(',') === 'sm,md,lg,xl', + `sizes ${spinners.map(s => s.size).join(',')}`, + ); + for (const spinner of spinners) { + checkRing(check, spinner, `size ${spinner.size}`); + } + const axe = await checkAxe(page, check); + await frame('rest', {spinners, axe}); +}); + +// Every shade paints its documented arc color and track opacity. +add('shades', async (page, check, frame) => { + const spinners = await readSpinners(page); + const shades = new Set(spinners.map(s => s.shade)); + for (const shade of Object.keys(SHADES)) { + check(shades.has(shade), `no ${shade} spinner`); + } + for (const spinner of spinners) { + checkRing(check, spinner, `shade ${spinner.shade}`); + if (spinner.shade === 'default' || spinner.shade === 'onMedia') { + check( + spinner.contrast != null && spinner.contrast >= 3, + `shade ${spinner.shade}: arc contrast ${spinner.contrast}`, + ); + } + } + const axe = await checkAxe(page, check); + await frame('rest', {spinners, axe}); +}); + +// A string label names the indicator through the visible text and sits +// below the ring; a rich label leaves the caller's aria-label as the name. +add('label', async (page, check, frame) => { + const spinners = await readSpinners(page); + check(spinners.length === 2, `${spinners.length} progressbars`); + const [stringLabel, richLabel] = spinners; + if (stringLabel != null) { + checkRing(check, stringLabel, 'string label'); + check(!stringLabel.targetIsIndicator, 'the wrapper carries no target'); + check( + stringLabel.ariaLabel == null && + stringLabel.labelledByText === 'Loading...', + `string label name: aria-label "${stringLabel.ariaLabel}", labelledby "${stringLabel.labelledByText}"`, + ); + check( + stringLabel.labelBox != null && + stringLabel.labelBox.top >= stringLabel.box.bottom - 0.5, + 'the label is not below the ring', + ); + } + if (richLabel != null) { + checkRing(check, richLabel, 'rich label'); + check( + richLabel.ariaLabel === 'Fetching data', + `rich label name "${richLabel.ariaLabel}"`, + ); + } + const axe = await checkAxe(page, check); + await frame('rest', {spinners, axe}); +}); + +// A flex host narrower than the ring does not compress the box. +add('narrow', async (page, check, frame) => { + const spinners = await readSpinners(page); + check(spinners.length === 3, `${spinners.length} progressbars`); + for (const spinner of spinners) { + checkRing(check, spinner, `narrow host ${spinner.size}`); + } + const axe = await checkAxe(page, check); + await frame('rest', {spinners, axe}); +}); + +test.beforeAll(async () => { + OUTPUT = resetAuditEvidence(EVIDENCE, test.info()); + checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], { + encoding: 'utf8', + }).trim(); + const expected = process.env.ASTRYX_HEAD_SHA; + if (expected && expected !== checkoutSha) { + throw new Error( + `checkout ${checkoutSha} does not match expected head ${expected}`, + ); + } + server = await serveStorybook( + process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR, + ); + const response = await fetch(`${server.origin}/astryx-build-sha.txt`); + if (!response.ok) { + throw new Error(`Storybook build has no SHA stamp (${response.status})`); + } + storybookSha = (await response.text()).trim(); + if (storybookSha !== checkoutSha) { + throw new Error( + `Storybook ${storybookSha} does not match checkout ${checkoutSha}`, + ); + } +}); + +test.afterAll(async () => { + await server?.close(); +}); + +async function runCase(page: Page, item: AuditCase) { + const story = STORIES[item.group]; + await page.setViewportSize(item.viewport); + // The pointer position survives navigation; park it so it cannot hover the + // next story. + await page.mouse.move(0, 0); + await page.emulateMedia({ + colorScheme: item.mode, + reducedMotion: 'reduce', + forcedColors: 'none', + }); + const pageErrors: string[] = []; + const onError = (error: Error) => pageErrors.push(String(error)); + page.on('pageerror', onError); + const url = `${server.origin}/iframe.html?id=${story}&viewMode=story&globals=colorMode:${item.mode};astryxTheme:${item.theme};direction:${item.direction}`; + const failures: string[] = []; + const check: Check = (condition, message) => { + if (!condition) { + failures.push(message); + } + }; + let sensors: Awaited> | null = null; + const frames: { + state: string; + observed: unknown; + file: string; + sha256: string; + }[] = []; + const frame: FrameSink = async (state, observed) => { + const clip = await page.evaluate(() => { + const root = document.querySelector('#storybook-root'); + const box = root?.getBoundingClientRect(); + if (box == null || box.width === 0 || box.height === 0) { + return undefined; + } + const left = Math.max(0, box.left - 8); + const top = Math.max(0, box.top - 8); + return { + x: left, + y: top, + width: Math.min(innerWidth, box.right + 8) - left, + height: Math.min(innerHeight, box.bottom + 8) - top, + }; + }); + const screenshot = await page.screenshot({clip, animations: 'disabled'}); + const file = `${item.key}__${state}.png`; + fs.writeFileSync(path.join(OUTPUT, file), screenshot); + frames.push({ + state, + observed, + file, + sha256: createHash('sha256').update(screenshot).digest('hex'), + }); + }; + try { + await page.goto(url, {waitUntil: 'load'}); + // A missing story fails this receipt instead of stalling the group. + await page + .locator('#storybook-root .astryx-spinner') + .first() + .waitFor({timeout: 15_000}); + await page.waitForFunction( + () => + (window as StorybookPreviewWindow).__STORYBOOK_PREVIEW__?.currentRender + ?.phase === 'finished', + ); + await settle(page); + sensors = await pageSensors(page); + check(!sensors.storybookError, 'storybook error display'); + check(sensors.mode === item.mode, `mode ${sensors.mode}`); + check( + sensors.direction === item.direction, + `direction ${sensors.direction}`, + ); + check(sensors.dpr === 2, `dpr ${sensors.dpr}`); + check(sensors.fonts === 'loaded', `fonts ${sensors.fonts}`); + check(sensors.reducedMotion, 'reduced motion is not set'); + check(!sensors.forcedColors, 'forced colors are active'); + await item.run(page, check, frame, item.direction); + } catch (error) { + check(false, `run threw: ${String(error)}`); + } + page.off('pageerror', onError); + check(pageErrors.length === 0, `page errors: ${pageErrors.join(' | ')}`); + const receipt = { + component: 'Spinner', + build: storybookSha, + checkout: checkoutSha, + story, + mode: item.mode, + theme: item.theme, + direction: item.direction, + viewport: item.viewport, + reducedMotion: 'reduce', + forcedColors: false, + sensors, + pageErrors, + frames, + passed: failures.length === 0, + failures, + }; + fs.writeFileSync( + path.join(OUTPUT, `${item.key}.json`), + `${JSON.stringify(receipt, null, 2)}\n`, + ); + return failures.map(failure => `${item.key}: ${failure}`); +} + +for (const group of [...new Set(cases.map(item => item.group))]) { + test(group, async ({browser}) => { + test.setTimeout(240_000); + const context = await browser.newContext({deviceScaleFactor: 2}); + try { + const page = await context.newPage(); + const failures: string[] = []; + for (const item of cases.filter(c => c.group === group)) { + failures.push(...(await runCase(page, item))); + } + expect(failures).toEqual([]); + } finally { + await context.close(); + } + }); +} From ec5aa828b2eb045f62f60208bd634873e3685f60 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 3 Dec 2026 05:33:44 -0800 Subject: [PATCH 2/9] Spinner audit: label docs, announcement test, comment and audit-spec review fixes --- .changeset/spinner-audit.md | 2 +- packages/core/src/Spinner/Spinner.doc.mjs | 6 +- packages/core/src/Spinner/Spinner.test.tsx | 16 ++-- packages/core/src/Spinner/Spinner.tsx | 30 ++++---- .../SpinnerAudit.a11y.chromium.spec.ts | 76 ++++++++++++++++--- 5 files changed, 93 insertions(+), 37 deletions(-) diff --git a/.changeset/spinner-audit.md b/.changeset/spinner-audit.md index a8fa6e94efb39..726c3ef1a3d5c 100644 --- a/.changeset/spinner-audit.md +++ b/.changeset/spinner-audit.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] Spinner: an empty or blank `aria-label` or string `label` no longer leaves the loading indicator with no accessible name. The indicator falls back to the next name in its order: a non-empty string label, then the translated "Loading". The docs say when to hide a Spinner with `aria-hidden`. +[fix] Spinner: an empty or blank `aria-label` or string `label` no longer leaves the loading indicator with no accessible name. The indicator falls back to a non-empty string label, else the translated "Loading", and a standalone Spinner with an empty `aria-label` now announces "Loading" like any other standalone Spinner. To silence a Spinner inside a control that already reports that it is busy, hide it with `aria-hidden`, as the docs now say. @cixzhang diff --git a/packages/core/src/Spinner/Spinner.doc.mjs b/packages/core/src/Spinner/Spinner.doc.mjs index a98660f2605bb..6ceab850fa04f 100644 --- a/packages/core/src/Spinner/Spinner.doc.mjs +++ b/packages/core/src/Spinner/Spinner.doc.mjs @@ -35,7 +35,7 @@ export const docs = { name: 'label', type: 'ReactNode', description: - 'Visible content below the spinner. A string label names the indicator through aria-labelledby.', + 'Visible content below the spinner. A non-empty string label names the indicator through aria-labelledby, unless a non-empty aria-label is set.', }, { name: 'aria-label', @@ -142,7 +142,7 @@ export const docsZh = { name: 'label', type: 'ReactNode', description: - '旋转器下方的可见内容。未设置 aria-label 时,字符串标签提供无障碍名称。', + '旋转器下方的可见内容。未设置非空的 aria-label 时,非空的字符串标签提供无障碍名称。', }, { name: 'aria-label', @@ -265,7 +265,7 @@ export const docsDense = { size: 'Spinner size: ring diameter (10px, 14px, 18px, 28px).', shade: 'Color shade for light or dark backgrounds.', label: - 'Visible content below spinner. String provides its accessible name unless aria-label is set.', + 'Visible content below spinner. A non-empty string provides its accessible name unless a non-empty aria-label is set.', 'aria-label': 'A11y name for screen readers. Empty counts as unset. Defaults to a non-empty string label or a translated "Loading".', xstyle: diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsx index 084413ca8072d..ecaedbf3813d1 100644 --- a/packages/core/src/Spinner/Spinner.test.tsx +++ b/packages/core/src/Spinner/Spinner.test.tsx @@ -229,12 +229,11 @@ describe('Spinner', () => { }); }); - // The themed geometry resolves in the cascade — jsdom implements no layout + // The themed geometry resolves in the cascade. jsdom implements no layout // and no custom-property registration, so no test here can reach what a - // theme actually draws; a browser spec verifies that. What IS a contract a - // unit test can hold is the routing: a theme - // writes an override against the documented key, and it has to come out on - // the selector the component reads from. + // theme draws, and no automated check covers it. A unit test can hold the + // routing: a theme writes an override against the documented key, and it + // comes out on the selector the component reads from. describe('a theme reaches the spinner through its public vars', () => { const cssFor = ( components: Parameters[0]['components'], @@ -836,6 +835,11 @@ describe('shared announcement lifecycle', () => { ]); }); + it('announces the translated default for an empty aria-label', () => { + render(); + expect(announce).toHaveBeenCalledExactlyOnceWith('Loading', 'polite'); + }); + it('uses the accessible-name fallback for a textless ReactNode label', () => { render(