| 1 | #!/usr/bin/env python3 |
| 2 | """Export the Codewhale palettes to the other Codewhale clients. |
| 3 | |
| 4 | The versioned `vendor/codewhale-design/tokens.json` snapshot owns the GPUI |
| 5 | colors, radii, typography fallbacks and focus geometry. The adapter preserves |
| 6 | this site's existing light/OS-dark/pinned-dark roles. The portable artifact's |
| 7 | own generator checks its digest before exporting. Update the entire vendored |
| 8 | folder from the app's design package; never edit its JSON here. |
| 9 | |
| 10 | `crates/palette/src/rgb.rs` still owns the terminal's WHALE, LIGHT and |
| 11 | SHORELINE presets. They remain available to terminal-specific illustrations; |
| 12 | the public site's GPUI aliases no longer copy the Rust palette's mirrors. |
| 13 | |
| 14 | Target: <repo>/web/app/tokens.css. This script writes nothing outside this |
| 15 | repository. |
| 16 | |
| 17 | Usage: |
| 18 | scripts/export-design-tokens.py # write |
| 19 | scripts/export-design-tokens.py --check # exit 1 if any target is stale |
| 20 | """ |
| 21 | |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import argparse |
| 25 | import hashlib |
| 26 | import json |
| 27 | import re |
| 28 | import subprocess |
| 29 | import sys |
| 30 | from pathlib import Path |
| 31 | |
| 32 | REPO = Path(__file__).resolve().parent.parent |
| 33 | TOKENS_RS = REPO / "crates/palette/src/rgb.rs" |
| 34 | SOURCE_LABEL = "crates/palette/src/rgb.rs + vendor/codewhale-design/tokens.json" |
| 35 | GPUI_DIR = REPO / "vendor/codewhale-design" |
| 36 | |
| 37 | CONST_RE = re.compile( |
| 38 | r"^pub const ((?:SHORELINE_LIGHT|SHORELINE|WHALE|LIGHT)_[A-Z0-9_]+)_RGB: \(u8, u8, u8\) = " |
| 39 | r"(?:\((\d+), (\d+), (\d+)\)|((?:SHORELINE_LIGHT|SHORELINE|WHALE|LIGHT)_[A-Z0-9_]+)_RGB);", |
| 40 | re.MULTILINE, |
| 41 | ) |
| 42 | |
| 43 | |
| 44 | def parse_tokens(text: str) -> list[tuple[str, tuple[int, int, int] | str]]: |
| 45 | """Return [(NAME, (r, g, b) | alias-NAME)] in source order.""" |
| 46 | tokens: list[tuple[str, tuple[int, int, int] | str]] = [] |
| 47 | known: set[str] = set() |
| 48 | for m in CONST_RE.finditer(text): |
| 49 | name = m.group(1) |
| 50 | if m.group(5) is not None: |
| 51 | target = m.group(5) |
| 52 | if target not in known: |
| 53 | raise SystemExit(f"{name} aliases unknown token {target}") |
| 54 | tokens.append((name, target)) |
| 55 | else: |
| 56 | tokens.append((name, (int(m.group(2)), int(m.group(3)), int(m.group(4))))) |
| 57 | known.add(name) |
| 58 | if not tokens: |
| 59 | raise SystemExit(f"no palette RGB consts found in {TOKENS_RS}") |
| 60 | return tokens |
| 61 | |
| 62 | |
| 63 | def css_name(name: str) -> str: |
| 64 | """Keep the website's existing names while replacing their source.""" |
| 65 | if name.startswith("GPUI_LIGHT_"): |
| 66 | return "--gpui-light-" + name.removeprefix("GPUI_LIGHT_").lower().replace("_", "-") |
| 67 | if name.startswith("GPUI_"): |
| 68 | return "--gpui-dark-" + name.removeprefix("GPUI_").lower().replace("_", "-") |
| 69 | if name.startswith("SHORELINE_LIGHT_"): |
| 70 | return "--shoreline-light-" + name.removeprefix("SHORELINE_LIGHT_").lower().replace( |
| 71 | "_", "-" |
| 72 | ) |
| 73 | if name.startswith("SHORELINE_"): |
| 74 | return "--shoreline-" + name.removeprefix("SHORELINE_").lower().replace("_", "-") |
| 75 | if name.startswith("LIGHT_"): |
| 76 | return "--light-" + name.removeprefix("LIGHT_").lower().replace("_", "-") |
| 77 | return "--whale-" + name.removeprefix("WHALE_").lower().replace("_", "-") |
| 78 | |
| 79 | |
| 80 | def render_css(tokens) -> str: |
| 81 | lines = [ |
| 82 | f"/* generated from {SOURCE_LABEL} — do not edit */", |
| 83 | "/* regenerate: scripts/export-design-tokens.py (in the codewhale repo) */", |
| 84 | ":root {", |
| 85 | ] |
| 86 | for name, value in tokens: |
| 87 | prop = css_name(name) |
| 88 | if isinstance(value, str): |
| 89 | ref = css_name(value) |
| 90 | lines.append(f" {prop}: var({ref});") |
| 91 | lines.append(f" {prop}-rgb: var({ref}-rgb);") |
| 92 | else: |
| 93 | r, g, b = value |
| 94 | lines.append(f" {prop}: #{r:02x}{g:02x}{b:02x};") |
| 95 | lines.append(f" {prop}-rgb: {r} {g} {b};") |
| 96 | lines.append("}") |
| 97 | return "\n".join(lines) + "\n" |
| 98 | |
| 99 | |
| 100 | def gpui_tokens(data): |
| 101 | aliases = { |
| 102 | "BG": "background", "TEXT": "foreground", "PANEL": "surface", |
| 103 | "TEXT_MUTED": "muted_foreground", "BORDER": "border", "SIDEBAR": "sidebar", |
| 104 | "PRIMARY": "primary", "ON_PRIMARY": "primary_foreground", "ACCENT": "hover", |
| 105 | "LIST_ACTIVE": "selected", "ATTENTION": "attention", "LIVE": "live", |
| 106 | "DANGER": "danger", "BORDER_STRONG": "border_strong", |
| 107 | } |
| 108 | return [ |
| 109 | (f"{prefix}_{name}", tuple(bytes.fromhex(palette[key]))) |
| 110 | for mode, prefix in [("dark", "GPUI"), ("light", "GPUI_LIGHT")] |
| 111 | for palette in [data["colors"][mode]] |
| 112 | for name, key in aliases.items() |
| 113 | ] |
| 114 | |
| 115 | |
| 116 | def gpui_geometry(data, digest): |
| 117 | lines = [f"/* GPUI design {data['version']}; sha256 {digest}. */", ":root {"] |
| 118 | for section in ["radius", "focus", "spacing"]: |
| 119 | for name, value in data[section].items(): |
| 120 | lines.append(f" --gpui-{section}-{name}: {value}px;") |
| 121 | for name in ["selection_opacity", "primary_hover_opacity"]: |
| 122 | lines.append(f" --gpui-{name.replace('_', '-')}: {data[name]};") |
| 123 | fallbacks = ", ".join(json.dumps(v) for v in data["typography"]["fallbacks"]) |
| 124 | lines += [f" --gpui-font-fallbacks: {fallbacks};", |
| 125 | f" --gpui-mono-size: {data['typography']['mono_px'] / 16:g}rem;", "}"] |
| 126 | return "\n".join(lines) + "\n" |
| 127 | |
| 128 | |
| 129 | def main() -> int: |
| 130 | ap = argparse.ArgumentParser(description=__doc__) |
| 131 | ap.add_argument("--check", action="store_true", help="verify instead of write") |
| 132 | args = ap.parse_args() |
| 133 | |
| 134 | subprocess.run([sys.executable, str(GPUI_DIR / "generate.py"), "--check"], check=True) |
| 135 | source = (GPUI_DIR / "tokens.json").read_bytes() |
| 136 | data = json.loads(source) |
| 137 | tokens = parse_tokens(TOKENS_RS.read_text(encoding="utf-8")) + gpui_tokens(data) |
| 138 | css = render_css(tokens) + gpui_geometry(data, hashlib.sha256(source).hexdigest()) |
| 139 | |
| 140 | targets: list[tuple[Path, str]] = [(REPO / "web/app/tokens.css", css)] |
| 141 | |
| 142 | stale = [] |
| 143 | for path, content in targets: |
| 144 | current = path.read_text(encoding="utf-8") if path.exists() else None |
| 145 | if current == content: |
| 146 | continue |
| 147 | if args.check: |
| 148 | stale.append(path) |
| 149 | else: |
| 150 | path.parent.mkdir(parents=True, exist_ok=True) |
| 151 | path.write_text(content, encoding="utf-8") |
| 152 | print(f"wrote {path}") |
| 153 | |
| 154 | if stale: |
| 155 | for path in stale: |
| 156 | print(f"stale: {path}", file=sys.stderr) |
| 157 | print( |
| 158 | "run scripts/export-design-tokens.py to regenerate from " |
| 159 | f"{SOURCE_LABEL}", |
| 160 | file=sys.stderr, |
| 161 | ) |
| 162 | return 1 |
| 163 | if args.check: |
| 164 | print(f"design tokens up to date ({len(targets)} file(s), {len(tokens)} tokens)") |
| 165 | return 0 |
| 166 | |
| 167 | |
| 168 | if __name__ == "__main__": |
| 169 | sys.exit(main()) |
| 170 |