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

generate-uniwind-themes.mts

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