Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate-uniwind-themes.mts

278 lines12.4 KB

1#!/usr/bin/env node
2​
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import tailwindColors from "tailwindcss/colors";
6import { BUILT_IN_THEME_IDS, type BuiltInThemeId } from "@t3tools/shared/themePalettes";
7​
8import {
9 getMobileThemeVariables,
10 MOBILE_THEME_VARIABLE_NAMES,
11 type MobileThemeAppearance,
12 type MobileThemeVariables,
13} from "../src/lib/mobileTheme.ts";
14​
15const APPEARANCES = ["light", "dark"] as const;
16const GLOBAL_CSS_PATH = NodePath.resolve(import.meta.dirname, "../global.css");
17const GENERATED_CSS_PATH = NodePath.resolve(import.meta.dirname, "../generated-uniwind-themes.css");
18const GENERATED_NAMES_PATH = NodePath.resolve(
19 import.meta.dirname,
20 "../generated-uniwind-theme-names.json",
21);
22const GENERATED_DEFAULT_VARIABLES_PATH = NodePath.resolve(
23 import.meta.dirname,
24 "../generated-uniwind-default-theme-variables.json",
25);
26​
27type TailwindColorFamily = keyof typeof tailwindColors;
28type TailwindColorShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950;
29​
30const color = (family: TailwindColorFamily, shade?: TailwindColorShade, opacity = 1): string => {
31 const familyColors = tailwindColors[family];
32 const value =
33 typeof familyColors === "string"
34 ? shade === undefined
35 ? familyColors
36 : undefined
37 : shade === undefined
38 ? undefined
39 : familyColors[String(shade) as keyof typeof familyColors];
40 if (value === undefined) {
41 throw new Error(`Unknown Tailwind color ${family}${shade === undefined ? "" : `-${shade}`}.`);
42 }
43 if (opacity === 1) return value;
44​
45 const percentage = Number((opacity * 100).toFixed(4));
46 const oklch = /^oklch\((.*)\)$/.exec(value);
47 if (oklch) return `oklch(${oklch[1]} / ${percentage}%)`;
48 if (value === "#fff") return `rgb(255 255 255 / ${percentage}%)`;
49 if (value === "#000") return `rgb(0 0 0 / ${percentage}%)`;
50 return `color-mix(in srgb, ${value} ${percentage}%, transparent)`;
51};
52​
53// These replace the remaining dark:* utility pairs. A registered palette theme is
54// neither literally `light` nor `dark`, so appearance-sensitive values must also be
55// represented as semantic variables for custom themes.
56const ADAPTIVE_COLORS: Readonly<Record<string, readonly [light: string, dark: string]>> = {
57 "--color-adaptive-amber-50-950-a40": [color("amber", 50), color("amber", 950, 0.4)],
58 "--color-adaptive-amber-200-900-a60": [color("amber", 200), color("amber", 900, 0.6)],
59 "--color-adaptive-amber-500-a12-a16": [color("amber", 500, 0.12), color("amber", 500, 0.16)],
60 "--color-adaptive-amber-500-a10-400-a10": [color("amber", 500, 0.1), color("amber", 400, 0.1)],
61 "--color-adaptive-amber-500-a25-400-a25": [color("amber", 500, 0.25), color("amber", 400, 0.25)],
62 "--color-adaptive-amber-700-300": [color("amber", 700), color("amber", 300)],
63 "--color-adaptive-amber-700-400": [color("amber", 700), color("amber", 400)],
64 "--color-adaptive-amber-800-200": [color("amber", 800), color("amber", 200)],
65 "--color-adaptive-blue-50-blue-400-a14": [color("blue", 50), color("blue", 400, 0.14)],
66 "--color-adaptive-blue-300-a50-blue-400-a28": [color("blue", 300, 0.5), color("blue", 400, 0.28)],
67 "--color-adaptive-blue-500-a20-blue-400-a15": [color("blue", 500, 0.2), color("blue", 400, 0.15)],
68 "--color-adaptive-blue-500-400": [color("blue", 500), color("blue", 400)],
69 "--color-adaptive-blue-600-400": [color("blue", 600), color("blue", 400)],
70 "--color-adaptive-black-a10-a25": [
71 color("black", undefined, 0.1),
72 color("black", undefined, 0.25),
73 ],
74 "--color-adaptive-black-a15-a35": [
75 color("black", undefined, 0.15),
76 color("black", undefined, 0.35),
77 ],
78 "--color-adaptive-black-a2p5-white-a2p5": [
79 color("black", undefined, 0.025),
80 color("white", undefined, 0.025),
81 ],
82 "--color-adaptive-emerald-500-a12-a16": [
83 color("emerald", 500, 0.12),
84 color("emerald", 500, 0.16),
85 ],
86 "--color-adaptive-emerald-600-400": [color("emerald", 600), color("emerald", 400)],
87 "--color-adaptive-emerald-700-300": [color("emerald", 700), color("emerald", 300)],
88 "--color-adaptive-indigo-500-a12-a16": [color("indigo", 500, 0.12), color("indigo", 500, 0.16)],
89 "--color-adaptive-indigo-600-300": [color("indigo", 600), color("indigo", 300)],
90 "--color-adaptive-indigo-700-300": [color("indigo", 700), color("indigo", 300)],
91 "--color-adaptive-neutral-100-900": [color("neutral", 100), color("neutral", 900)],
92 "--color-adaptive-neutral-200-700-a60": [color("neutral", 200), color("neutral", 700, 0.6)],
93 "--color-adaptive-neutral-200-800": [color("neutral", 200), color("neutral", 800)],
94 "--color-adaptive-neutral-200-a70-white-a8": [
95 color("neutral", 200, 0.7),
96 color("white", undefined, 0.08),
97 ],
98 "--color-adaptive-neutral-200-white-a6": [color("neutral", 200), color("white", undefined, 0.06)],
99 "--color-adaptive-neutral-200-white-a8": [color("neutral", 200), color("white", undefined, 0.08)],
100 "--color-adaptive-neutral-200-a80-white-a8": [
101 color("neutral", 200, 0.8),
102 color("white", undefined, 0.08),
103 ],
104 "--color-adaptive-neutral-300-a60-white-a12": [
105 color("neutral", 300, 0.6),
106 color("white", undefined, 0.12),
107 ],
108 "--color-adaptive-neutral-400-500": [color("neutral", 400), color("neutral", 500)],
109 "--color-adaptive-neutral-400-a60-500-a60": [
110 color("neutral", 400, 0.6),
111 color("neutral", 500, 0.6),
112 ],
113 "--color-adaptive-neutral-400-a80-500-a80": [
114 color("neutral", 400, 0.8),
115 color("neutral", 500, 0.8),
116 ],
117 "--color-adaptive-neutral-500-a10-a16": [color("neutral", 500, 0.1), color("neutral", 500, 0.16)],
118 "--color-adaptive-neutral-500-400": [color("neutral", 500), color("neutral", 400)],
119 "--color-adaptive-neutral-500-500": [color("neutral", 500), color("neutral", 500)],
120 "--color-adaptive-neutral-600-300": [color("neutral", 600), color("neutral", 300)],
121 "--color-adaptive-neutral-600-400": [color("neutral", 600), color("neutral", 400)],
122 "--color-adaptive-neutral-950-50": [color("neutral", 950), color("neutral", 50)],
123 "--color-adaptive-neutral-950-a5-white-a5": [
124 color("neutral", 950, 0.05),
125 color("white", undefined, 0.05),
126 ],
127 "--color-adaptive-neutral-950-a10-white-a10": [
128 color("neutral", 950, 0.1),
129 color("white", undefined, 0.1),
130 ],
131 "--color-adaptive-red-50-950-a80": [color("red", 50), color("red", 950, 0.8)],
132 "--color-adaptive-red-200-800": [color("red", 200), color("red", 800)],
133 "--color-adaptive-red-600-a80-400-a80": [color("red", 600, 0.8), color("red", 400, 0.8)],
134 "--color-adaptive-red-700-300": [color("red", 700), color("red", 300)],
135 "--color-adaptive-rose-100-500-a18": [color("rose", 100), color("rose", 500, 0.18)],
136 "--color-adaptive-rose-100-a80-500-a12": [color("rose", 100, 0.8), color("rose", 500, 0.12)],
137 "--color-adaptive-rose-300-a70-400-a28": [color("rose", 300, 0.7), color("rose", 400, 0.28)],
138 "--color-adaptive-rose-500-a12-a16": [color("rose", 500, 0.12), color("rose", 500, 0.16)],
139 "--color-adaptive-rose-500-400": [color("rose", 500), color("rose", 400)],
140 "--color-adaptive-rose-600-400": [color("rose", 600), color("rose", 400)],
141 "--color-adaptive-rose-700-300": [color("rose", 700), color("rose", 300)],
142 "--color-adaptive-sky-500-a12-a16": [color("sky", 500, 0.12), color("sky", 500, 0.16)],
143 "--color-adaptive-sky-500-a10-400-a10": [color("sky", 500, 0.1), color("sky", 400, 0.1)],
144 "--color-adaptive-sky-500-a25-400-a25": [color("sky", 500, 0.25), color("sky", 400, 0.25)],
145 "--color-adaptive-sky-600-400": [color("sky", 600), color("sky", 400)],
146 "--color-adaptive-sky-700-300": [color("sky", 700), color("sky", 300)],
147 "--color-adaptive-violet-500-a12-a16": [color("violet", 500, 0.12), color("violet", 500, 0.16)],
148 "--color-adaptive-violet-600-400": [color("violet", 600), color("violet", 400)],
149 "--color-adaptive-violet-700-300": [color("violet", 700), color("violet", 300)],
150 "--color-adaptive-white-neutral-950-a70": [color("white"), color("neutral", 950, 0.7)],
151 "--color-adaptive-zinc-500-a12-a16": [color("zinc", 500, 0.12), color("zinc", 500, 0.16)],
152 "--color-adaptive-zinc-500-400": [color("zinc", 500), color("zinc", 400)],
153 "--color-adaptive-zinc-600-300": [color("zinc", 600), color("zinc", 300)],
154};
155​
156export const customThemeNames = BUILT_IN_THEME_IDS.flatMap((themeId) =>
157 APPEARANCES.map((appearance) => `${themeId}-${appearance}`),
158);
159​
160const adaptiveVariablesFor = (appearance: MobileThemeAppearance) =>
161 Object.fromEntries(
162 Object.entries(ADAPTIVE_COLORS).map(([name, [light, dark]]) => [
163 name,
164 appearance === "light" ? light : dark,
165 ]),
166 );
167​
168const variablesFor = (themeId: BuiltInThemeId, appearance: MobileThemeAppearance) => ({
169 ...getMobileThemeVariables(themeId, appearance),
170 ...adaptiveVariablesFor(appearance),
171});
172​
173const renderVariant = (name: string, variables: Readonly<Record<string, string>>) => {
174 const declarations = Object.entries(variables)
175 .map(([variable, value]) => ` ${variable}: ${value};`)
176 .join("\n");
177 return ` @variant ${name} {\n${declarations}\n }`;
178};
179​
180export const renderUniwindThemesCSS = () => {
181 const variants = [
182 renderVariant("light", adaptiveVariablesFor("light")),
183 renderVariant("dark", adaptiveVariablesFor("dark")),
184 ...BUILT_IN_THEME_IDS.flatMap((themeId) =>
185 APPEARANCES.map((appearance) =>
186 renderVariant(`${themeId}-${appearance}`, variablesFor(themeId, appearance)),
187 ),
188 ),
189 ];
190 return [
191 "/* Generated by scripts/generate-uniwind-themes.mts. Do not edit manually. */",
192 "@layer theme {",
193 " :root {",
194 variants.join("\n\n"),
195 " }",
196 "}",
197 "",
198 ].join("\n");
199};
200​
201const readVariantBody = (css: string, appearance: MobileThemeAppearance): string => {
202 const marker = `@variant ${appearance} {`;
203 const markerIndex = css.indexOf(marker);
204 if (markerIndex === -1) throw new Error(`Could not find ${marker} in global.css.`);
205​
206 const openingBraceIndex = css.indexOf("{", markerIndex);
207 let depth = 0;
208 for (let index = openingBraceIndex; index < css.length; index += 1) {
209 if (css[index] === "{") depth += 1;
210 if (css[index] !== "}") continue;
211 depth -= 1;
212 if (depth === 0) return css.slice(openingBraceIndex + 1, index);
213 }
214 throw new Error(`Could not find the end of ${marker} in global.css.`);
215};
216​
217export const readDefaultThemeVariables = (css: string) =>
218 Object.fromEntries(
219 APPEARANCES.map((appearance) => {
220 const body = readVariantBody(css, appearance);
221 const variables = Object.fromEntries(
222 MOBILE_THEME_VARIABLE_NAMES.map((name) => {
223 const match = new RegExp(`^\\s*${name}:\\s*([^;]+);`, "mu").exec(body);
224 if (!match?.[1]) {
225 throw new Error(`Default ${appearance} theme is missing ${name}.`);
226 }
227 return [name, match[1].trim()];
228 }),
229 ) as MobileThemeVariables;
230 return [appearance, variables];
231 }),
232 ) as Readonly<Record<MobileThemeAppearance, MobileThemeVariables>>;
233​
234export const renderDefaultThemeVariablesJSON = (css: string) =>
235 `${JSON.stringify(readDefaultThemeVariables(css), null, 2)}\n`;
236​
237export const getGeneratedUniwindThemeOutputs = (): ReadonlyArray<
238 readonly [filename: string, contents: string]
239> => [
240 [GENERATED_CSS_PATH, renderUniwindThemesCSS()],
241 [GENERATED_NAMES_PATH, `${JSON.stringify(customThemeNames, null, 2)}\n`],
242 [
243 GENERATED_DEFAULT_VARIABLES_PATH,
244 renderDefaultThemeVariablesJSON(NodeFS.readFileSync(GLOBAL_CSS_PATH, "utf8")),
245 ],
246];
247​
248const writeFileAtomically = (filename: string, contents: string) => {
249 const current = NodeFS.existsSync(filename) ? NodeFS.readFileSync(filename, "utf8") : null;
250 if (current === contents) return;
251​
252 const temporaryFilename = `${filename}.${process.pid}.tmp`;
253 try {
254 NodeFS.writeFileSync(temporaryFilename, contents);
255 NodeFS.renameSync(temporaryFilename, filename);
256 } finally {
257 if (NodeFS.existsSync(temporaryFilename)) NodeFS.unlinkSync(temporaryFilename);
258 }
259};
260​
261if (import.meta.main) {
262 const checkOnly = process.argv.includes("--check");
263 for (const [filename, contents] of getGeneratedUniwindThemeOutputs()) {
264 if (checkOnly) {
265 const current = NodeFS.existsSync(filename) ? NodeFS.readFileSync(filename, "utf8") : null;
266 if (current !== contents) {
267 console.error(
268 `${NodePath.relative(process.cwd(), filename)} is stale. Run vp run --filter @t3tools/mobile generate.`,
269 );
270 process.exitCode = 1;
271 }
272 continue;
273 }
274 // Metro watches the generated CSS. Replacing a complete temporary file keeps
275 // Tailwind from compiling a partially rewritten theme file.
276 writeFileAtomically(filename, contents);
277 }