An open source design system that's fully customizable and agent ready
TypeScript
ci(a11y): a story scan waits for Storybook's outcome, not a fixed budget (re-land of #9220) (#9226)
Cindy Zhangc8b1b9368c9f
diff --git a/.github/scripts/accessibility-audit.integration.test.mjs b/.github/scripts/accessibility-audit.integration.test.mjsindex bcaf979b66..1a001590ad 100644--- a/.github/scripts/accessibility-audit.integration.test.mjs+++ b/.github/scripts/accessibility-audit.integration.test.mjs@@ -26,22 +26,29 @@ let selectorResolved = false;// The layout-settle step waits two frames before sampling geometry.global.requestAnimationFrame = callback => setTimeout(callback, 0);+// Storybook's own state as the audit reads it: whether the preview started,+// the selected story's render phase, and the document's load state.function scenarioState() {const scenario = process.env.A11Y_TEST_SCENARIO;reads += 1;+ const started = {preview: true, phase: 'rendering', loaded: false};if (scenario === 'redirect') {- return {url: 'chrome-error://chromewebdata/', classes: [], content: false};+ return {url: 'chrome-error://chromewebdata/', classes: [], content: false, ...started};}if (scenario === 'error') {- return {url: requestedUrl, classes: ['sb-show-errordisplay'], content: false};+ return {url: requestedUrl, classes: ['sb-show-errordisplay'], content: false, ...started};}if (scenario === 'empty') {- return {url: requestedUrl, classes: ['sb-show-main'], content: false};+ return {url: requestedUrl, classes: ['sb-show-main'], content: false, ...started, phase: 'finished'};+ }+ if (scenario === 'no-preview') {+ return {url: requestedUrl, classes: [], content: false, preview: false, phase: null, loaded: true};}return {url: requestedUrl,classes: ['sb-show-main'],content: reads >= 3,+ ...started,};}@@ -49,8 +56,18 @@ function evaluateInFixture(fn, arg) {const state = scenarioState();const previousWindow = global.window;const previousDocument = global.document;- global.window = {location: {href: state.url}};+ const storyId = new URL(state.url).searchParams.get('id');+ global.window = {+ location: {href: state.url},+ __STORYBOOK_PREVIEW__: state.preview+ ? {+ selectionStore: {selection: {storyId}},+ currentRender: {phase: state.phase},+ }+ : undefined,+ };global.document = {+ readyState: state.loaded ? 'complete' : 'interactive',body: {classList: {contains: name => state.classes.includes(name)}},querySelector: selector =>selector === '#storybook-root'@@ -91,7 +108,11 @@ const page = {waitForTimeout: async () => {},close: async () => {},};-const context = {newPage: async () => page, close: async () => {}};+const context = {+ addInitScript: async () => {},+ newPage: async () => page,+ close: async () => {},+};const browser = {newContext: async () => context, close: async () => {}};class FakeAxeBuilder {@@ -318,18 +339,23 @@ describe.sequential('accessibility-audit CLI readiness', () => {expect(result.report).toBeNull();});- it(- 'fails an attached but empty Storybook root without writing a report',- () => {- const result = runFixture('empty', VALID_INDEX);- expect(result.status).not.toBe(0);- expect(result.stderr).toContain(- 'Storybook root did not render story content before timeout',- );- expect(result.report).toBeNull();- },- 10000,- );+ it('fails a story render Storybook ended with an empty root, without writing a report', () => {+ const result = runFixture('empty', VALID_INDEX);+ expect(result.status).not.toBe(0);+ expect(result.stderr).toContain(+ 'Storybook ended the story render (finished) with no content in its root',+ );+ expect(result.report).toBeNull();+ });++ it('fails a page that loaded without starting the Storybook preview, without writing a report', () => {+ const result = runFixture('no-preview', VALID_INDEX);+ expect(result.status).not.toBe(0);+ expect(result.stderr).toContain(+ 'the story page finished loading without starting the Storybook preview',+ );+ expect(result.report).toBeNull();+ });it('fails an invalid index before browser readiness or routing', () => {const result = runFixture('delayed', '{invalid json');diff --git a/.github/scripts/accessibility-audit.js b/.github/scripts/accessibility-audit.jsindex a238221da4..8f0f5fabfd 100644--- a/.github/scripts/accessibility-audit.js+++ b/.github/scripts/accessibility-audit.js@@ -385,24 +385,38 @@ async function runAccessibilityAudit() {reducedMotion: 'reduce',}): null;+ // Animations are frozen from the page's first script on, however far the+ // document has parsed: an adopted stylesheet needs no <head>.+ if (context) {+ await context.addInitScript(css => {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(css);+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];+ }, FREEZE_CSS);+ }// Scan one story on a fresh page; returns its axe violations.const scanStory = async (component, story) => {const page = await context.newPage();try {const url = `${origin}/iframe.html?id=${story.id}&viewMode=story`;- // Higher timeout to accommodate axe-core's heavier DOM analysis+ // The bound covers only the server's answer. Loading and rendering+ // the story is CPU-bound, so the readiness gate waits for the outcome+ // the page and Storybook report instead, with a per-story backstop+ // that names a story that never renders (lib/a11y-story-readiness.js).await page.goto(url, {- waitUntil: 'domcontentloaded',+ waitUntil: 'commit',timeout: 15000,});- await page.addStyleTag({ content: FREEZE_CSS }).catch(() => {});await waitForStoryReadiness(() =>page.evaluate(({expectedOrigin, storyId}) => {const currentUrl = new URL(window.location.href);const root = document.querySelector('#storybook-root');+ const preview = window.__STORYBOOK_PREVIEW__;+ // Absent until the document has parsed its <body>.+ const classes = document.body?.classList;return {url: currentUrl.href,urlMatches:@@ -410,19 +424,24 @@ async function runAccessibilityAudit() {currentUrl.pathname === '/iframe.html' &¤tUrl.searchParams.get('id') === storyId,errorVisible:- document.body.classList.contains('sb-show-errordisplay') ||- document.body.classList.contains('sb-show-nopreview'),- mainVisible:- document.body.classList.contains('sb-show-main'),+ classes?.contains('sb-show-errordisplay') === true ||+ classes?.contains('sb-show-nopreview') === true,+ mainVisible: classes?.contains('sb-show-main') === true,hasContent:root != null &&(root.childElementCount > 0 ||(root.textContent ?? '').trim().length > 0),+ pageLoaded: document.readyState === 'complete',+ previewStarted: preview != null,+ renderPhase:+ preview?.selectionStore?.selection?.storyId === storyId+ ? (preview.currentRender?.phase ?? null)+ : null,};},{expectedOrigin: origin, storyId: story.id},),- {timeoutMs: 5000, pollMs: 50},+ {storyId: story.id, pollMs: 50},);if (readySelector != null) {await page.waitForSelector(readySelector, {diff --git a/.github/scripts/lib/a11y-story-readiness.js b/.github/scripts/lib/a11y-story-readiness.jsindex fea73b7a68..2b0ff21cc7 100644--- a/.github/scripts/lib/a11y-story-readiness.js+++ b/.github/scripts/lib/a11y-story-readiness.js@@ -4,25 +4,42 @@/* global module *//**- * @file Bounded readiness gate for one Storybook accessibility scan.- * @input Repeated snapshots of URL, Storybook shell state, and root content.- * @output Resolves only after the intended story has rendered; rejects redirects,- * Storybook errors, and timeouts.- * @position Pure timing policy used by accessibility-audit.js and unit tests.+ * @file Readiness gate for one Storybook accessibility scan.+ * @input Repeated snapshots of the page's URL and load state, the Storybook+ * shell's classes, the selected story's render phase, and the root content.+ * @output Resolves once the intended story has rendered content; rejects on an+ * outcome the page or Storybook reports: a redirect, a Storybook error+ * display, a page that finished loading without starting the preview, or a+ * story render that ended with an empty root; and rejects, by name, a story+ * that reaches none of these within the backstop.+ * @position Pure policy used by accessibility-audit.js and unit tests.+ *+ * Loading and rendering a story is CPU-bound, so on a loaded machine a tight+ * budget failed stories that were still rendering and would have rendered+ * moments later. The gate decides on the outcomes above instead, which every+ * story reaches once Storybook has run it. Its one clock is a backstop for a+ * story that never reaches one, such as a loader or play function that never+ * settles: 60 s, far above the slowest story measured on a loaded machine, so+ * it names that story instead of leaving the job's timeout to end the whole+ * shard with none named.*/const defaultSleep = ms => new Promise(resolve => setTimeout(resolve, ms));+// Render phases after which Storybook does no more work on the story.+const ENDED_PHASES = new Set(['finished', 'errored', 'aborted']);+async function waitForStoryReadiness(readState,{- timeoutMs = 5000,+ storyId = null,+ backstopMs = 60000,pollMs = 50,now = Date.now,sleep = defaultSleep,} = {},) {- const deadline = now() + timeoutMs;+ const backstop = now() + backstopMs;while (true) {const state = await readState();if (!state.urlMatches) {@@ -34,8 +51,21 @@ async function waitForStoryReadiness(if (state.mainVisible && state.hasContent) {return;}- if (now() >= deadline) {- throw new Error('Storybook root did not render story content before timeout');+ if (ENDED_PHASES.has(state.renderPhase)) {+ throw new Error(+ `Storybook ended the story render (${state.renderPhase}) with no content in its root`,+ );+ }+ if (state.pageLoaded && !state.previewStarted) {+ throw new Error(+ 'the story page finished loading without starting the Storybook preview',+ );+ }+ if (now() >= backstop) {+ const subject = storyId == null ? 'the story' : `story ${storyId}`;+ throw new Error(+ `${subject} never rendered within ${backstopMs / 1000} s`,+ );}await sleep(pollMs);}diff --git a/.github/scripts/lib/a11y-story-readiness.test.mjs b/.github/scripts/lib/a11y-story-readiness.test.mjsindex 622f8c7417..826822bd3a 100644--- a/.github/scripts/lib/a11y-story-readiness.test.mjs+++ b/.github/scripts/lib/a11y-story-readiness.test.mjs@@ -17,22 +17,70 @@ const waiting = {errorVisible: false,mainVisible: true,hasContent: false,+ pageLoaded: false,+ previewStarted: true,+ renderPhase: 'rendering',};const ready = {...waiting, hasContent: true};describe('waitForStoryReadiness', () => {it('waits for delayed story content instead of sampling the root once', async () => {- let time = 0;const readState = sequencedReader([waiting, waiting, ready]);await expect(- waitForStoryReadiness(readState, {- timeoutMs: 5,- pollMs: 0,- now: () => time++,- sleep: async () => {},+ waitForStoryReadiness(readState, {pollMs: 0, sleep: async () => {}}),+ ).resolves.toBeUndefined();+ });++ it('keeps waiting while Storybook is still rendering, as long as a loaded machine takes', async () => {+ // Thirty seconds of rendering, one second per read: the story is still in+ // progress, so it is not failed for being slow.+ let time = 0;+ const states = [...Array.from({length: 30}, () => waiting), ready];+ await expect(+ waitForStoryReadiness(sequencedReader(states), {+ pollMs: 1000,+ now: () => time,+ sleep: async ms => {+ time += ms;+ },}),).resolves.toBeUndefined();+ expect(time).toBe(30000);+ });++ it('fails a story that never renders at the 60 s backstop, naming it', async () => {+ let time = 0;+ await expect(+ waitForStoryReadiness(async () => waiting, {+ storyId: 'core-button--default',+ pollMs: 1000,+ now: () => time,+ sleep: async ms => {+ time += ms;+ },+ }),+ ).rejects.toThrow('story core-button--default never rendered within 60 s');+ expect(time).toBe(60000);+ });++ it('lets an outcome Storybook reports win over the backstop', async () => {+ let time = 0;+ const ended = {...waiting, renderPhase: 'finished'};+ const states = [...Array.from({length: 20}, () => waiting), ended];+ await expect(+ waitForStoryReadiness(sequencedReader(states), {+ storyId: 'core-button--default',+ pollMs: 1000,+ now: () => time,+ sleep: async ms => {+ time += ms;+ },+ }),+ ).rejects.toThrow(+ 'Storybook ended the story render (finished) with no content in its root',+ );+ expect(time).toBe(20000);});it('rejects a redirect away from the selected Storybook iframe', async () => {@@ -53,15 +101,51 @@ describe('waitForStoryReadiness', () => {).rejects.toThrow('Storybook reported a story render error');});- it('rejects a root that never renders within the bound', async () => {- let time = 0;+ it('rejects a render Storybook ended with an empty root, at once', async () => {+ let reads = 0;await expect(- waitForStoryReadiness(async () => waiting, {- timeoutMs: 2,+ waitForStoryReadiness(+ async () => {+ reads += 1;+ return {...waiting, renderPhase: 'finished'};+ },+ {pollMs: 0, sleep: async () => {}},+ ),+ ).rejects.toThrow(+ 'Storybook ended the story render (finished) with no content in its root',+ );+ expect(reads).toBe(1);+ });++ it('rejects a page that finished loading without starting the Storybook preview', async () => {+ await expect(+ waitForStoryReadiness(+ async () => ({+ ...waiting,+ mainVisible: false,+ pageLoaded: true,+ previewStarted: false,+ renderPhase: null,+ }),+ {pollMs: 0, sleep: async () => {}},+ ),+ ).rejects.toThrow(+ 'the story page finished loading without starting the Storybook preview',+ );+ });++ it('keeps waiting for a preview that has not started while the page still loads', async () => {+ const booting = {+ ...waiting,+ mainVisible: false,+ previewStarted: false,+ renderPhase: null,+ };+ await expect(+ waitForStoryReadiness(sequencedReader([booting, booting, ready]), {pollMs: 0,- now: () => time++,sleep: async () => {},}),- ).rejects.toThrow('did not render story content before timeout');+ ).resolves.toBeUndefined();});});