#!/usr/bin/env python3 """ Generate the landing page's component catalogue from the built Storybook index, so it cannot drift from the stories again. Run it after `npm run build:docs` and before `npm run build:site` when you add or remove a component. It prints the entries to paste into packages/brand/src/catalogue.ts and writes /tmp/component_catalogue.json. python3 scripts/gen_catalogue.py # print entries python3 scripts/gen_catalogue.py --patch # also rewrite packages/brand/src/catalogue.ts 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 import argparse import json import re import sys from pathlib import Path REPO = Path(__file__).resolve().parent.parent IDX = REPO / "apps" / "docs" / "storybook-static" / "index.json" CATALOGUE = REPO / "packages" / "brand" / "src" / "catalogue.ts" OUT = Path("/tmp/component_catalogue.json") # Group order on the landing page; matches the Storybook sidebar. GROUP_ORDER = ["Actions", "Forms", "Overlays", "Navigation", "Feedback", "Display", "Layout"] # 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 · 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", } def collect(): if not IDX.is_file(): sys.exit(f"{IDX} not found - run: npm run build:docs") entries = json.loads(IDX.read_text())["entries"].values() comps: dict[str, dict] = {} 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, (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": c["group"], "name": name, "detail": DETAIL.get(name, f"{c['count']} stories"), "href": f"/docs/?path=/docs/{c['doc']}", "count": c["count"], }) return out def as_tsx(entries) -> str: body = "".join( " {\n" f" number: '{e['number']}',\n" f" group: '{e['group']}',\n" f" name: '{e['name']}',\n" f" detail: '{e['detail']}',\n" f" href: '{e['href']}',\n" " },\n" for e in entries ) return f"export const documentation: CatalogueEntry[] = [\n{body}]\n" def as_counts(entries) -> str: lines = [] for e in entries: key = e["name"] if re.fullmatch(r"[A-Za-z][A-Za-z0-9]*", e["name"]) \ else f"'{e['name']}'" lines.append(f" {key}: {e['count']},") return ("export const storyCounts: Record = {\n" + "\n".join(lines) + "\n}\n") def patch_catalogue(entries) -> None: src = CATALOGUE.read_text() src, n = re.subn(r"export const documentation\b[^=]*= \[.*?\n\]\n", lambda _: as_tsx(entries), src, count=1, flags=re.S) if n == 0: sys.exit(f"could not find the documentation array in {CATALOGUE}") src, n2 = re.subn(r"export const storyCounts\b[^=]*= \{.*?\n\}\n", lambda _: as_counts(entries), src, count=1, flags=re.S) if n2 == 0: sys.exit(f"could not find the storyCounts block in {CATALOGUE}") CATALOGUE.write_text(src) print(f"patched {CATALOGUE} with {len(entries)} components") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--patch", action="store_true", help="rewrite the catalogue and story counts in packages/brand/src/catalogue.ts") args = ap.parse_args() entries = collect() if not entries: sys.exit("no components with a documentation story were found") total = sum(e["count"] for e in entries) for e in entries: print(f" {e['number']} {e['name']:<16} {e['group']:<12} " f"{e['count']:>2} stories {e['href']}") OUT.write_text(json.dumps(entries, indent=1)) print(f"\n{len(entries)} components, {total} stories -> {OUT}") if args.patch: patch_catalogue(entries) print("now run: npm run build:site") if __name__ == "__main__": main()