Every story and the landing page now fit from a 320px phone to a wide desktop without scrolling sideways. - Inputs in flex rows (Input, FeaturedInput, NumberInput, Combobox) shrink instead of holding their native width - Tab rows and ToggleGroup scroll within themselves on narrow screens; vertical tabs stack above their panel on phones - Positioned popups cap at Base UI's --available-width - Landing page: tablet header no longer crowds; code sample fits at 1024px - Storybook a11y panel skips page-level rules that can't apply to a story - check-stories.mjs gains --width and fails on horizontal overflow; all 423 stories pass at 320, 375, 768 and desktop widths in both modes
196 lines
7.9 KiB
JavaScript
196 lines
7.9 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Render every story in a real browser and report what's broken.
|
|
*
|
|
* For each story in storybook-static/index.json it:
|
|
* - loads the story in Chrome (light or dark mode),
|
|
* - records page errors and console errors,
|
|
* - runs axe, including colour contrast (jsdom tests can't check that),
|
|
* - saves a screenshot.
|
|
*
|
|
* npm run build-storybook
|
|
* node scripts/check-stories.mjs [--filter forms-] [--mode dark] [--palette emerald] [--width 375] [--out dir] [--no-shots]
|
|
*
|
|
* Exits non-zero when any story has an error or an axe violation.
|
|
* Uses the system Chrome (CHROME_PATH, default /usr/bin/google-chrome).
|
|
*/
|
|
import { createServer } from 'node:http'
|
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
import { createRequire } from 'node:module'
|
|
import { extname, join, resolve } from 'node:path'
|
|
import { chromium } from 'playwright'
|
|
|
|
const args = process.argv.slice(2)
|
|
const opt = (name, fallback) => {
|
|
const i = args.indexOf(`--${name}`)
|
|
return i === -1 ? fallback : args[i + 1]
|
|
}
|
|
const DIR = resolve(opt('dir', 'storybook-static'))
|
|
const FILTER = opt('filter', '')
|
|
const MODE = opt('mode', 'light')
|
|
const PALETTE = opt('palette', '')
|
|
const WIDTH = Number(opt('width', 1100))
|
|
const OUT = resolve(opt('out', `/tmp/tansy-story-check/${MODE}${PALETTE ? `-${PALETTE}` : ''}${WIDTH !== 1100 ? `-${WIDTH}` : ''}`))
|
|
const SHOTS = !args.includes('--no-shots')
|
|
const CONCURRENCY = Number(opt('concurrency', 4))
|
|
|
|
const require = createRequire(import.meta.url)
|
|
const AXE = await readFile(require.resolve('axe-core/axe.min.js'), 'utf8')
|
|
|
|
const TYPES = {
|
|
'.html': 'text/html',
|
|
'.js': 'text/javascript',
|
|
'.mjs': 'text/javascript',
|
|
'.css': 'text/css',
|
|
'.json': 'application/json',
|
|
'.svg': 'image/svg+xml',
|
|
'.woff2': 'font/woff2',
|
|
'.png': 'image/png',
|
|
}
|
|
|
|
const server = createServer(async (req, res) => {
|
|
const path = decodeURIComponent(new URL(req.url, 'http://x').pathname)
|
|
const file = join(DIR, path.endsWith('/') ? `${path}index.html` : path)
|
|
try {
|
|
const body = await readFile(file)
|
|
res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' })
|
|
res.end(body)
|
|
} catch {
|
|
res.writeHead(404)
|
|
res.end()
|
|
}
|
|
})
|
|
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
|
|
const base = `http://127.0.0.1:${server.address().port}`
|
|
|
|
const index = JSON.parse(await readFile(join(DIR, 'index.json'), 'utf8'))
|
|
const stories = Object.values(index.entries).filter(
|
|
(e) => e.type === 'story' && (!FILTER || e.id.startsWith(FILTER)),
|
|
)
|
|
|
|
await mkdir(OUT, { recursive: true })
|
|
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome' })
|
|
// Each story gets its own context: shared contexts leaked theme state and
|
|
// axe runs between parallel pages.
|
|
const newContext = () => browser.newContext({ viewport: { width: WIDTH, height: 760 }, reducedMotion: 'reduce' })
|
|
|
|
const results = []
|
|
async function check(story, attempt = 1) {
|
|
const context = await newContext()
|
|
const page = await context.newPage()
|
|
const errors = []
|
|
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`))
|
|
page.on('console', (m) => {
|
|
// Failed requests are reported with their URL by the response handler below.
|
|
if (m.type() === 'error' && !m.text().startsWith('Failed to load resource'))
|
|
errors.push(`console: ${m.text().slice(0, 300)}`)
|
|
})
|
|
page.on('response', (r) => {
|
|
if (r.status() >= 400) errors.push(`http ${r.status()}: ${r.url().replace(base, '')}`)
|
|
})
|
|
page.on('requestfailed', (r) => {
|
|
if (!r.url().startsWith(base)) return
|
|
errors.push(`request failed: ${r.url().replace(base, '')}`)
|
|
})
|
|
// a11y.manual stops Storybook's own axe run, which would race ours on window.axe.
|
|
const url = `${base}/iframe.html?id=${story.id}&viewMode=story&globals=mode:${MODE};a11y.manual:!true${PALETTE ? `;palette:${PALETTE}` : ''}`
|
|
let axe = []
|
|
try {
|
|
await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 })
|
|
await page.waitForFunction(() => document.querySelector('#storybook-root')?.childElementCount > 0, null, {
|
|
timeout: 10000,
|
|
})
|
|
await page.waitForFunction((dark) => document.documentElement.classList.contains('dark') === dark, MODE === 'dark', {
|
|
timeout: 10000,
|
|
})
|
|
// Globals from the URL (mode) trigger a re-render; wait for the DOM to settle.
|
|
await page.evaluate(() => document.fonts.ready)
|
|
await page.waitForFunction(
|
|
() =>
|
|
new Promise((done) => {
|
|
let last = document.body.innerHTML.length
|
|
let stable = 0
|
|
const tick = setInterval(() => {
|
|
const now = document.body.innerHTML.length
|
|
stable = now === last ? stable + 1 : 0
|
|
last = now
|
|
if (stable >= 3) {
|
|
clearInterval(tick)
|
|
done(true)
|
|
}
|
|
}, 100)
|
|
}),
|
|
null,
|
|
{ timeout: 10000 },
|
|
)
|
|
await page.waitForTimeout(250)
|
|
const sbError = await page.evaluate(() => {
|
|
const el = document.querySelector('.sb-show-errordisplay #error-message')
|
|
return el ? el.textContent : null
|
|
})
|
|
if (sbError) errors.push(`storybook: ${sbError.slice(0, 300)}`)
|
|
// Responsive: nothing may make the page scroll sideways at this width.
|
|
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)
|
|
if (overflow > 1) {
|
|
const culprits = await page.evaluate(() => {
|
|
const vw = document.documentElement.clientWidth
|
|
return [...document.querySelectorAll('body *')]
|
|
.filter((el) => el.getBoundingClientRect().right > vw + 1 && getComputedStyle(el).position !== 'fixed')
|
|
.filter((el) => ![...el.children].some((c) => c.getBoundingClientRect().right > vw + 1))
|
|
.slice(0, 3)
|
|
.map((el) => `${el.tagName.toLowerCase()}${el.className && typeof el.className === 'string' ? '.' + el.className.split(' ').slice(0, 3).join('.') : ''}`)
|
|
})
|
|
errors.push(`overflow: page scrolls ${overflow}px sideways at ${WIDTH}px → ${culprits.join(' | ')}`)
|
|
}
|
|
await page.addScriptTag({ content: AXE })
|
|
axe = await page.evaluate(async () => {
|
|
const r = await window.axe.run(document.body, {
|
|
rules: {
|
|
region: { enabled: false },
|
|
'landmark-one-main': { enabled: false },
|
|
'page-has-heading-one': { enabled: false },
|
|
},
|
|
})
|
|
return r.violations.map((v) => ({
|
|
id: v.id,
|
|
impact: v.impact,
|
|
help: v.help,
|
|
nodes: v.nodes.slice(0, 4).map((n) => n.target.join(' ')),
|
|
}))
|
|
})
|
|
if (SHOTS) await page.screenshot({ path: join(OUT, `${story.id}.png`) })
|
|
} catch (e) {
|
|
errors.push(`load: ${e.message.split('\n')[0]}`)
|
|
}
|
|
await context.close()
|
|
// The local file server can drop requests under load. If nothing but
|
|
// network loading failed, the story never ran: try it once more.
|
|
const infraOnly = errors.length > 0 && !axe.length && errors.every((e) => /^(request failed|load:|console: TypeError: Failed to fetch)/.test(e))
|
|
if (infraOnly && attempt === 1) return check(story, 2)
|
|
results.push({ id: story.id, title: story.title, name: story.name, errors, axe })
|
|
}
|
|
|
|
const queue = [...stories]
|
|
await Promise.all(
|
|
Array.from({ length: CONCURRENCY }, async () => {
|
|
while (queue.length) await check(queue.shift())
|
|
}),
|
|
)
|
|
await browser.close()
|
|
server.close()
|
|
|
|
results.sort((a, b) => a.id.localeCompare(b.id))
|
|
await writeFile(join(OUT, 'report.json'), JSON.stringify(results, null, 2))
|
|
|
|
const bad = results.filter((r) => r.errors.length || r.axe.length)
|
|
for (const r of bad) {
|
|
console.log(`\n✗ ${r.id}`)
|
|
for (const e of r.errors) console.log(` ${e}`)
|
|
for (const v of r.axe) console.log(` axe ${v.impact} ${v.id}: ${v.help} → ${v.nodes.join(' | ')}`)
|
|
}
|
|
console.log(
|
|
`\n${results.length} stories checked in ${MODE} mode${PALETTE ? `, ${PALETTE} palette` : ''} at ${WIDTH}px: ${results.length - bad.length} clean, ${bad.length} with problems.`,
|
|
)
|
|
console.log(`Screenshots and report.json in ${OUT}`)
|
|
process.exit(bad.length ? 1 : 0)
|