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.
This commit is contained in:
thekhalidsha committed 2026-09-28 21:12:11 +05:30
1 parent dc5e6ff800
commit f01de83733
185 files changed
+22542 -5182

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
#!/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)
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""
Tile story screenshots into labelled contact sheets for quick visual review.
python3 scripts/contact-sheet.py /tmp/tansy-story-check/light [--prefix forms-] [--per 12]
Each screenshot is trimmed to its content (plus a margin) before tiling, so a
small component isn't lost in an empty 1100x760 frame.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw
def trim(img: Image.Image, margin: int = 16) -> Image.Image:
rgb = img.convert("RGB")
bg = Image.new("RGB", rgb.size, rgb.getpixel((2, 2)))
box = ImageChops.difference(rgb, bg).getbbox()
if not box:
return rgb.crop((0, 0, 400, 120))
l, t, r, b = box
return rgb.crop((max(l - margin, 0), max(t - margin, 0), min(r + margin, rgb.width), min(b + margin, rgb.height)))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("dir")
ap.add_argument("--prefix", default="")
ap.add_argument("--per", type=int, default=12)
ap.add_argument("--cols", type=int, default=3)
ap.add_argument("--cell", type=int, default=560, help="cell width in px")
args = ap.parse_args()
src = Path(args.dir)
shots = sorted(p for p in src.glob("*.png") if p.name.startswith(args.prefix) and not p.name.startswith("sheet-"))
if not shots:
sys.exit("no screenshots matched")
out = []
for n in range(0, len(shots), args.per):
batch = shots[n : n + args.per]
cells = []
for p in batch:
img = trim(Image.open(p))
scale = min(1.0, (args.cell - 16) / img.width)
img = img.resize((int(img.width * scale), int(img.height * scale)))
cells.append((p.stem, img))
rows = [cells[i : i + args.cols] for i in range(0, len(cells), args.cols)]
heights = [max(c[1].height for c in row) + 34 for row in rows]
sheet = Image.new("RGB", (args.cell * args.cols, sum(heights)), "#8a8f99")
draw = ImageDraw.Draw(sheet)
y = 0
for row, h in zip(rows, heights):
for i, (name, img) in enumerate(row):
x = i * args.cell
draw.rectangle([x + 2, y + 2, x + args.cell - 2, y + h - 2], fill="#ffffff")
draw.text((x + 10, y + 8), name, fill="#b00020")
sheet.paste(img, (x + 8, y + 26))
y += h
path = src / f"sheet-{args.prefix or 'all'}-{n // args.per + 1:02d}.png"
sheet.save(path)
out.append(str(path))
print("\n".join(out))
if __name__ == "__main__":
main()
+63 -117
View File
@@ -10,10 +10,8 @@ src/data/catalogue.ts and writes /tmp/component_catalogue.json.
python3 scripts/gen_catalogue.py # print entries
python3 scripts/gen_catalogue.py --patch # also rewrite src/data/catalogue.ts
Story ids are `<group>-<component>--<story>`, but the group is not always
a single segment: TextField publishes as `data-entry-text-field--*`. So
components are matched by longest known name against `base` or
`base.endswith("-" + name)`, with aliases for the hyphenated spellings.
Components are read from story titles (`Group/Name`), so a new component
appears here without editing this script; only DETAIL is hand-written.
"""
from __future__ import annotations
@@ -28,92 +26,50 @@ IDX = REPO / "storybook-static" / "index.json"
CATALOGUE = REPO / "src" / "data" / "catalogue.ts"
OUT = Path("/tmp/component_catalogue.json")
# component id -> group slug
GROUPS = {
"button": "actions",
"accordion": "navigation",
"text-field": "data-entry",
"textfield": "data-entry",
"input": "forms",
"featuredinput": "forms",
"featured-input": "forms",
"select": "forms",
"checkbox": "forms",
"radio": "forms",
"switch": "forms",
"textarea": "forms",
"text-area": "forms",
"alert": "feedback",
"spinner": "feedback",
"badge": "display",
"card": "layout",
"tooltip": "overlays",
}
# Group order on the landing page; matches the Storybook sidebar.
GROUP_ORDER = ["Actions", "Forms", "Overlays", "Navigation", "Feedback", "Display", "Layout"]
# alias id key -> canonical component key
CANON = {
"text-field": "textfield",
"featured-input": "featuredinput",
"text-area": "textarea",
}
SPECIAL = {
"textfield": "Text field",
"featuredinput": "FeaturedInput",
"textarea": "TextArea",
"checkbox": "Checkbox",
"spinner": "Spinner",
"accordion": "Accordion",
"tooltip": "Tooltip",
"button": "Button",
"select": "Select",
"radio": "Radio",
"switch": "Switch",
"alert": "Alert",
"badge": "Badge",
"card": "Card",
"input": "Input",
}
GROUP_LABEL = {
"actions": "Actions",
"navigation": "Navigation",
"data": "Data entry",
"data-entry": "Data entry",
"forms": "Forms",
"feedback": "Feedback",
"display": "Display",
"layout": "Layout",
"overlays": "Overlays",
"misc": "Other",
}
# display order on the landing page
ORDER = [
"button", "accordion", "textfield",
"input", "featuredinput", "select", "checkbox", "radio", "switch", "textarea",
"alert", "spinner",
"badge", "card",
"tooltip",
]
# one-line coverage summary shown in the index row
# One-line coverage summary per component. Anything missing falls back to
# its story count, so a new component never breaks the generator.
DETAIL = {
"button": "Variants · sizes · disabled",
"accordion": "Disclosure · multiple",
"textfield": "Labels · hints · errors",
"input": "Plain · themed · icon slot",
"featuredinput": "Floating label · password · number",
"select": "Searchable · featured · async",
"checkbox": "Themes · tooltip · uncontrolled",
"radio": "Themes · horizontal · required",
"switch": "Themes · required · described",
"textarea": "Resize · featured · prefilled",
"alert": "Variants · colors · auto-close",
"spinner": "Sizes · variants · dark",
"badge": "Colors · floating · pulse",
"card": "Themes · shadows · horizontal",
"tooltip": "Positions · rich content · sizes",
"Button": "Variants · colours · loading · icons",
"ToggleGroup": "Segmented · multiple · icon-only",
"Input": "Addons · icons · filled · underline",
"FeaturedInput": "Floating label · password · clearable",
"TextArea": "Auto-resize · character count",
"FeaturedTextArea": "Floating label · auto-resize",
"NumberInput": "Steppers · currency · min/max",
"Field": "Label · description · error wiring",
"Select": "Single · multiple · grouped · clearable",
"FeaturedSelect": "Floating label · searchable · actions",
"Combobox": "Search · chips · async",
"NativeSelect": "Native menu · groups",
"Checkbox": "Indeterminate · colours · sizes",
"CheckboxGroup": "Select all · horizontal",
"Radio": "Cards · horizontal · descriptions",
"Switch": "Icons · label position · colours",
"Slider": "Range · marks · formatted",
"Dialog": "Sizes · scrolling body · forms",
"AlertDialog": "Destructive · async confirm",
"Drawer": "Four sides · sizes",
"Popover": "Sides · arrow · rich content",
"Tooltip": "Sides · colours · InfoTip",
"DropdownMenu": "Shortcuts · submenus · checkable",
"Tabs": "Underline · pills · vertical",
"Accordion": "Multiple · variants · heading level",
"Breadcrumb": "Collapse · icons",
"Pagination": "Siblings · boundaries · sizes",
"Alert": "Soft · solid · outline · dismissible",
"Toast": "Promise · actions · placement",
"Spinner": "Sizes · colours",
"Progress": "Indeterminate · meter · formatted",
"Skeleton": "Text · circle · card loading",
"Badge": "Colours · dot · removable · count",
"Avatar": "Initials · status · groups",
"Kbd": "Key combinations",
"Table": "Sortable · striped · sticky header",
"Card": "Outline · elevated · media · link",
"Separator": "Labelled · dashed · vertical",
}
@@ -121,41 +77,31 @@ def collect():
if not IDX.is_file():
sys.exit(f"{IDX} not found - run: npm run build-storybook")
entries = json.loads(IDX.read_text())["entries"]
ids = [v.get("id", k) if isinstance(v, dict) else k for k, v in entries.items()]
entries = json.loads(IDX.read_text())["entries"].values()
comps: dict[str, dict] = {}
for sid in ids:
if "--" not in sid:
continue
base, story = sid.split("--", 1)
comp = next(
(CANON.get(c, c) for c in sorted(GROUPS, key=len, reverse=True)
if base == c or base.endswith("-" + c)),
None,
)
if comp is None:
print(f" WARN unmapped story id: {sid}", file=sys.stderr)
continue
g = comps.setdefault(comp, {"group": GROUPS[comp], "doc": None,
"count": 0})
g["count"] += 1
if story in ("documentation", "docs"):
g["doc"] = sid
for e in entries:
group, _, name = e["title"].partition("/")
if not name or group not in GROUP_ORDER:
continue # Introduction pages and anything outside the component groups
c = comps.setdefault(name, {"group": group, "doc": None, "count": 0})
if e["type"] == "docs":
c["doc"] = e["id"]
else:
c["count"] += 1
ordered = sorted(comps.items(), key=lambda kv: (GROUP_ORDER.index(kv[1]["group"]), kv[0].lower()))
out = []
for i, comp in enumerate(ORDER, start=1):
g = comps.get(comp)
if not g or not g["doc"]:
print(f" WARN {comp}: no documentation story, skipped", file=sys.stderr)
for i, (name, c) in enumerate(ordered, start=1):
if not c["doc"]:
print(f" WARN {name}: no documentation page, skipped", file=sys.stderr)
continue
out.append({
"number": f"{i:02d}",
"group": GROUP_LABEL.get(g["group"], g["group"].title()),
"name": SPECIAL.get(comp, comp.title()),
"detail": DETAIL.get(comp, f"{g['count']} stories"),
"href": f"/docs/?path=/docs/{g['doc']}",
"count": g["count"],
"group": c["group"],
"name": name,
"detail": DETAIL.get(name, f"{c['count']} stories"),
"href": f"/docs/?path=/docs/{c['doc']}",
"count": c["count"],
})
return out