#!/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-storybook` and before `npm run build` when you add or remove a component. It prints the entries to paste into 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 `---`, 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. """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path REPO = Path(__file__).resolve().parent.parent 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", } # 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 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", } 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()] 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 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) 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"], }) 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 src/data/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") if __name__ == "__main__": main()