返回 CodeWhale
generate.py
根目录 / vendor / codewhale-design / generate.py
1 #!/usr/bin/env python3
2 """Generate the portable Codewhale design artifact. No sibling checkout is needed.
3 Edit tokens.json only in the codewhale-design repository. Consumers vendor the whole folder.
4 """
5 import argparse
6 import hashlib
7 import json
8 from pathlib import Path
9
10 ROOT = Path(__file__).resolve().parent
11 HERE = ROOT
12
13 # WCAG 2.x contrast every palette must hold, in both modes, before anything is
14 # generated: text roles at 4.5:1 and control edges at 3:1 on each ground a
15 # role can sit on, including a hovered or selected row and the deepest point
16 # of the ocean field behind the working area, and the added and removed rows
17 # of a diff, which carry code and their +/− marks.
18 GROUNDS = ["background", "surface", "sidebar", "hover", "selected", "ocean_depth", "diff_add", "diff_remove"]
19 # `primary` is a fill only; its text is `primary_foreground`, checked in FILLED.
20 TEXT = ["foreground", "muted_foreground", "subagent", "accent", "live", "live_peak", "attention", "danger"]
21 # Secondary text carries labels, metadata and status words people must read at
22 # small sizes, so it holds 5.5:1 on every ground, above the AA floor.
23 TEXT_FLOORS = {"muted_foreground": 5.5}
24 EDGES = ["border_strong"]
25 # Disabled labels and icons stay readable while reading as off: a solid ink
26 # at the 3:1 floor of a user-interface component, never an opacity.
27 QUIET = ["disabled"]
28 FILLED = [("primary_foreground", "primary")]
29 # The ombre's deep stop can carry body text on the dark ground; both stops
30 # carry `primary_foreground` on the primary action in either mode.
31 OMBRE_TEXT = [("foreground", "deep", 4.5)]
32 LEVELS = ["clear", "frosted", "solid"]
33 HEX = "0123456789abcdef"
34
35 def color(value, name):
36 """A token colour is a solid hex string or {"hex", "alpha"}; returns (hex, alpha)."""
37 hex6, alpha = (value, 1) if isinstance(value, str) else (value.get("hex"), value.get("alpha"))
38 if not (isinstance(hex6, str) and len(hex6) == 6 and all(c in HEX for c in hex6)):
39 raise ValueError(f"{name} must be six lowercase hex digits")
40 if isinstance(alpha, bool) or not isinstance(alpha, (int, float)) or not 0 <= alpha <= 1:
41 raise ValueError(f"{name} alpha must be a number between 0 and 1")
42 return hex6, alpha
43
44 def over(value, ground, name="colour"):
45 hex6, alpha = color(value, name)
46 top = [int(hex6[i:i + 2], 16) for i in (0, 2, 4)]
47 under = [int(ground[i:i + 2], 16) for i in (0, 2, 4)]
48 return "".join(f"{round(alpha * t + (1 - alpha) * u):02x}" for t, u in zip(top, under))
49
50 def css_color(value, name):
51 hex6, alpha = color(value, name)
52 if alpha == 1:
53 return f"#{hex6}"
54 r, g, b = (int(hex6[i:i + 2], 16) for i in (0, 2, 4))
55 return f"rgb({r} {g} {b} / {alpha})"
56
57 def luminance(hex6):
58 channels = [int(hex6[i:i + 2], 16) / 255 for i in (0, 2, 4)]
59 channels = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels]
60 return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
61
62 def contrast(a, b):
63 hi, lo = sorted([luminance(a), luminance(b)], reverse=True)
64 return (hi + 0.05) / (lo + 0.05)
65
66 def composited_grounds(data, mode):
67 """Every glass and sheet fill over each water stop and the surface-light peak,
68 and every card fill over the sheet and each Glass level: the real grounds text sits on."""
69 water = {f"water {s['at']}%": color(s["color"], f"water.{mode}")[0] for s in data["water"][mode]}
70 first = data["water"][mode][0]["color"]
71 water["surface-light peak"] = over(data["surface_light"][mode]["stops"][0]["color"], first, f"surface_light.{mode}")
72 grounds = {}
73 for under_name, under in water.items():
74 if under_name != "surface-light peak":
75 grounds[under_name] = under
76 for level in LEVELS:
77 grounds[f"{level} glass over {under_name}"] = over(data["glass"][mode][level]["fill"], under, f"glass.{mode}.{level}")
78 grounds[f"sheet over {under_name}"] = over(data["sheet"][mode]["fill"], under, f"sheet.{mode}")
79 for name, ground in list(grounds.items()):
80 if " over " not in name:
81 continue
82 grounds[f"card on {name}"] = over(data["card"][mode]["fill"], ground, f"card.{mode}")
83 for surf in ["change_bar", "subagent_tag", "workbar"]:
84 grounds[f"{surf} on {name}"] = over(data[surf][mode]["fill"], ground, f"{surf}.{mode}")
85 for tint_key, role in [("accent_fill", "accent"), ("live_fill", "live"), ("attention_fill", "attention"),
86 ("danger_fill", "danger"), ("count_fill", "foreground")]:
87 tint_val = {"hex": data["colors"][mode][role], "alpha": data["tint"][tint_key]}
88 for under_name in water:
89 for base_name in [f"frosted glass over {under_name}", f"solid glass over {under_name}", f"sheet over {under_name}"]:
90 grounds[f"tint.{tint_key} on {base_name}"] = over(tint_val, grounds[base_name], f"tint.{tint_key}")
91 return grounds
92
93 def contrast_violations(data):
94 colors, ombre = data["colors"], data["ombre"]
95 pairs = [(fg, bg, TEXT_FLOORS.get(fg, 4.5)) for fg in TEXT for bg in GROUNDS]
96 pairs += [(edge, bg, 3.0) for edge in EDGES for bg in GROUNDS]
97 pairs += [(quiet, bg, 3.0) for quiet in QUIET for bg in GROUNDS]
98 pairs += [(fg, bg, 4.5) for fg, bg in FILLED]
99 found = []
100 for mode, palette in colors.items():
101 for fg, bg, floor in pairs:
102 ratio = contrast(palette[fg], palette[bg])
103 if ratio < floor:
104 found.append(f"{mode} {fg} on {bg} is {ratio:.2f}:1, needs {floor}:1")
105 for stop, value in ombre.items():
106 ratio = contrast(palette["primary_foreground"], value)
107 if ratio < 4.5:
108 found.append(f"{mode} primary_foreground on ombre {stop} is {ratio:.2f}:1, needs 4.5:1")
109 for ground_name, ground in composited_grounds(data, mode).items():
110 for fg in TEXT + QUIET + EDGES:
111 floor = 3.0 if fg in QUIET or fg in EDGES else TEXT_FLOORS.get(fg, 4.5)
112 ratio = contrast(palette[fg], ground)
113 if ratio < floor:
114 found.append(f"{mode} {fg} on {ground_name} is {ratio:.2f}:1, needs {floor}:1")
115 for fg, stop, floor in OMBRE_TEXT:
116 ratio = contrast(colors["dark"][fg], ombre[stop])
117 if ratio < floor:
118 found.append(f"dark {fg} on ombre {stop} is {ratio:.2f}:1, needs {floor}:1")
119 return found
120
121 def check_solid_roles(data):
122 """colors.* keep solid hex: each translucent v5 value is stored as its result over `background`."""
123 for mode, palette in data["colors"].items():
124 ground = palette["background"]
125 if ground != data["water"][mode][-1]["color"]:
126 raise ValueError(f"colors.{mode}.background must be the bottom water stop")
127 for role, value in [("surface", data["sheet"][mode]["fill"]), ("sidebar", data["glass"][mode]["frosted"]["fill"])]:
128 if palette[role] != over(value, ground):
129 raise ValueError(f"colors.{mode}.{role} must be {over(value, ground)}, its fill over background")
130
131 FILL_, EDGE_ = ["FRAME_FILL", "SHAPE_FILL"], ["STROKE_COLOR"]
132 TINT_SOURCES = {"accent_fill": "var(--accent)", "accent_border": "var(--accent)",
133 "live_fill": "var(--live)", "live_border": "var(--live)",
134 "attention_fill": "var(--attention)", "attention_border": "var(--attention)",
135 "danger_fill": "var(--danger)", "danger_border": "var(--danger)",
136 "count_fill": "var(--text)", "scrim": "var(--surface)", "on_primary_border": "currentColor"}
137 TINT_FIGMA = {"accent_fill": ("effort/fill", "accent", FILL_), "accent_border": ("chip/accent-border", "accent", EDGE_),
138 "live_fill": ("tint/live-fill", "live", FILL_), "live_border": ("tint/live-border", "live", EDGE_),
139 "attention_fill": ("tint/attention-fill", "attention", FILL_), "attention_border": ("tint/attention-border", "attention", EDGE_),
140 "danger_fill": ("tint/danger-fill", "danger", FILL_), "danger_border": ("tint/danger-border", "danger", EDGE_),
141 "count_fill": ("count/fill", "foreground", FILL_),
142 "scrim": ("tint/scrim", "background", FILL_), "on_primary_border": ("kbd/on-primary-border", "primary_foreground", EDGE_)}
143 WEIGHT_STYLE = {400: "Regular", 500: "Medium", 550: "SemiBold", 600: "SemiBold", 700: "Bold"}
144 FILL, INK, EDGE = ["FRAME_FILL", "SHAPE_FILL"], ["SHAPE_FILL", "TEXT_FILL", "STROKE_COLOR"], ["STROKE_COLOR"]
145 FIGMA_SCOPES = {"text": INK, "muted": INK, "subagent": INK, "disabled": INK, "accent": FILL + ["TEXT_FILL", "STROKE_COLOR"], "button-text": INK,
146 "live": INK, "live-peak": INK, "attention": INK, "danger": INK, "line": FILL + EDGE, "border-strong": EDGE}
147
148 def figma_payload(data, aliases):
149 modes = list(data["colors"])
150 def both(get):
151 return {mode.capitalize(): dict(zip(["hex", "alpha"], color(get(mode), "figma"))) for mode in modes}
152 colors = [{"name": alias, "type": "COLOR", "scopes": FIGMA_SCOPES.get(alias, FILL), "web": f"var(--{alias})",
153 "values": both(lambda mode, key=key: data["colors"][mode][key])} for alias, key in aliases.items()]
154 for group in ["card", "sheet", "change_bar", "subagent_tag", "workbar"]:
155 slug = group.replace("_", "-")
156 for part in data[group][modes[0]]:
157 colors.append({"name": f"{slug}/{part}", "type": "COLOR", "scopes": FILL if part in ("fill", "track") else EDGE,
158 "web": f"var(--{slug}-{part})", "values": both(lambda mode, g=group, p=part: data[g][mode][p])})
159 for level in LEVELS:
160 colors.append({"name": f"glass/{level}-fill", "type": "COLOR", "scopes": FILL, "web": f"var(--glass-{level}-fill)",
161 "values": both(lambda mode, l=level: data["glass"][mode][l]["fill"])})
162 for part in ["border", "highlight"]:
163 colors.append({"name": f"glass/{part}", "type": "COLOR", "scopes": EDGE, "web": f"var(--glass-{part})",
164 "values": both(lambda mode, p=part: data["glass"][mode][p])})
165 for name, value in data["ombre"].items():
166 colors.append({"name": f"ombre/{name}", "type": "COLOR", "scopes": FILL, "web": f"var(--ombre-{name})",
167 "values": both(lambda mode, v=value: v)})
168 for index, stop in enumerate(["top", "upper", "lower", "bottom"]):
169 if all(len(data["water"][mode]) == 4 for mode in modes):
170 colors.append({"name": f"water/{stop}", "type": "COLOR", "scopes": ["FRAME_FILL"], "web": f"var(--water) · {stop} stop",
171 "values": both(lambda mode, i=index: data["water"][mode][i]["color"])})
172 for index, stop in enumerate(["peak", "mid", "edge"]):
173 if all(len(data["surface_light"][mode]["stops"]) == 3 for mode in modes):
174 colors.append({"name": f"surface-light/{stop}", "type": "COLOR", "scopes": ["FRAME_FILL"], "web": f"var(--surface-light) · {stop} stop",
175 "values": both(lambda mode, i=index: data["surface_light"][mode]["stops"][i]["color"])})
176 for layer in ["popover", "dialog"]:
177 colors.append({"name": f"shadow/{layer}", "type": "COLOR", "scopes": ["EFFECT_COLOR"], "web": f"var(--elevation-{layer})",
178 "values": both(lambda mode, l=layer: {"hex": "000000", "alpha": data["elevation"][f"{l}_alpha_{mode}"]})})
179 for name, (figma_name, role, scopes) in TINT_FIGMA.items():
180 web = f"var(--tint-{name.replace('_', '-')})"
181 colors.append({"name": figma_name, "type": "COLOR", "scopes": scopes, "web": web,
182 "values": both(lambda mode, r=role, n=name: {"hex": data["colors"][mode][r], "alpha": data["tint"][n]})})
183 whale = json.loads((HERE / "whale" / "source" / "spec.json").read_text())["palette"]
184 for figma_name, pick in [("whale/rise", lambda p: p["body"][0]), ("whale/deep", lambda p: p["body"][1]),
185 ("whale/pouch", lambda p: p["throat"]), ("whale/eye", lambda p: p["eye"])]:
186 colors.append({"name": figma_name, "type": "COLOR", "scopes": FILL, "web": "whale/source/spec.json palette",
187 "values": both(lambda mode, f=pick: f(whale[mode])[1:])})
188 metric = lambda name, value, scopes, web: {"name": name, "type": "FLOAT", "scopes": scopes, "web": web, "values": {"Value": value}}
189 metrics = [metric(f"spacing/{name}", value, ["GAP"], f"var(--spacing-{name})") for name, value in data["spacing"].items()]
190 metrics += [metric(f"radius/{name}", value, ["CORNER_RADIUS"], f"var(--radius-{name})") for name, value in data["radius"].items()]
191 metrics += [metric(f"size/{name[:-3].replace('_', '-')}", value, ["WIDTH_HEIGHT"], f"var(--size-{name[:-3].replace('_', '-')})")
192 for name, value in data["size"].items()]
193 metrics += [metric(f"focus/{name}", value, ["STROKE_FLOAT"] if name == "width" else ["GAP"], f"var(--focus-{name})")
194 for name, value in data["focus"].items()]
195 styles = []
196 for name, role in data["type_roles"].items():
197 if role["weight"] not in WEIGHT_STYLE:
198 raise ValueError(f"type_roles.{name} weight {role['weight']} has no Figma font style")
199 styles.append({"name": f"CW 5/{name.capitalize()}", "family": "Geist Mono" if name == "code" else "Geist",
200 "style": WEIGHT_STYLE[role["weight"]], "size": role["size_px"], "line": role["line_px"]})
201 return {"version": data["version"], "textStyles": styles, "collections": [
202 {"name": "CW 5 · Color", "modes": [mode.capitalize() for mode in modes], "variables": colors},
203 {"name": "CW 5 · Metrics", "modes": ["Value"], "variables": metrics}]}
204
205 def dtcg(data):
206 def hexa(value):
207 hex6, alpha = color(value, "dtcg")
208 return f"#{hex6}" if alpha == 1 else f"#{hex6}{round(alpha * 255):02x}"
209 px = lambda group: {name: {"$value": f"{value}px"} for name, value in data[group].items()}
210 out = {"$description": f"Codewhale design {data['version']}. Generated from tokens.json; do not edit.",
211 "color": {mode: {"$type": "color", **{role: {"$value": f"#{value}"} for role, value in palette.items()}}
212 for mode, palette in data["colors"].items()},
213 "ombre": {"$type": "color", **{name: {"$value": f"#{value}"} for name, value in data["ombre"].items()}},
214 "spacing": {"$type": "dimension", **px("spacing")}, "radius": {"$type": "dimension", **px("radius")},
215 "size": {"$type": "dimension", **{name[:-3]: {"$value": f"{value}px"} for name, value in data["size"].items()}},
216 "duration": {"$type": "duration", **{name[9:-3]: {"$value": f"{value}ms"} for name, value in data["motion"].items()
217 if name.startswith("duration_")}},
218 "easing": {"$type": "cubicBezier", **{name: {"$value": curve} for name, curve in data["easing"].items()}},
219 "type": {"$type": "typography", **{name: {"$value": {
220 "fontFamily": data["typography"]["mono_family" if name == "code" else "family"], "fontSize": f"{role['size_px']}px",
221 "lineHeight": round(role["line_px"] / role["size_px"], 4), "fontWeight": role["weight"]}}
222 for name, role in data["type_roles"].items()}}}
223 for group in ["glass", "sheet", "card", "change_bar", "subagent_tag", "workbar"]:
224 out[group] = {"$type": "color"}
225 for mode, parts in data[group].items():
226 out[group][mode] = {part: {"$value": hexa(value["fill"] if isinstance(value, dict) and "fill" in value else value)}
227 for part, value in parts.items()}
228 return out
229
230 def render():
231 source = (ROOT / "tokens.json").read_bytes()
232 data = json.loads(source)
233 unit = {name: data[name] for name in ["selection_opacity", "primary_hover_opacity"]}
234 unit |= {f"glow.{name}": v for name, v in data["glow"].items() if name.endswith("_alpha")}
235 unit |= {f"tint.{name}": v for name, v in data["tint"].items()}
236 unit |= {f"elevation.{name}": v for name, v in data["elevation"].items() if "_alpha" in name}
237 for name, value in unit.items():
238 if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 <= value <= 1:
239 raise ValueError(f"{name} must be a number between 0 and 1")
240 # No overshoot or undershoot: a curve's x and y control points stay in [0, 1].
241 for name, curve in data["easing"].items():
242 if len(curve) != 4 or not all(isinstance(v, (int, float)) and 0 <= v <= 1 for v in curve):
243 raise ValueError(f"easing.{name} must be four control points between 0 and 1")
244 stream = data["stream"]
245 if not all(isinstance(v, int) and v > 0 for v in stream.values()) or stream["reveal_first_ms"] > stream["reveal_lag_ms"]:
246 raise ValueError("stream values must be positive integers, with reveal_first_ms no longer than reveal_lag_ms")
247 digest = hashlib.sha256(source).hexdigest()
248 header = f"Generated from Codewhale design {data['version']}; sha256 {digest}. Do not edit."
249 keys = list(data["colors"]["dark"])
250 assert set(keys) == set(data["colors"]["light"])
251 for palette in [*data["colors"].values(), data["ombre"]]:
252 assert all(len(v) == 6 and all(c in HEX for c in v) for v in palette.values())
253 modes = list(data["colors"])
254 for group in ["water", "surface_light", "glass", "sheet", "card", "change_bar", "subagent_tag", "workbar"]:
255 if set(data[group]) != set(modes):
256 raise ValueError(f"{group} needs exactly the modes {', '.join(modes)}")
257 for mode in modes:
258 stops = data["water"][mode]
259 if not stops or [s["at"] for s in stops] != sorted(s["at"] for s in stops):
260 raise ValueError(f"water.{mode} needs stops in order")
261 if set(data["glass"][mode]) != {"border", "highlight", *LEVELS}:
262 raise ValueError(f"glass.{mode} needs border, highlight, {', '.join(LEVELS)}")
263 check_solid_roles(data)
264 violations = contrast_violations(data)
265 if violations:
266 raise ValueError("Contrast below WCAG AA:\n " + "\n ".join(violations))
267
268 def rust_color(prefix, value, name):
269 hex6, alpha = color(value, name)
270 return [f"pub const {prefix}: u32 = 0x{hex6};", f"pub const {prefix}_ALPHA: f32 = {float(alpha)};"]
271
272 rust = [f"// {header}", "#![allow(dead_code)]", "", f'pub const VERSION: &str = "{data["version"]}";',
273 "#[derive(Clone, Copy, Debug)]", "pub struct Colors {"]
274 rust += [f" pub {k}: u32," for k in keys]
275 rust += ["}"]
276 for name, palette in data["colors"].items():
277 rust += [f"pub const {name.upper()}: Colors = Colors {{"]
278 rust += [f" {k}: 0x{v}," for k, v in palette.items()]
279 rust += ["};"]
280 rust += ["pub fn colors(dark: bool) -> Colors {", " if dark { DARK } else { LIGHT }", "}"]
281 for mode in modes:
282 m = mode.upper()
283 for stop in data["water"][mode]:
284 rust += [f"pub const WATER_{m}_{stop['at']}: u32 = 0x{color(stop['color'], 'water')[0]};"]
285 for level in LEVELS:
286 glass = data["glass"][mode][level]
287 rust += rust_color(f"GLASS_{m}_{level.upper()}_FILL", glass["fill"], "glass")
288 rust += [f"pub const GLASS_{m}_{level.upper()}_BLUR_PX: f32 = {float(glass['blur_px'])};"]
289 for part in ["border", "highlight"]:
290 rust += rust_color(f"GLASS_{m}_{part.upper()}", data["glass"][mode][part], "glass")
291 for group in ["sheet", "card", "change_bar", "subagent_tag", "workbar"]:
292 for part, value in data[group][mode].items():
293 rust += rust_color(f"{group.upper()}_{m}_{part.upper()}", value, group)
294 rust += [f'pub const FONT_FAMILY: &str = "{data["typography"]["family"]}";',
295 f'pub const FONT_MONO_FAMILY: &str = "{data["typography"]["mono_family"]}";',
296 "pub const FONT_FALLBACKS: &[&str] = &["]
297 rust += [f" {json.dumps(v)}," for v in data["typography"]["fallbacks"]]
298 rust += ["];"]
299 for section in ["spacing", "radius", "focus", "icons", "motion", "stream", "glow", "elevation"]:
300 for name, value in data[section].items():
301 rust += [f"pub const {section.upper()}_{name.upper()}: f32 = {float(value)};"]
302 for name, curve in data["easing"].items():
303 rust += [f"pub const EASING_{name.upper()}: [f32; 4] = [{', '.join(str(float(v)) for v in curve)}];"]
304 for name, value in data["ombre"].items():
305 rust += [f"pub const OMBRE_{name.upper()}: u32 = 0x{value};"]
306 for name in ["selection_opacity", "primary_hover_opacity"]:
307 rust += [f"pub const {name.upper()}: f32 = {float(data[name])};"]
308 rust += [f'pub const MONO_PX: f32 = {float(data["typography"]["mono_px"])};']
309 roles = data["type_roles"]
310 for name, role in roles.items():
311 if not (isinstance(role["size_px"], (int, float)) and role["line_px"] >= role["size_px"] and role["weight"] in range(100, 1000)):
312 raise ValueError(f"type_roles.{name} needs size_px, a line_px no smaller than it, and a weight from 100 to 900")
313 for key in ["size_px", "line_px", "weight"]:
314 rust += [f"pub const TYPE_ROLE_{name.upper()}_{key.upper()}: f32 = {float(role[key])};"]
315 for section in ["size", "breakpoints"]:
316 for name, value in data[section].items():
317 rust += [f"pub const {section.upper()}_{name.upper()}: f32 = {float(value)};"]
318 if data["size"]["touch_target_px"] < 44:
319 raise ValueError("size.touch_target_px must be at least 44")
320 for name in ["body_px", "caption_px", "prose_px", "heading_px", "title_px"]:
321 if name in data["typography"]:
322 rust += [f'pub const TYPE_{name.upper()}: f32 = {float(data["typography"][name])};']
323 # Existing web names remain aliases, so every current component migrates together.
324 aliases = {"outside":"sidebar","surface":"background","panel":"surface","text":"foreground",
325 "muted":"muted_foreground","subagent":"subagent","disabled":"disabled","line":"border","accent":"accent","button":"primary",
326 "button-text":"primary_foreground","attention":"attention","hover":"hover","selected":"selected",
327 "live":"live","live-peak":"live_peak","danger":"danger","border-strong":"border_strong","ocean-depth":"ocean_depth",
328 "diff-add":"diff_add","diff-remove":"diff_remove"}
329 css = [f"/* {header} */"]
330 for mode, palette in data["colors"].items():
331 css += [":root {" if mode == "dark" else '[data-theme="light"] {']
332 css += [f" --{alias}: #{palette[key]};" for alias, key in aliases.items()]
333 elevation = data["elevation"]
334 css += [f' --selection: #{palette["accent"]}{round(data["selection_opacity"] * 255):02x};',
335 f' --elevation-popover: 0 {elevation["popover_y_px"]}px {elevation["popover_blur_px"]}px rgb(0 0 0 / {elevation[f"popover_alpha_{mode}"]});',
336 f' --elevation-dialog: 0 {elevation["dialog_y_px"]}px {elevation["dialog_blur_px"]}px rgb(0 0 0 / {elevation[f"dialog_alpha_{mode}"]});']
337 water = ", ".join(f"#{color(s['color'], 'water')[0]} {s['at']}%" for s in data["water"][mode])
338 light = data["surface_light"][mode]
339 glow = ", ".join(f"{css_color(s['color'], 'surface_light')} {s['at']}%" for s in light["stops"])
340 css += [f" --water: linear-gradient(180deg, {water});",
341 f" --surface-light: radial-gradient(ellipse at {light['x']}% {light['y']}%, {glow});"]
342 css += [f" --glass-{level}-fill: {css_color(data['glass'][mode][level]['fill'], 'glass')};" for level in LEVELS]
343 css += [f" --glass-{part}: {css_color(data['glass'][mode][part], 'glass')};" for part in ["border", "highlight"]]
344 for group in ["sheet", "card", "change_bar", "subagent_tag", "workbar"]:
345 slug = group.replace("_", "-")
346 css += [f" --{slug}-{part}: {css_color(value, group)};" for part, value in data[group][mode].items()]
347 css += [f" color-scheme: {mode};", "}"]
348 dark_glass = data["glass"][modes[0]]
349 for index, level in enumerate(["frosted", "clear", "solid"]):
350 selector = ":root, [data-theme], [data-glass]" if index == 0 else f'[data-glass="{level}"], [data-glass="{level}"] [data-theme]'
351 css += [f"{selector} {{", f" --glass-fill: var(--glass-{level}-fill);",
352 f" --glass-blur: {dark_glass[level]['blur_px']}px;", "}"]
353 css += [":root, [data-theme] {"]
354 glow = data["glow"]
355 css_alias = {"primary": "accent", "live": "live", "attention": "attention"}
356 css += [f' --glow-{name[:-6]}: 0 0 {glow["blur_px"]}px color-mix(in srgb, var(--{css_alias[name[:-6]]}) {round(value * 100)}%, transparent);'
357 for name, value in glow.items() if name.endswith("_alpha")]
358 css += [f' --tint-{name.replace("_", "-")}: color-mix(in srgb, {source} {round(data["tint"][name] * 100)}%, transparent);'
359 for name, source in TINT_SOURCES.items()]
360 css += [" --verb-sweep: linear-gradient(90deg, var(--muted) 0%, var(--live) 34%, var(--live-peak) 50%, var(--live) 66%, var(--muted) 100%);",
361 " --focus-ring: var(--focus-width) solid var(--accent);", " --glass-edge: inset 0 1px 0 var(--glass-highlight);"]
362 css += ["}"]
363 css += [":root {"]
364 for section in ["spacing", "radius", "focus"]:
365 css += [f" --{section}-{name}: {value}px;" for name, value in data[section].items()]
366 motion = data["motion"]
367 css += [f" --motion-duration-{name[9:-3].replace('_', '-')}: {value}ms;" for name, value in motion.items()
368 if name.startswith("duration_")]
369 css += [f" --motion-{name[:-3].replace('_', '-')}: {value}ms;" for name, value in motion.items()
370 if (name.startswith("loop_") or name in ("sweep_active_ms", "sweep_rest_ms", "sweep_delay_ms")) and name.endswith("_ms")]
371 css += [f" --motion-{name[:-6].replace('_', '-')}: {value};" for name, value in motion.items()
372 if name in ("breathe_min_alpha", "breathe_max_alpha")]
373 css += [f' --motion-arrive-rise: {motion["arrive_rise_px"]}px;']
374 css += [f" --motion-ease-{name}: cubic-bezier({', '.join(str(v) for v in curve)});"
375 for name, curve in data["easing"].items()]
376 css += [f" --ombre-{name}: #{value};" for name, value in data["ombre"].items()]
377 css += [f' --ombre: linear-gradient(135deg, #{data["ombre"]["rise"]}, #{data["ombre"]["deep"]});']
378 css += [f' --icon-stroke: {data["icons"]["stroke"]};',
379 f' --font-family: {json.dumps(data["typography"]["family"], ensure_ascii=False)};',
380 f' --font-mono-family: {json.dumps(data["typography"]["mono_family"], ensure_ascii=False)};',
381 f' --font-fallbacks: {", ".join(json.dumps(v, ensure_ascii=False) for v in data["typography"]["fallbacks"])};',
382 f' --font-body-size: {data["typography"]["body_px"]}px;',
383 f' --font-code-size: {data["typography"]["mono_px"]}px;']
384 for name in ["caption_px", "prose_px", "heading_px", "title_px"]:
385 if name in data["typography"]:
386 css += [f' --font-{name[:-3]}-size: {data["typography"][name]}px;']
387 for name, role in data["type_roles"].items():
388 css += [f' --type-{name}-size: {role["size_px"]}px;', f' --type-{name}-line: {role["line_px"]}px;',
389 f' --type-{name}-weight: {role["weight"]};']
390 css += [f' --size-{name[:-3].replace("_", "-")}: {value}px;' for name, value in data["size"].items()]
391 css += [f' --breakpoint-{name[:-3]}: {value}px;' for name, value in data["breakpoints"].items()]
392 css += ["}"]
393 reduced = [f" --motion-duration-{name[9:-3].replace('_', '-')}: 0ms;" for name in motion if name.startswith("duration_")]
394 reduced += [f" --motion-{name[:-3].replace('_', '-')}: 0ms;" for name in motion
395 if (name.startswith("loop_") or name in ("sweep_active_ms", "sweep_rest_ms", "sweep_delay_ms")) and name.endswith("_ms")]
396 reduced += [" --motion-arrive-rise: 0px;"]
397 css += ["@media (prefers-reduced-motion: reduce) {", " :root {"] + [f" {line}" for line in reduced] + [" }", "}"]
398 css += [':root[data-motion="reduced"],', ':root[data-motion="still"] {'] + reduced + ["}"]
399 ts = [f"// {header}", f"export const tokens = {json.dumps(data, indent=2, ensure_ascii=False)} as const;",
400 "export type Tokens = typeof tokens;"]
401 figma = figma_payload(data, aliases)
402 sync = f"// {header}\nconst PAYLOAD = {json.dumps(figma, indent=1)};\n" + (HERE / "figma" / "sync.template.js").read_text()
403 mark = (HERE / "whale/source/mark.svg").read_text()
404 brand = {"sourceHash": hashlib.sha256(mark.encode()).hexdigest(), "light": mark, "dark": mark.replace("#000000", "#F5F5F5")}
405 brand_script = "const CW_BRAND = " + json.dumps(brand) + ";\n" + (HERE / "figma/brand.template.js").read_text()
406 return {"tokens.rs": "\n".join(rust) + "\n", "tokens.css": "\n".join(css) + "\n", "tokens.ts": "\n".join(ts) + "\n",
407 "tokens.dtcg.json": json.dumps(dtcg(data), indent=2) + "\n",
408 "figma/variables.json": json.dumps(figma, indent=2) + "\n", "figma/sync.js": sync, "figma/brand.js": brand_script}
409
410 def main():
411 parser = argparse.ArgumentParser(description=__doc__)
412 parser.add_argument("--check", action="store_true")
413 args = parser.parse_args()
414 stale = []
415 for name, content in render().items():
416 path = ROOT / name
417 if args.check:
418 if not path.exists() or path.read_text() != content:
419 stale.append(name)
420 else:
421 path.parent.mkdir(exist_ok=True)
422 path.write_text(content)
423 if stale:
424 raise SystemExit("Stale design artifact: " + ", ".join(stale))
425 print("Design artifact verified" if args.check else "Design artifact generated")
426
427 if __name__ == "__main__":
428 main()
429
429 lines PYTHON