Files
tansy-ui/scripts/check-stories.mjs
T
thekhalidsha f01de83733 Rebuild Tansy UI on Base UI with one API and dark mode (v0.3.0)
Every component is rebuilt on @base-ui/react with a single prop API,
token-only colours and dark mode, and 28 new components are added.

Components
- New: Field, FeaturedTextArea, NumberInput, Combobox, CheckboxGroup,
  Slider, ToggleGroup/Toggle, IconButton, Dialog/Modal, AlertDialog,
  Drawer/Sheet, Popover, InfoTip, DropdownMenu, Tabs, Breadcrumb,
  Pagination, Toast (Toaster, useToast), Progress, Meter, Skeleton,
  CountBadge, Avatar/AvatarGroup, Kbd, Separator, Table
- Rewritten: Button, Input, FeaturedInput, TextArea, Select,
  FeaturedSelect (real ARIA combobox), NativeSelect, Checkbox, Radio,
  Switch, Tooltip, Accordion, Alert, Spinner, Badge, Card
- Removed TextField (use Input) and sonner (use Toast)

Foundations
- Semantic tokens (surfaces, text, borders, status ramps) in
  src/styles/tokens.css, with class-based dark mode
- Visible focus rings, linked labels/descriptions/errors, alert roles by
  severity, keyboard support from Base UI
- Fixed the Classic Blue ramp; Emerald, Amber and Teal 500 steps now
  carry white text at AA
- Library build (per-component ES modules, types, tokens.css, exports)

Quality
- Vitest, Testing Library and axe tests for every component (289 tests)
- scripts/check-stories.mjs renders every story in Chrome and fails on
  errors or axe violations, including contrast; all 423 stories pass in
  light and dark mode and in all seven palettes
- Storybook: controls for every prop, open states for every popup,
  light/dark toolbar, Introduction guides, docs/CONVENTIONS.md

BREAKING CHANGE: component props changed across the kit; see CHANGELOG.md.
2026-09-28 21:12:11 +05:30

182 lines
6.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] [--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 OUT = resolve(opt('out', `/tmp/tansy-story-check/${MODE}${PALETTE ? `-${PALETTE}` : ''}`))
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: 1100, 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)}`)
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` : ''}: ${results.length - bad.length} clean, ${bad.length} with problems.`,
)
console.log(`Screenshots and report.json in ${OUT}`)
process.exit(bad.length ? 1 : 0)