Skip to content

Agent skill that draws an original icon library matching your design system (React, Vue, Svelte, React Native, SVG).

42.2 KB
Raw Blame
#!/usr/bin/env python3
"""Build an icon package from one source file (icons.json + icon-style.json).

  python3 build.py icons.json --out ./packages/icons [--framework react] [--only a,b]
                   [--compare ./ref-svgs] [--name @acme/icons]
  python3 build.py --gallery a.json b.json ... --out gallery.html

Outputs: framework components (one file per icon), svg/ (hex colors), sprite.svg
(CSS variables), icons.css (tones per state and theme), manifest.json,
catalog.html (self-contained review page) and README.md.
Python 3.8+, standard library only.
"""
import argparse
import datetime
import glob
import html
import json
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from iconlib import (STATES, SourceError, component_name, esc, flat_icons, fmt, gradient_defs,  # noqa: E402
                     icon_nodes, load_source, node_tones, paint_props, palette_color, parse_color,
                     svg_document, svg_inner, tone_fallback)

FRAMEWORKS = ("react", "vue", "svelte", "react-native", "svg")
HOVER_SEL = [':is(a, button, [role="button"], [role="menuitem"], [role="tab"]):hover', '[data-icon-state="hover"]']
ACTIVE_SEL = ['[aria-current="page"]', '[aria-selected="true"]', '[aria-pressed="true"]', '[data-icon-state="active"]']
DISABLED_SEL = [":disabled", '[aria-disabled="true"]', '[data-icon-state="disabled"]']
CAMEL = {"stroke-width": "strokeWidth", "stroke-linecap": "strokeLinecap", "stroke-linejoin": "strokeLinejoin",
         "fill-rule": "fillRule", "clip-rule": "clipRule", "fill-opacity": "fillOpacity",
         "stroke-opacity": "strokeOpacity", "stop-color": "stopColor", "stop-opacity": "stopOpacity"}
RN_TAGS = {"path": "Path", "rect": "Rect", "circle": "Circle", "ellipse": "Ellipse", "line": "Line",
           "polyline": "Polyline", "polygon": "Polygon"}


def camel(k):
    return CAMEL.get(k, k)


def write(path, text):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as fh:
        fh.write(text)


# ---------------- CSS (tones per state and theme) ----------------

def tone_vars(style, theme, state):
    p, out = style["prefix"], []
    for tone in style["tones"]:
        try:
            c = palette_color(style, theme, state, tone)
        except SourceError:
            continue
        if c["kind"] == "gradient":
            for i, st in enumerate(c["stops"]):
                out.append("--%s-%s-%d: %s; --%s-%s-%d-opacity: %s;" % (p, tone, i, st["hex"], p, tone, i, fmt(st["opacity"])))
        else:
            val = "var(--%s, %s)" % (c["token"].lstrip("-"), c["hex"]) if c.get("token") else c["hex"]
            out.append("--%s-%s: %s; --%s-%s-opacity: %s;" % (p, tone, val, p, tone, fmt(c["opacity"])))
    return " ".join(out)


def build_css(style, scope=None, dark_selectors=None, dark_mode=None):
    dark_selectors = dark_selectors or style.get("darkSelector") or [".dark", '[data-theme="dark"]']
    if isinstance(dark_selectors, str):
        dark_selectors = [dark_selectors]
    dark_mode = dark_mode or style.get("darkMode", "class")
    pre = (scope + " ") if scope else ""
    root = scope or ":root"

    def rule(sels, body):
        return ":where(%s) { %s }" % (", ".join(sels), body)

    def block(theme, dark_prefixes):
        lines = []
        if dark_prefixes is None:
            lines.append(rule([root], tone_vars(style, theme, "default")))
            ctx = [pre]
        else:
            lines.append(rule([pre + d for d in dark_prefixes], tone_vars(style, theme, "default")))
            ctx = [pre + d + " " for d in dark_prefixes]
        for state, sels in (("hover", HOVER_SEL), ("active", ACTIVE_SEL), ("disabled", DISABLED_SEL)):
            lines.append(rule([c + s for c in ctx for s in sels], tone_vars(style, theme, state)))
        return lines

    out = ["/* Icon tones per state and theme. Generated by generate-icons; edit icon-style.json, not this file. */"]
    out += block("light", None)
    if "dark" in style["palette"]:
        if dark_mode in ("class", "both"):
            out += block("dark", dark_selectors)
        if dark_mode in ("media", "both") and not scope:
            out.append("@media (prefers-color-scheme: dark) {")
            out += ["  " + line for line in block("dark", None)]
            out.append("}")
    return "\n".join(out) + "\n"


# ---------------- framework backends ----------------

def react_node(n, style, gid_expr):
    attrs, css = paint_props(n, style, "vars", gid=lambda t: "@@%s@@" % t)
    parts = ['%s="%s"' % (k, v) for k, v in n["geom"].items()]
    for k, v in attrs.items():
        if "@@" in v:
            tone = v.split("@@")[1]
            parts.append("%s={`url(#${id}-%s)`}" % (camel(k), tone))
        else:
            parts.append('%s="%s"' % (camel(k), v))
    if css:
        parts.append("style={{ %s }}" % ", ".join('%s: "%s"' % (camel(k), v) for k, v in css.items()))
    return "<%s %s />" % (n["tag"], " ".join(parts))


def react_defs(style, nodes):
    defs = gradient_defs(style, nodes, "vars", gid=lambda t: t)
    if not defs:
        return []
    out = ["<defs>"]
    for tone, x1, y1, x2, y2, stops in defs:
        out.append('  <linearGradient id={`${id}-%s`} x1="%s" y1="%s" x2="%s" y2="%s">' % (tone, x1, y1, x2, y2))
        for off, color, op in stops:
            out.append('    <stop offset="%s" style={{ stopColor: "%s", stopOpacity: "%s" }} />' % (off, color, op))
        out.append("  </linearGradient>")
    out.append("</defs>")
    return out


def gen_react(icons, style, out):
    g = fmt(style["grid"])
    rendering = '\n        shapeRendering="%s"' % style["rendering"] if style.get("rendering") else ""
    write(os.path.join(out, "src", "create-icon.tsx"), REACT_BASE.replace("__GRID__", g).replace("__RENDERING__", rendering))
    for icon in icons:
        nodes = icon_nodes(icon, style)
        body = react_defs(style, nodes) + [react_node(n, style, None) for n in nodes]
        uses_id = any("${id}" in b for b in body)
        cname = component_name(icon["name"])
        text = ('import { createIcon } from "../create-icon"\n\n'
                "/** %s */\nexport const %s = createIcon(\"%s\", (%s) => (\n  <>\n%s\n  </>\n))\n\nexport default %s\n"
                % (icon["label"], cname, cname, "id" if uses_id else "", "\n".join("    " + b for b in body), cname))
        write(os.path.join(out, "src", "icons", icon["name"] + ".tsx"), text)
    return "tsx"


def vue_node(n, style):
    attrs, css = paint_props(n, style, "vars", gid=lambda t: "@@%s@@" % t)
    props = ["%s: %s" % (json.dumps(k), json.dumps(v)) for k, v in n["geom"].items()]
    for k, v in attrs.items():
        if "@@" in v:
            props.append("%s: `url(#${id}-%s)`" % (json.dumps(k), v.split("@@")[1]))
        else:
            props.append("%s: %s" % (json.dumps(k), json.dumps(v)))
    if css:
        props.append('style: %s' % json.dumps(";".join("%s:%s" % kv for kv in css.items())))
    return 'h("%s", { %s })' % (n["tag"], ", ".join(props))


def gen_vue(icons, style, out):
    g = fmt(style["grid"])
    rendering = ', "shape-rendering": "%s"' % style["rendering"] if style.get("rendering") else ""
    write(os.path.join(out, "src", "create-icon.ts"), VUE_BASE.replace("__GRID__", g).replace("__RENDERING__", rendering))
    for icon in icons:
        nodes = icon_nodes(icon, style)
        items, grads = [], []
        for tone, x1, y1, x2, y2, stops in gradient_defs(style, nodes, "vars", gid=lambda t: t):
            st = ", ".join('h("stop", { offset: "%s", style: "stop-color:%s;stop-opacity:%s" })' % s for s in stops)
            grads.append('h("linearGradient", { id: `${id}-%s`, x1: "%s", y1: "%s", x2: "%s", y2: "%s" }, [%s])'
                         % (tone, x1, y1, x2, y2, st))
        if grads:
            items.append('h("defs", [%s])' % ", ".join(grads))
        items += [vue_node(n, style) for n in nodes]
        uses_id = any("${id}" in i for i in items)
        cname = component_name(icon["name"])
        text = ('import { h } from "vue"\nimport { createIcon } from "../create-icon"\n\n'
                "/** %s */\nexport const %s = createIcon(\"%s\", (%s) => [\n%s,\n])\n\nexport default %s\n"
                % (icon["label"], cname, cname, "id" if uses_id else "", ",\n".join("  " + i for i in items), cname))
        write(os.path.join(out, "src", "icons", icon["name"] + ".ts"), text)
    return "ts"


def gen_svelte(icons, style, out):
    g = fmt(style["grid"])
    rendering = ' shape-rendering="%s"' % style["rendering"] if style.get("rendering") else ""
    for icon in icons:
        nodes = icon_nodes(icon, style)
        body = []
        grads = ['<linearGradient id="{id}-%s" x1="%s" y1="%s" x2="%s" y2="%s">%s</linearGradient>' % (
            tone, x1, y1, x2, y2, "".join('<stop offset="%s" style="stop-color:%s;stop-opacity:%s" />' % s for s in stops))
            for tone, x1, y1, x2, y2, stops in gradient_defs(style, nodes, "vars", gid=lambda t: t)]
        if grads:
            body.append("<defs>%s</defs>" % "".join(grads))
        for n in nodes:
            attrs, css = paint_props(n, style, "vars", gid=lambda t: "{id}-" + t)
            parts = ['%s="%s"' % kv for kv in n["geom"].items()] + ['%s="%s"' % kv for kv in attrs.items()]
            if css:
                parts.append('style="%s"' % ";".join("%s:%s" % kv for kv in css.items()))
            body.append("<%s %s />" % (n["tag"], " ".join(parts)))
        text = SVELTE_ICON.replace("__GRID__", g).replace("__RENDERING__", rendering).replace(
            "__LABEL__", icon["label"]).replace("__BODY__", "\n  ".join(body))
        write(os.path.join(out, "src", "icons", icon["name"] + ".svelte"), text)
    return "svelte"


def gen_react_native(icons, style, out):
    g = fmt(style["grid"])
    tones = list(style["tones"])
    palette = {}
    for theme in style["palette"]:
        palette[theme] = {}
        for state in STATES:
            palette[theme][state] = {}
            for tone in tones:
                try:
                    c = palette_color(style, theme, state, tone)
                except SourceError:
                    continue
                palette[theme][state][tone] = c["stops"][0]["hex"] if c["kind"] == "gradient" else c["hex"]
    fallback_op = {t: tone_fallback(style, t)[1] for t in tones}
    base = (RN_BASE.replace("__GRID__", g)
            .replace("__TONES__", " | ".join(json.dumps(t) for t in tones))
            .replace("__PALETTE__", json.dumps(palette, indent=2))
            .replace("__FALLBACK_OPACITY__", json.dumps(fallback_op)))
    write(os.path.join(out, "src", "create-icon.tsx"), base)
    for icon in icons:
        nodes = icon_nodes(icon, style)
        used = {"Svg"}
        body = []
        defs = gradient_defs(style, nodes, "hex", gid=lambda t: "%s-%s" % (icon["name"], t))
        if defs:
            used |= {"Defs", "LinearGradient", "Stop"}
            body.append("<Defs>")
            for tone, x1, y1, x2, y2, stops in defs:
                body.append('  <LinearGradient id="%s" x1="%s" y1="%s" x2="%s" y2="%s">' % (tone, x1, y1, x2, y2))
                for off, color, op in stops:
                    body.append('    <Stop offset="%s" stopColor="%s" stopOpacity={%s} />' % (off, color, op))
                body.append("  </LinearGradient>")
            body.append("</Defs>")
        grad_tones = {d[0][len(icon["name"]) + 1:] for d in defs}
        for n in nodes:
            tag = RN_TAGS[n["tag"]]
            used.add(tag)
            attrs, _ = paint_props(n, style, "hex", gid=lambda t: t)
            kind = n["paint"]
            parts = ['%s="%s"' % kv for kv in n["geom"].items()]
            for k, v in attrs.items():
                if k in (kind, kind + "-opacity"):
                    continue
                parts.append('%s="%s"' % (camel(k), v))
            if n["tone"] in grad_tones:
                parts.append('%s="url(#%s-%s)"' % (kind, icon["name"], n["tone"]))
            else:
                parts.append('%s={t("%s").color} %sOpacity={t("%s").opacity}' % (kind, n["tone"], kind, n["tone"]))
            body.append("<%s %s />" % (tag, " ".join(parts)))
        cname = component_name(icon["name"])
        imports = sorted(used - {"Svg"})
        arg = "t" if any("{t(" in b for b in body) else ""
        text = ('import { %s } from "react-native-svg"\nimport { createIcon } from "../create-icon"\n\n'
                "/** %s */\nexport const %s = createIcon(\"%s\", (%s) => (\n  <>\n%s\n  </>\n))\n\nexport default %s\n"
                % (", ".join(imports), icon["label"], cname, cname, arg, "\n".join("    " + b for b in body), cname))
        write(os.path.join(out, "src", "icons", icon["name"] + ".tsx"), text)
    return "tsx"


def gen_index(icons, out, framework, ext):
    if framework == "svg":
        return
    lines = []
    for icon in icons:
        cname = component_name(icon["name"])
        if framework == "svelte":
            lines.append('export { default as %s } from "./icons/%s.svelte"' % (cname, icon["name"]))
        else:
            lines.append('export { %s } from "./icons/%s"' % (cname, icon["name"]))
    if framework in ("react", "react-native"):
        lines.append('export { createIcon } from "./create-icon"')
        lines.append('export type { IconProps, Icon } from "./create-icon"')
    if framework == "react-native":
        lines.append('export { palette } from "./create-icon"')
    if framework == "vue":
        lines.append('export { createIcon } from "./create-icon"')
    write(os.path.join(out, "src", "index.ts"), "\n".join(lines) + "\n")


def gen_package_json(src, style, out, framework, ext, name):
    existing = os.path.join(out, "package.json")
    if os.path.exists(existing):
        return  # never overwrite a package.json the project already owns
    pkg = {"name": name, "version": (src.get("package") or {}).get("version", "0.1.0"), "private": True,
           "description": "Icon library generated with generate-icons (%s style)." % style.get("name", "custom"),
           "sideEffects": ["*.css"], "files": ["src", "svg", "sprite.svg", "icons.css", "manifest.json"]}
    exports = {"./icons.css": "./icons.css", "./sprite.svg": "./sprite.svg", "./svg/*": "./svg/*",
               "./manifest.json": "./manifest.json"}
    peers = {"react": {"react": ">=18"}, "react-native": {"react": ">=18", "react-native-svg": ">=13"},
             "vue": {"vue": ">=3.5"}, "svelte": {"svelte": ">=5.20"}}.get(framework)
    if framework != "svg":
        exports = dict({".": "./src/index.ts", "./icons/*": "./src/icons/*.%s" % ext}, **exports)
        pkg["main"] = "./src/index.ts"
        pkg["types"] = "./src/index.ts"
        if framework == "svelte":
            pkg["svelte"] = "./src/index.ts"
    pkg["exports"] = exports
    if peers:
        pkg["peerDependencies"] = peers
    write(existing, json.dumps(pkg, indent=2) + "\n")


# ---------------- sprite, svg files, manifest ----------------

def build_sprite(icons, style, prefix="", data_tone=False, mode="vars"):
    g = fmt(style["grid"])
    syms = []
    for icon in icons:
        sid = prefix + icon["name"]
        syms.append('<symbol id="%s" viewBox="0 0 %s %s">%s</symbol>' % (
            sid, g, g, svg_inner(icon, style, mode, id_prefix=sid, data_tone=data_tone)))
    return syms


def strip_svg(text):
    text = re.sub(r"<\?xml[^>]*>|<!DOCTYPE[^>]*>|<!--.*?-->", "", text, flags=re.S)
    text = re.sub(r"<script.*?</script>", "", text, flags=re.S | re.I)
    text = re.sub(r"\son\w+=\"[^\"]*\"", "", text)
    text = re.sub(r"(<svg\b[^>]*?)\s(width|height)=\"[^\"]*\"", r"\1", text)
    text = re.sub(r"(<svg\b[^>]*?)\s(width|height)=\"[^\"]*\"", r"\1", text)
    return text.strip()


# ---------------- catalog ----------------

CATALOG_CSS = """
*{box-sizing:border-box}body{margin:0;font:14px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#F6F7F9;color:#1B1F27}
header{padding:28px 32px 8px}h1{margin:0 0 4px;font-size:22px}h2{font-size:15px;margin:28px 32px 10px;text-transform:uppercase;letter-spacing:.06em;color:#5A6273}
.muted{color:#6B7385}.wrap{padding:0 32px 40px}
.bar{position:sticky;top:0;z-index:5;display:flex;gap:16px;align-items:center;padding:10px 32px;background:rgba(246,247,249,.92);backdrop-filter:blur(6px);border-bottom:1px solid #E3E6EC}
.bar input[type=search]{padding:7px 10px;border:1px solid #CDD2DB;border-radius:8px;min-width:240px;font:inherit}
.bar label{display:flex;gap:6px;align-items:center;cursor:pointer}
table.why{border-collapse:collapse;margin:8px 0 0;font-size:13px}table.why td{padding:4px 12px 4px 0;vertical-align:top;border-bottom:1px solid #E3E6EC}
.rows{display:grid;gap:10px}
.row{display:grid;grid-template-columns:180px 1fr 1fr;gap:10px;align-items:stretch}
.name{padding:12px;background:#fff;border-radius:12px;border:1px solid #E3E6EC}.name b{display:block;font-size:13px}.name code{font-size:11px;color:#6B7385}
.panel{display:flex;gap:14px;align-items:flex-end;padding:12px 14px;border-radius:12px;border:1px solid #E3E6EC;background:#fff;overflow-x:auto}
.panel.gi-dark{background:#14171E;border-color:#262B36;color:#C9CED8}
.cell{display:flex;flex-direction:column;align-items:center;gap:6px;font-size:10px;color:#8A92A3;min-width:34px}
.cell svg{display:block}.sep{width:1px;align-self:stretch;background:#E3E6EC}.gi-dark .sep{background:#2C3240}
.grid-px .cell svg{background-image:linear-gradient(to right,rgba(127,127,127,.18) 1px,transparent 1px),linear-gradient(to bottom,rgba(127,127,127,.18) 1px,transparent 1px);outline:1px dashed rgba(127,127,127,.35)}
.detail-only [data-tone]:not([data-tone="__DETAIL__"]){opacity:0}
.ctx{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.app{display:grid;grid-template-columns:200px 1fr;min-height:260px;overflow:hidden;border:1px solid #E3E6EC}
.app nav{padding:14px 10px;display:flex;flex-direction:column;gap:2px}
.app nav a{display:flex;gap:10px;align-items:center;padding:8px 10px;text-decoration:none;color:inherit}
.app main{padding:18px;display:flex;flex-direction:column;gap:14px}
.btns{display:flex;gap:8px;flex-wrap:wrap}.btn{display:inline-flex;gap:8px;align-items:center;padding:8px 14px;border:1px solid transparent;font:inherit;cursor:pointer}
.empty{display:flex;flex-direction:column;align-items:center;gap:8px;padding:18px;border:1px dashed;text-align:center}
.compare{display:flex;flex-direction:column;align-items:flex-start;gap:8px}.compare .set{display:flex;gap:12px;align-items:center;padding:12px 14px;background:#fff;border:1px solid #E3E6EC;border-radius:12px}
.compare .set span{font-size:11px;color:#6B7385;width:64px}
"""

CATALOG_JS = """
const q=document.getElementById('q');q&&q.addEventListener('input',()=>{const v=q.value.trim().toLowerCase();document.querySelectorAll('.row').forEach(r=>{r.style.display=!v||r.dataset.k.includes(v)?'':'none'})});
const d=document.getElementById('detail');d&&d.addEventListener('change',()=>document.body.classList.toggle('detail-only',d.checked));
const gp=document.getElementById('gridpx');gp&&gp.addEventListener('change',()=>document.body.classList.toggle('grid-px',gp.checked));
"""


def use(sid, size, state=None, grid=24):
    st = ' data-icon-state="%s"' % state if state and state != "default" else ""
    return '<svg width="%s" height="%s" viewBox="0 0 %s %s" aria-hidden="true"%s><use href="#%s"/></svg>' % (
        size, size, fmt(grid), fmt(grid), st, sid)


def state_cells(sid, style):
    sizes = sorted(set(style["sizes"]) | {16, 24})
    cells = ['<div class="cell">%s%s</div>' % (use(sid, 24, s, style["grid"]), s) for s in STATES]
    cells.append('<div class="sep"></div>')
    cells += ['<div class="cell">%s%s</div>' % (use(sid, z, None, style["grid"]), z) for z in sizes]
    return "".join(cells)


def context_preview(icons, style):
    ctx = style.get("context") or {}
    font = ctx.get("font", "inherit")
    radius = ctx.get("radius", 10)
    brand = ctx.get("brand", "#3B5BDB")
    on_brand = ctx.get("onBrand", "#FFFFFF")
    tones = list(style["tones"])
    p = style["prefix"]
    cur = "; ".join("--%s-%s: currentColor; --%s-%s-opacity: %s" % (p, t, p, t, "1" if i == 0 else ".5") for i, t in enumerate(tones))
    nav = icons[:6]
    il = icons[0]
    panels = []
    for theme in ("light", "dark"):
        if theme == "dark" and "dark" not in style["palette"]:
            continue
        surface = ctx.get("surface" if theme == "light" else "surfaceDark", "#FFFFFF" if theme == "light" else "#14171E")
        side = ctx.get("sidebar" if theme == "light" else "sidebarDark", "#F3F4F7" if theme == "light" else "#1A1E27")
        text = ctx.get("text" if theme == "light" else "textDark", "#1B1F27" if theme == "light" else "#E6E8EE")
        border = ctx.get("border" if theme == "light" else "borderDark", "#E3E6EC" if theme == "light" else "#2A303C")
        links = "".join('<a href="#" %s style="border-radius:%spx%s">%s<span>%s</span></a>' % (
            'aria-current="page"' if i == 1 else "", radius,
            ";background:%s" % ("rgba(0,0,0,.05)" if theme == "light" else "rgba(255,255,255,.06)") if i == 1 else "",
            use(p_id(ic), 20, None, style["grid"]), esc(ic["label"])) for i, ic in enumerate(nav))
        illo = ("il-" + il["name"]) if style.get("illustration") else p_id(il)
        panels.append(
            '<div class="app%s" style="font-family:%s;background:%s;color:%s;border-radius:%spx;border-color:%s">'
            '<nav style="background:%s">%s</nav><main>'
            '<div class="btns"><button class="btn" style="background:%s;color:%s;border-radius:%spx;%s">%s New item</button>'
            '<button class="btn" style="background:transparent;color:inherit;border-color:%s;border-radius:%spx">%s Settings</button>'
            '<button class="btn" disabled style="background:transparent;color:inherit;opacity:.6;border-color:%s;border-radius:%spx">%s Disabled</button></div>'
            '<div class="empty" style="border-color:%s;border-radius:%spx">%s<b>Nothing here yet</b><span class="muted">Empty state with the large variant.</span></div>'
            "</main></div>" % (
                " gi-dark" if theme == "dark" else "", esc(font), surface, text, radius, border, side, links,
                brand, on_brand, radius, cur, use(p_id(icons[min(2, len(icons) - 1)]), 18, None, style["grid"]),
                border, radius, use(p_id(icons[min(3, len(icons) - 1)]), 18, None, style["grid"]),
                border, radius, use(p_id(icons[min(4, len(icons) - 1)]), 18, None, style["grid"]),
                border, radius, '<svg width="72" height="72" viewBox="0 0 %s %s" aria-hidden="true"><use href="#%s"/></svg>' % (
                    fmt(style["grid"]), fmt(style["grid"]), illo)))
    return '<div class="ctx">%s</div>' % "".join(panels)


def p_id(icon):
    return "i-" + icon["name"]


def rationale_table(style):
    rows = style.get("rationale") or []
    if not rows:
        return ""
    cells = "".join("<tr><td><b>%s</b></td><td>%s</td><td class=muted>%s</td></tr>" % (
        esc(r.get("decision", "")), esc(r.get("because", "")), esc(r.get("source", ""))) for r in rows)
    return '<table class="why">%s</table>' % cells


def build_catalog(src, style, icons, compare_dir=None):
    name = (src.get("package") or {}).get("name") or src.get("name") or "icons"
    css = build_css(style, dark_selectors=[".gi-dark"], dark_mode="class")
    sprite = build_sprite(icons, style, prefix="i-", data_tone=True)
    if style.get("illustration"):
        sprite += ['<symbol id="il-%s" viewBox="0 0 %s %s">%s</symbol>' % (
            ic["name"], fmt(style["grid"]), fmt(style["grid"]),
            svg_inner(ic, style, "illo", id_prefix="il-" + ic["name"])) for ic in icons]
    detail = next(iter(style["tones"]))
    groups = []
    for icon in icons:
        if icon["group"] not in groups:
            groups.append(icon["group"])
    body = []
    for group in groups:
        body.append("<h2>%s</h2><div class='wrap rows'>" % esc(group))
        for icon in [i for i in icons if i["group"] == group]:
            sid = p_id(icon)
            big = ""
            if style.get("illustration"):
                big = '<div class="sep"></div>' + "".join(
                    '<div class="cell"><svg width="%s" height="%s" viewBox="0 0 %s %s" aria-hidden="true"><use href="#il-%s"/></svg>%s</div>'
                    % (z, z, fmt(style["grid"]), fmt(style["grid"]), icon["name"], z)
                    for z in (style["illustration"].get("sizes") or [48, 96]))
            key = " ".join([icon["name"], icon["label"]] + list(icon.get("tags") or [])).lower()
            body.append(
                '<div class="row" data-k="%s"><div class="name"><b>%s</b><code>%s · %s</code></div>'
                '<div class="panel">%s%s</div><div class="panel gi-dark">%s%s</div></div>' % (
                    esc(key), esc(icon["label"]), esc(icon["name"]), esc(component_name(icon["name"])),
                    state_cells(sid, style), big, state_cells(sid, style), big))
        body.append("</div>")
    compare = ""
    if compare_dir:
        refs = sorted(glob.glob(os.path.join(compare_dir, "*.svg")))[:24]
        if refs:
            def ref_cells(size):
                out = []
                for f in refs:
                    with open(f, encoding="utf-8") as fh:
                        svg = strip_svg(fh.read())
                    out.append(svg.replace("<svg", '<svg width="%s" height="%s"' % (size, size), 1))
                return "".join(out)
            ours = lambda size: "".join(use(p_id(i), size, None, style["grid"]) for i in icons[:len(refs)])
            compare = ("<h2>Side by side with the project's current icons</h2><div class='wrap compare'>"
                       "<div class='set'><span>project 24</span>%s</div><div class='set'><span>new 24</span>%s</div>"
                       "<div class='set'><span>project 16</span>%s</div><div class='set'><span>new 16</span>%s</div></div>"
                       % (ref_cells(24), ours(24), ref_cells(16), ours(16)))
    meta = "%d icons · style <b>%s</b> · grid %s, live area %s · %s" % (
        len(icons), esc(style.get("name", "custom")), fmt(style["grid"]), fmt(style["live"]),
        "stroke %s" % fmt(style["stroke"]["width"]) if style["paint"] == "stroke" else "filled")
    page = CATALOG_HTML
    if len(style["tones"]) < 2:
        page = page.replace('<label><input id="detail" type="checkbox"> Primary tone only (16 px legibility)</label>', "")
    return page.format(
        title=esc(name), css=CATALOG_CSS.replace("__DETAIL__", detail) + css, sprite="".join(sprite), meta=meta,
        why=rationale_table(style), ctx=context_preview(icons, style), compare=compare, body="".join(body),
        js=CATALOG_JS, date=datetime.date.today().isoformat())


CATALOG_HTML = """<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title} · icon catalog</title><style>{css}</style></head>
<body>
<svg width="0" height="0" style="position:absolute" aria-hidden="true">{sprite}</svg>
<header><h1>{title}</h1><div class="muted">{meta} · built {date}</div>{why}</header>
<div class="bar"><input id="q" type="search" placeholder="Filter by name or tag">
<label><input id="detail" type="checkbox"> Primary tone only (16 px legibility)</label>
<label><input id="gridpx" type="checkbox"> Show icon bounds</label>
<span class="muted">Columns: default · hover · active · disabled | sizes</span></div>
<h2>In context</h2><div class="wrap">{ctx}</div>
{compare}
{body}
<script>{js}</script>
</body></html>
"""


# ---------------- gallery (compare styles) ----------------

def build_gallery(paths):
    sections, sprites, css = [], [], []
    for n, path in enumerate(paths):
        src, style = load_source(path)
        icons = flat_icons(src)
        scope = "#s%d" % n
        css.append(build_css(style, scope=scope, dark_selectors=[".gi-dark"], dark_mode="class"))
        pre = "s%d-" % n
        sprites += build_sprite(icons, style, prefix=pre)
        g = style["grid"]

        def cells(state, size):
            return "".join('<div class="cell">%s</div>' % use(pre + i["name"], size, state, g) for i in icons)
        sections.append(
            '<section id="s%d"><h2>%s</h2><div class="wrap"><p class="muted">%s</p>'
            '<div class="row" style="grid-template-columns:1fr 1fr"><div class="panel">%s<div class="sep"></div>%s<div class="sep"></div>%s</div>'
            '<div class="panel gi-dark">%s<div class="sep"></div>%s<div class="sep"></div>%s</div></div></div></section>' % (
                n, esc(style.get("name", os.path.basename(path))), esc(src.get("description", "")),
                cells("default", 24), cells("active", 24), cells("default", 48),
                cells("default", 24), cells("active", 24), cells("default", 48)))
    return CATALOG_HTML.format(
        title="Style gallery", css=CATALOG_CSS + "\n".join(css), sprite="".join(sprites),
        meta="%d styles · each row: default 24 · active 24 · 48" % len(paths), why="", ctx="", compare="",
        body="".join(sections), js="", date=datetime.date.today().isoformat()).replace(
        '<h2>In context</h2><div class="wrap"></div>', "").replace(
        '<label><input id="detail" type="checkbox"> Primary tone only (16 px legibility)</label>', "").replace(
        '<span class="muted">Columns: default · hover · active · disabled | sizes</span>', "")


# ---------------- README ----------------

def build_readme(src, style, icons, framework, name):
    first = icons[0]
    cname = component_name(first["name"])
    usage = {
        "react": '```tsx\nimport { %s } from "%s"\n// or, for the smallest bundle: import %s from "%s/icons/%s"\n\n'
                 '<%s />                       // decorative: aria-hidden\n<%s size={16} title="%s" /> // informative: role="img" + <title>\n```'
                 % (cname, name, cname, name, first["name"], cname, cname, first["label"]),
        "react-native": '```tsx\nimport { %s, palette } from "%s"\n\n<%s size={20} />\n<%s colors={palette.light.active} title="%s" />\n<%s color="#FFFFFF" />  // every tone in one color (on brand surfaces)\n```'
                        % (cname, name, cname, cname, first["label"], cname),
        "vue": '```vue\n<script setup lang="ts">\nimport { %s } from "%s"\n</script>\n\n<template>\n  <%s :size="20" />\n  <%s title="%s" />\n</template>\n```'
               % (cname, name, cname, cname, first["label"]),
        "svelte": '```svelte\n<script lang="ts">\n  import { %s } from "%s"\n</script>\n\n<%s size={20} />\n<%s title="%s" />\n```'
                  % (cname, name, cname, cname, first["label"]),
        "svg": '```html\n<!-- inline sprite (inherits CSS variables) -->\n<svg width="24" height="24" aria-hidden="true"><use href="/sprite.svg#%s"/></svg>\n<!-- standalone file (hex colors, works in <img>, e-mail and design tools) -->\n<img src="/svg/%s.svg" width="24" height="24" alt="%s">\n```'
               % (first["name"], first["name"], first["label"]),
    }[framework]
    p = style["prefix"]
    tones = list(style["tones"])
    table = "\n".join("| `%s` | %s | %s | `%s` |" % (
        i["name"], i["label"], i["group"], component_name(i["name"])) for i in icons)
    css_note = "" if framework == "react-native" else (
        "## Colors and states\n\nEvery shape is painted with a CSS variable per tone (%s), falling back to `currentColor`, so the icons work "
        "with no setup. Import `icons.css` once to get the exact palette, states and dark mode:\n\n"
        "```css\n@import \"%s/icons.css\";\n```\n\n"
        "States follow the markup: `:hover` on links and buttons, `aria-current=\"page\"`, `aria-selected`, `aria-pressed` "
        "and `data-icon-state=\"active\"` for active, `:disabled`, `aria-disabled` and `data-icon-state=\"disabled\"` for disabled. "
        "Dark mode follows %s. To recolor one place, set the variables there:\n\n"
        "```css\n.on-brand { %s }\n```\n" % (
            ", ".join("`--%s-%s`" % (p, t) for t in tones), name,
            "`prefers-color-scheme`" if style.get("darkMode") == "media" else "`%s`" % ", ".join(
                style.get("darkSelector") or [".dark", '[data-theme="dark"]']),
            " ".join("--%s-%s: currentColor;" % (p, t) for t in tones)))
    return README.format(name=name, style=style.get("name", "custom"), count=len(icons), usage=usage,
                         css=css_note, table=table, grid=fmt(style["grid"]), live=fmt(style["live"]))


README = """# {name}

{count} icons in the **{style}** style, drawn on a {grid} px grid with a {live} px live area.
Generated by the `generate-icons` skill from `icons.json`. Do not edit the generated files by hand:
change the source and run the build again.

## Use

{usage}

- `size` sets width and height (default 24).
- Without `title` or `aria-label` the icon is decorative and gets `aria-hidden`.
  With either one it becomes `role="img"` with an accessible name. Use that when the icon is the only
  thing that carries the meaning (an icon-only button still needs its own `aria-label` on the button).
- Each icon is its own module, so bundlers keep only the ones you import.

{css}
## Files

| Path | What it is |
|------|------------|
| `src/` | One component per icon plus an index (absent for plain SVG). |
| `svg/` | Standalone SVGs with the default light palette in hex: for `<img>`, e-mail, Figma. |
| `sprite.svg` | All icons as `<symbol>`, painted with the CSS variables. |
| `icons.css` | The tone variables per state and theme. |
| `manifest.json` | Names, labels, groups and tags, for search or docs. |
| `catalog.html` | Review page: every icon in every state and size, light and dark. |

## Icons

| Name | Label | Group | Component |
|------|-------|-------|-----------|
{table}

## Regenerate

```bash
python3 <skill>/scripts/validate.py icons.json
python3 <skill>/scripts/build.py icons.json --out .
```
"""


# ---------------- templates ----------------

REACT_BASE = '''import * as React from "react"

export interface IconProps extends Omit<React.SVGProps<SVGSVGElement>, "ref"> {
  /** Width and height. Default 24. */
  size?: number | string
  /** Accessible name. Without it (or aria-label) the icon is decorative and hidden from assistive tech. */
  title?: string
}

export type Icon = React.ForwardRefExoticComponent<IconProps & React.RefAttributes<SVGSVGElement>>

export function createIcon(displayName: string, render: (id: string) => React.ReactNode): Icon {
  const Component = React.forwardRef<SVGSVGElement, IconProps>(function GeneratedIcon(
    { size = 24, title, children, ...props },
    ref,
  ) {
    const id = "gi" + React.useId().replace(/[^a-zA-Z0-9_-]/g, "")
    const labelled = Boolean(title || props["aria-label"] || props["aria-labelledby"])
    return (
      <svg
        ref={ref}
        xmlns="http://www.w3.org/2000/svg"
        width={size}
        height={size}
        viewBox="0 0 __GRID__ __GRID__"__RENDERING__
        focusable="false"
        role={labelled ? "img" : undefined}
        aria-hidden={labelled ? undefined : true}
        aria-labelledby={title && !props["aria-label"] ? `${id}-title` : undefined}
        {...props}
      >
        {title ? <title id={`${id}-title`}>{title}</title> : null}
        {render(id)}
        {children}
      </svg>
    )
  })
  Component.displayName = displayName
  return Component
}
'''

VUE_BASE = '''import { defineComponent, h, useId, type PropType, type VNode } from "vue"

export function createIcon(name: string, render: (id: string) => VNode[]) {
  return defineComponent({
    name,
    props: {
      /** Width and height. Default 24. */
      size: { type: [Number, String] as PropType<number | string>, default: 24 },
      /** Accessible name. Without it (or aria-label) the icon is decorative. */
      title: { type: String, default: undefined },
    },
    setup(props, { attrs }) {
      const id = "gi" + String(useId()).replace(/[^a-zA-Z0-9_-]/g, "")
      return () => {
        const labelled = Boolean(props.title || attrs["aria-label"] || attrs["aria-labelledby"])
        return h(
          "svg",
          {
            xmlns: "http://www.w3.org/2000/svg",
            width: props.size,
            height: props.size,
            viewBox: "0 0 __GRID__ __GRID__"__RENDERING__,
            focusable: "false",
            role: labelled ? "img" : undefined,
            "aria-hidden": labelled ? undefined : "true",
            "aria-labelledby": props.title && !attrs["aria-label"] ? `${id}-title` : undefined,
          },
          [props.title ? h("title", { id: `${id}-title` }, props.title) : null, ...render(id)],
        )
      }
    },
  })
}
'''

SVELTE_ICON = '''<!-- __LABEL__ -->
<script lang="ts">
  import type { SVGAttributes } from "svelte/elements"

  let {
    size = 24,
    title = undefined,
    ...rest
  }: { size?: number | string; title?: string } & SVGAttributes<SVGSVGElement> = $props()
  const id = "gi" + $props.id().replace(/[^a-zA-Z0-9_-]/g, "")
  const labelled = $derived(Boolean(title || rest["aria-label"] || rest["aria-labelledby"]))
</script>

<svg
  xmlns="http://www.w3.org/2000/svg"
  width={size}
  height={size}
  viewBox="0 0 __GRID__ __GRID__"__RENDERING__
  focusable="false"
  role={labelled ? "img" : undefined}
  aria-hidden={labelled ? undefined : "true"}
  aria-labelledby={title && !rest["aria-label"] ? `${id}-title` : undefined}
  {...rest}
>
  {#if title}<title id="{id}-title">{title}</title>{/if}
  __BODY__
</svg>
'''

RN_BASE = '''import * as React from "react"
import Svg, { type SvgProps } from "react-native-svg"

export type Tone = __TONES__
export type IconColors = Partial<Record<Tone, string>>

/** The palette from icon-style.json: palette[theme][state][tone]. */
export const palette = __PALETTE__ as const

const FALLBACK_OPACITY: Record<string, number> = __FALLBACK_OPACITY__

export interface IconProps extends SvgProps {
  /** Width and height. Default 24. */
  size?: number
  /** Paint every tone in one color (secondary tones keep their fallback opacity). */
  color?: string
  /** Exact color per tone, e.g. palette.light.active. Wins over `color`. */
  colors?: IconColors
  /** Accessible name. Without it the icon is hidden from screen readers. */
  title?: string
}

export type Icon = React.ForwardRefExoticComponent<IconProps & React.RefAttributes<Svg>>

type ToneResolver = (tone: Tone) => { color: string; opacity: number }

export function createIcon(displayName: string, render: (t: ToneResolver) => React.ReactNode): Icon {
  const Component = React.forwardRef<Svg, IconProps>(function GeneratedIcon(
    { size = 24, color, colors, title, children, ...props },
    ref,
  ) {
    const t: ToneResolver = (tone) => {
      const exact = colors?.[tone]
      if (exact) return { color: exact, opacity: 1 }
      if (color) return { color, opacity: FALLBACK_OPACITY[tone] ?? 1 }
      return { color: (palette.light.default as Record<string, string>)[tone], opacity: 1 }
    }
    const a11y = title
      ? { accessible: true, accessibilityRole: "image" as const, accessibilityLabel: title }
      : { accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants" as const }
    return (
      <Svg ref={ref} width={size} height={size} viewBox="0 0 __GRID__ __GRID__" {...a11y} {...props}>
        {render(t)}
        {children}
      </Svg>
    )
  })
  Component.displayName = displayName
  return Component
}
'''

GENERATORS = {"react": gen_react, "vue": gen_vue, "svelte": gen_svelte, "react-native": gen_react_native,
              "svg": lambda icons, style, out: None}


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("source", nargs="?", help="icons.json")
    ap.add_argument("--out", required=True, help="output directory (or .html file with --gallery)")
    ap.add_argument("--framework", choices=FRAMEWORKS)
    ap.add_argument("--name", help="package name (default: source package.name)")
    ap.add_argument("--only", help="comma-separated icon names to rewrite; aggregates are always rebuilt")
    ap.add_argument("--compare", help="directory of the project's current SVG icons to show side by side")
    ap.add_argument("--catalog-only", action="store_true", help="write only catalog.html (for samples)")
    ap.add_argument("--gallery", nargs="+", help="build one page comparing several sources")
    args = ap.parse_args(argv)

    if args.gallery:
        write(os.path.abspath(args.out), build_gallery(args.gallery))
        print("gallery: %s" % os.path.abspath(args.out))
        return 0
    if not args.source:
        ap.error("source is required")
    try:
        src, style = load_source(args.source)
        icons = flat_icons(src)
        if not icons:
            raise SourceError("the source has no icons")
        out = os.path.abspath(args.out)
        if args.catalog_only:
            write(os.path.join(out, "catalog.html"), build_catalog(src, style, icons, args.compare))
            print("catalog: %s" % os.path.join(out, "catalog.html"))
            return 0
        framework = args.framework or src.get("framework") or "react"
        name = args.name or (src.get("package") or {}).get("name") or "icons"
        only = set(filter(None, (args.only or "").split(",")))
        unknown = only - {i["name"] for i in icons}
        if unknown:
            raise SourceError("--only names not in the source: %s" % ", ".join(sorted(unknown)))
        targets = [i for i in icons if not only or i["name"] in only]
        ext = GENERATORS[framework](targets, style, out) or "svg"
        for icon in targets:
            write(os.path.join(out, "svg", icon["name"] + ".svg"), svg_document(icon, style, "hex"))
        gen_index(icons, out, framework, ext)
        gen_package_json(src, style, out, framework, ext, name)
        write(os.path.join(out, "icons.css"), build_css(style))
        write(os.path.join(out, "sprite.svg"), '<svg xmlns="http://www.w3.org/2000/svg" style="display:none">%s</svg>\n'
              % "".join(build_sprite(icons, style)))
        write(os.path.join(out, "manifest.json"), json.dumps({
            "name": name, "style": style.get("name"), "framework": framework, "grid": style["grid"],
            "icons": [{"name": i["name"], "label": i["label"], "group": i["group"], "tags": i.get("tags", []),
                       "component": component_name(i["name"])} for i in icons]}, indent=2, ensure_ascii=False) + "\n")
        write(os.path.join(out, "catalog.html"), build_catalog(src, style, icons, args.compare))
        write(os.path.join(out, "README.md"), build_readme(src, style, icons, framework, name))
        print("built %d icon(s) (%s) into %s" % (len(targets), framework, out))
        print("catalog: %s" % os.path.join(out, "catalog.html"))
        return 0
    except (SourceError, KeyError, ValueError, OSError) as exc:
        print("error: %s" % exc, file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())