返回 CodeWhale
export-design-tokens.py
根目录 / scripts / export-design-tokens.py
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
5 website's colors, type roles, spacing, radii, motion, easing, elevation,
6 breakpoints and focus geometry; `web/app/styles/tokens-roles.css` names the
7 site's roles over them (web/docs/BRAND_COLOR_MAPPING.md). The portable artifact's
8 own generator checks its digest before exporting. Update the entire vendored
9 folder from the app's design package; never edit its JSON here.
10
11 `crates/palette/src/rgb.rs` still owns the terminal's WHALE, LIGHT and
12 SHORELINE presets. They remain available to terminal-specific illustrations;
13 the public site's GPUI aliases no longer copy the Rust palette's mirrors.
14
15 Target: <repo>/web/app/tokens.css. This script writes nothing outside this
16 repository.
17
18 Usage:
19 scripts/export-design-tokens.py # write
20 scripts/export-design-tokens.py --check # exit 1 if any target is stale
21 """
22
23 from __future__ import annotations
24
25 import argparse
26 import hashlib
27 import json
28 import re
29 import subprocess
30 import sys
31 from pathlib import Path
32
33 REPO = Path(__file__).resolve().parent.parent
34 TOKENS_RS = REPO / "crates/palette/src/rgb.rs"
35 SOURCE_LABEL = "crates/palette/src/rgb.rs + vendor/codewhale-design/tokens.json"
36 GPUI_DIR = REPO / "vendor/codewhale-design"
37
38 CONST_RE = re.compile(
39 r"^pub const ((?:SHORELINE_LIGHT|SHORELINE|WHALE|LIGHT)_[A-Z0-9_]+)_RGB: \(u8, u8, u8\) = "
40 r"(?:\((\d+), (\d+), (\d+)\)|((?:SHORELINE_LIGHT|SHORELINE|WHALE|LIGHT)_[A-Z0-9_]+)_RGB);",
41 re.MULTILINE,
42 )
43
44
45 def parse_tokens(text: str) -> list[tuple[str, tuple[int, int, int] | str]]:
46 """Return [(NAME, (r, g, b) | alias-NAME)] in source order."""
47 tokens: list[tuple[str, tuple[int, int, int] | str]] = []
48 known: set[str] = set()
49 for m in CONST_RE.finditer(text):
50 name = m.group(1)
51 if m.group(5) is not None:
52 target = m.group(5)
53 if target not in known:
54 raise SystemExit(f"{name} aliases unknown token {target}")
55 tokens.append((name, target))
56 else:
57 tokens.append((name, (int(m.group(2)), int(m.group(3)), int(m.group(4)))))
58 known.add(name)
59 if not tokens:
60 raise SystemExit(f"no palette RGB consts found in {TOKENS_RS}")
61 return tokens
62
63
64 def css_name(name: str) -> str:
65 """Keep the website's existing names while replacing their source."""
66 if name.startswith("GPUI_LIGHT_"):
67 return "--gpui-light-" + name.removeprefix("GPUI_LIGHT_").lower().replace("_", "-")
68 if name.startswith("GPUI_"):
69 return "--gpui-dark-" + name.removeprefix("GPUI_").lower().replace("_", "-")
70 if name.startswith("SHORELINE_LIGHT_"):
71 return "--shoreline-light-" + name.removeprefix("SHORELINE_LIGHT_").lower().replace(
72 "_", "-"
73 )
74 if name.startswith("SHORELINE_"):
75 return "--shoreline-" + name.removeprefix("SHORELINE_").lower().replace("_", "-")
76 if name.startswith("LIGHT_"):
77 return "--light-" + name.removeprefix("LIGHT_").lower().replace("_", "-")
78 return "--whale-" + name.removeprefix("WHALE_").lower().replace("_", "-")
79
80
81 def render_css(tokens) -> str:
82 lines = [
83 f"/* generated from {SOURCE_LABEL} — do not edit */",
84 "/* regenerate: scripts/export-design-tokens.py (in the codewhale repo) */",
85 ":root {",
86 ]
87 for name, value in tokens:
88 prop = css_name(name)
89 if isinstance(value, str):
90 ref = css_name(value)
91 lines.append(f" {prop}: var({ref});")
92 lines.append(f" {prop}-rgb: var({ref}-rgb);")
93 else:
94 r, g, b = value
95 lines.append(f" {prop}: #{r:02x}{g:02x}{b:02x};")
96 lines.append(f" {prop}-rgb: {r} {g} {b};")
97 lines.append("}")
98 return "\n".join(lines) + "\n"
99
100
101 def gpui_tokens(data):
102 aliases = {
103 "BG": "background", "TEXT": "foreground", "PANEL": "surface",
104 "TEXT_MUTED": "muted_foreground", "SUBAGENT": "subagent", "BORDER": "border", "SIDEBAR": "sidebar",
105 "PRIMARY": "primary", "ON_PRIMARY": "primary_foreground", "ACCENT": "accent",
106 "HOVER": "hover", "LIST_ACTIVE": "selected", "ATTENTION": "attention", "LIVE": "live",
107 "LIVE_PEAK": "live_peak", "DANGER": "danger", "BORDER_STRONG": "border_strong",
108 "OCEAN_DEPTH": "ocean_depth", "DIFF_ADD": "diff_add", "DIFF_REMOVE": "diff_remove",
109 }
110 return [
111 (f"{prefix}_{name}", tuple(bytes.fromhex(palette[key])))
112 for mode, prefix in [("dark", "GPUI"), ("light", "GPUI_LIGHT")]
113 for palette in [data["colors"][mode]]
114 for name, key in aliases.items()
115 ]
116
117
118 def gpui_geometry(data, digest):
119 lines = [f"/* GPUI design {data['version']}; sha256 {digest}. */", ":root {"]
120 for section in ["radius", "focus", "spacing"]:
121 for name, value in data[section].items():
122 lines.append(f" --gpui-{section}-{name}: {value}px;")
123 for name, value in data["size"].items():
124 lines.append(f" --gpui-size-{name.removesuffix('_px').replace('_', '-')}: {value}px;")
125 for name in ["selection_opacity", "primary_hover_opacity"]:
126 lines.append(f" --gpui-{name.replace('_', '-')}: {data[name]};")
127 for role, spec in data["type_roles"].items():
128 lines += [f" --gpui-type-{role}-size: {spec['size_px'] / 16:g}rem;",
129 f" --gpui-type-{role}-line: {spec['line_px'] / spec['size_px']:.4g};",
130 f" --gpui-type-{role}-weight: {spec['weight']};"]
131 for name, value in data["motion"].items():
132 if (name.startswith("duration_") or name.startswith("loop_") or name in ("sweep_active_ms", "sweep_rest_ms", "sweep_delay_ms")) and name.endswith("_ms"):
133 lines.append(f" --gpui-motion-{name.removesuffix('_ms').replace('_', '-')}: {value}ms;")
134 elif name in ("breathe_min_alpha", "breathe_max_alpha"):
135 lines.append(f" --gpui-motion-{name.removesuffix('_alpha').replace('_', '-')}: {value:g};")
136 lines.append(f" --gpui-motion-arrive-rise: {data['motion']['arrive_rise_px']}px;")
137 for name, curve in data["easing"].items():
138 lines.append(f" --gpui-easing-{name}: cubic-bezier({', '.join(f'{v:g}' for v in curve)});")
139 e = data["elevation"]
140 for kind in ["popover", "dialog"]:
141 for mode in ["light", "dark"]:
142 lines.append(f" --gpui-elevation-{kind}-{mode}: 0 {e[kind + '_y_px']}px "
143 f"{e[kind + '_blur_px']}px rgb(0 0 0 / {e[kind + '_alpha_' + mode]:g});")
144 for name, value in data["breakpoints"].items():
145 lines.append(f" --gpui-breakpoint-{name.removesuffix('_px')}: {value}px;")
146 for mode, stops in data["water"].items():
147 ramp = ", ".join(f"#{stop['color']} {stop['at']}%" for stop in stops)
148 lines.append(f" --gpui-water-{mode}: linear-gradient(180deg, {ramp});")
149 for mode, light in data["surface_light"].items():
150 stops = ", ".join(
151 f"rgb({' '.join(str(v) for v in bytes.fromhex(stop['color']['hex']))} / {stop['color']['alpha']:g}) {stop['at']}%"
152 for stop in light["stops"])
153 lines.append(f" --gpui-surface-light-{mode}: radial-gradient(ellipse at {light['x']}% {light['y']}%, {stops});")
154 rise, deep = data["ombre"]["rise"], data["ombre"]["deep"]
155 lines.append(f" --gpui-ombre: linear-gradient(135deg, #{rise}, #{deep});")
156 fallbacks = ", ".join(json.dumps(v) for v in data["typography"]["fallbacks"])
157 lines += [f" --gpui-font-fallbacks: {fallbacks};",
158 f" --gpui-mono-size: {data['typography']['mono_px'] / 16:g}rem;", "}"]
159 return "\n".join(lines) + "\n"
160
161
162 def main() -> int:
163 ap = argparse.ArgumentParser(description=__doc__)
164 ap.add_argument("--check", action="store_true", help="verify instead of write")
165 args = ap.parse_args()
166
167 subprocess.run([sys.executable, str(GPUI_DIR / "generate.py"), "--check"], check=True)
168 source = (GPUI_DIR / "tokens.json").read_bytes()
169 data = json.loads(source)
170 tokens = parse_tokens(TOKENS_RS.read_text(encoding="utf-8")) + gpui_tokens(data)
171 css = render_css(tokens) + gpui_geometry(data, hashlib.sha256(source).hexdigest())
172
173 targets: list[tuple[Path, str]] = [(REPO / "web/app/tokens.css", css)]
174
175 stale = []
176 for path, content in targets:
177 current = path.read_text(encoding="utf-8") if path.exists() else None
178 if current == content:
179 continue
180 if args.check:
181 stale.append(path)
182 else:
183 path.parent.mkdir(parents=True, exist_ok=True)
184 path.write_text(content, encoding="utf-8")
185 print(f"wrote {path}")
186
187 if stale:
188 for path in stale:
189 print(f"stale: {path}", file=sys.stderr)
190 print(
191 "run scripts/export-design-tokens.py to regenerate from "
192 f"{SOURCE_LABEL}",
193 file=sys.stderr,
194 )
195 return 1
196 if args.check:
197 print(f"design tokens up to date ({len(targets)} file(s), {len(tokens)} tokens)")
198 return 0
199
200
201 if __name__ == "__main__":
202 sys.exit(main())
203
203 lines PYTHON