@halftone-ds/tokens 1.3.2 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -11
- package/cli.mjs +50 -15
- package/lib/contrast.mjs +50 -6
- package/lib/doctor.mjs +360 -0
- package/lib/generate.mjs +28 -0
- package/lib/init.mjs +264 -0
- package/lib/resolve.mjs +31 -2
- package/lib/scan.mjs +15 -11
- package/lib/system/generate.mjs +5 -1
- package/lib/system/index.d.mts +17 -2
- package/lib/system/index.mjs +1 -0
- package/lib/system/schema.mjs +80 -9
- package/lib/theme/apply.mjs +30 -5
- package/lib/theme/codec.mjs +13 -7
- package/lib/theme/components.mjs +276 -52
- package/lib/theme/fix.mjs +26 -3
- package/lib/theme/generate.mjs +14 -1
- package/lib/theme/index.d.mts +72 -3
- package/lib/theme/index.mjs +9 -2
- package/lib/theme/motion.mjs +99 -0
- package/lib/theme/recipe.mjs +11 -1
- package/lib/theme/semantic.mjs +27 -0
- package/lib/theme/vars.mjs +20 -4
- package/lib/usage.mjs +1 -1
- package/package.json +2 -1
- package/targets/design-md.mjs +17 -11
- package/targets/figma.mjs +3 -0
- package/targets/fonts.mjs +28 -1
- package/targets/llms.mjs +6 -6
- package/targets/nativewind3.mjs +43 -13
- package/targets/shadcn-web.mjs +36 -5
- package/targets/ts-theme.mjs +44 -7
- package/templates/tokens.json +2400 -0
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `halftone-tokens doctor` — check that an app is set up for Halftone's kit components, and say how to fix what isn't.
|
|
3
|
+
* Read-only: it never changes a file.
|
|
4
|
+
*
|
|
5
|
+
* halftone-tokens doctor [--platform web|expo] [--offline] [--json]
|
|
6
|
+
*
|
|
7
|
+
* Problems (exit 1): tokens not set up or out of date; the stylesheet (web) or global.css (Expo) not importing them;
|
|
8
|
+
* the Tailwind preset missing (Expo); a components.json on another style; `@/` aliases that don't resolve; a kit
|
|
9
|
+
* file in components/ui that shadcn's or react-native-reusables' stock version has replaced.
|
|
10
|
+
* Warnings: rules in the app's own files that win over the kit's; nothing that sets dark mode; kit links without
|
|
11
|
+
* KitLinkProvider; fonts not loaded (Expo); a second `cn` in lib/utils.ts.
|
|
12
|
+
*
|
|
13
|
+
* The stock-file check reads the kit's registry (the URL in components.json) and the upstream one: --offline skips it.
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
16
|
+
import { basename, join, posix, relative } from 'node:path';
|
|
17
|
+
|
|
18
|
+
import { loadContext, renderTargets } from './generate.mjs';
|
|
19
|
+
import { detectPlatform, overridingExtends, overridingRules, STYLESHEETS, STYLESHEETS_EXPO } from './init.mjs';
|
|
20
|
+
|
|
21
|
+
/** Where the stock version of a kit-changed ui file comes from, by platform. */
|
|
22
|
+
export const UPSTREAM = {
|
|
23
|
+
web: { registry: '@halftone-web', url: 'https://ui.shadcn.com/r/styles/new-york-v4/{name}.json', label: "shadcn/ui's" },
|
|
24
|
+
expo: { registry: '@halftone-native', url: 'https://reactnativereusables.com/r/nativewind/{name}.json', label: "react-native-reusables'" },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const toPosix = (p) => p.split('\\').join('/');
|
|
28
|
+
const read = (path) => readFileSync(path, 'utf8');
|
|
29
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
30
|
+
|
|
31
|
+
/** JSON with comments and trailing commas (tsconfig), read without mistaking "@/*" for a comment. */
|
|
32
|
+
export function parseJsonc(text) {
|
|
33
|
+
let out = '';
|
|
34
|
+
for (let i = 0; i < text.length; i++) {
|
|
35
|
+
const c = text[i];
|
|
36
|
+
if (c === '"') {
|
|
37
|
+
let j = i + 1;
|
|
38
|
+
while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
|
|
39
|
+
out += text.slice(i, j + 1);
|
|
40
|
+
i = j;
|
|
41
|
+
} else if (c === '/' && text[i + 1] === '/') {
|
|
42
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
43
|
+
out += '\n';
|
|
44
|
+
} else if (c === '/' && text[i + 1] === '*') {
|
|
45
|
+
i = text.indexOf('*/', i + 2);
|
|
46
|
+
if (i === -1) break;
|
|
47
|
+
i++;
|
|
48
|
+
} else out += c;
|
|
49
|
+
}
|
|
50
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A file's code without its imports, directives and whitespace: what `shadcn add` leaves alone. It rewrites import
|
|
55
|
+
* paths to the app's aliases and drops "use client" outside RSC, so those can't tell two copies apart.
|
|
56
|
+
*/
|
|
57
|
+
export function normalizeSource(src) {
|
|
58
|
+
return src
|
|
59
|
+
.replace(/^\s*['"]use client['"];?/gm, '')
|
|
60
|
+
.replace(/^\s*import\s[\s\S]*?\sfrom\s*['"][^'"]+['"];?/gm, '')
|
|
61
|
+
.replace(/^\s*import\s*['"][^'"]+['"];?/gm, '')
|
|
62
|
+
.replace(/\s+/g, '');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The `paths` of the app's tsconfig (tsconfig.json, then tsconfig.app.json, as Vite splits them). */
|
|
66
|
+
export function tsPaths(root) {
|
|
67
|
+
for (const file of ['tsconfig.json', 'tsconfig.app.json']) {
|
|
68
|
+
try {
|
|
69
|
+
const paths = parseJsonc(read(join(root, file))).compilerOptions?.paths;
|
|
70
|
+
if (paths && Object.keys(paths).length) return { file, paths };
|
|
71
|
+
} catch {
|
|
72
|
+
// missing or unreadable: try the next
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { file: null, paths: {} };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** An import alias (`@/components/ui`) as a folder relative to the root (`src/components/ui`), or null. */
|
|
79
|
+
export function aliasDir(paths, alias) {
|
|
80
|
+
for (const [key, targets] of Object.entries(paths)) {
|
|
81
|
+
const prefix = key.replace(/\*$/, '');
|
|
82
|
+
const target = Array.isArray(targets) ? targets[0] : null;
|
|
83
|
+
if (!key.endsWith('*') || typeof target !== 'string' || !alias.startsWith(prefix)) continue;
|
|
84
|
+
return posix.normalize(posix.join(target.replace(/\*$/, '') || '.', alias.slice(prefix.length)));
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Files under dir (relative to root), skipping dependencies, builds and the kit's own folders. */
|
|
90
|
+
function sourceFiles(root, dir, found = []) {
|
|
91
|
+
const full = join(root, dir);
|
|
92
|
+
if (!existsSync(full)) return found;
|
|
93
|
+
for (const name of readdirSync(full)) {
|
|
94
|
+
if (/^(node_modules|dist|build|\.next|\.expo|\.git|ios|android|tokens|ui|kit)$/.test(name)) continue;
|
|
95
|
+
const rel = posix.join(dir, name);
|
|
96
|
+
const stat = statSync(join(root, rel));
|
|
97
|
+
if (stat.isDirectory()) sourceFiles(root, rel, found);
|
|
98
|
+
else if (/\.(tsx?|jsx?|html)$/.test(name)) found.push(rel);
|
|
99
|
+
}
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
const anySource = (root, dirs, re) => dirs.some((dir) => sourceFiles(root, dir).some((f) => re.test(read(join(root, f)))));
|
|
103
|
+
|
|
104
|
+
async function fetchJson(url) {
|
|
105
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
|
|
106
|
+
if (!res.ok) throw new Error(`${res.status} ${url}`);
|
|
107
|
+
return res.json();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function doctorCommand({ root, flags }) {
|
|
111
|
+
const results = await doctor({ root, flags });
|
|
112
|
+
const problems = results.filter((r) => r.level === 'problem');
|
|
113
|
+
const warnings = results.filter((r) => r.level === 'warning');
|
|
114
|
+
if (flags.json) {
|
|
115
|
+
console.log(JSON.stringify({ ok: problems.length === 0, results }, null, 2));
|
|
116
|
+
} else {
|
|
117
|
+
const mark = { ok: '✓', problem: '✗', warning: '!', info: '·' };
|
|
118
|
+
for (const r of results) {
|
|
119
|
+
console.log(`${mark[r.level]} ${r.message}`);
|
|
120
|
+
if (r.fix) console.log(` ${r.fix.split('\n').join('\n ')}`);
|
|
121
|
+
}
|
|
122
|
+
const summary = [problems.length && `${problems.length} problem(s)`, warnings.length && `${warnings.length} warning(s)`].filter(Boolean);
|
|
123
|
+
console.log(`\nhalftone-tokens doctor: ${summary.length ? summary.join(', ') : 'all good'}.`);
|
|
124
|
+
}
|
|
125
|
+
if (problems.length) process.exitCode = 1;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Every check, as [{ level: ok|problem|warning|info, message, fix? }]. */
|
|
129
|
+
export async function doctor({ root, flags = {} }) {
|
|
130
|
+
const results = [];
|
|
131
|
+
const ok = (message) => results.push({ level: 'ok', message });
|
|
132
|
+
const problem = (message, fix) => results.push({ level: 'problem', message, fix });
|
|
133
|
+
const warning = (message, fix) => results.push({ level: 'warning', message, fix });
|
|
134
|
+
const info = (message, fix) => results.push({ level: 'info', message, fix });
|
|
135
|
+
|
|
136
|
+
let pkg = {};
|
|
137
|
+
try {
|
|
138
|
+
pkg = JSON.parse(read(join(root, 'package.json')));
|
|
139
|
+
} catch {
|
|
140
|
+
problem('No package.json here.', 'Run doctor in the app’s root folder, or pass --root <dir>.');
|
|
141
|
+
return results;
|
|
142
|
+
}
|
|
143
|
+
const platform = flags.platform === 'web' || flags.platform === 'expo' ? flags.platform : detectPlatform(pkg);
|
|
144
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
145
|
+
info(platform === 'expo' ? 'An Expo app (NativeWind).' : 'A React app (Tailwind 4).');
|
|
146
|
+
|
|
147
|
+
// components.json: the style, the aliases, the registry.
|
|
148
|
+
let components = null;
|
|
149
|
+
try {
|
|
150
|
+
components = JSON.parse(read(join(root, 'components.json')));
|
|
151
|
+
} catch {
|
|
152
|
+
warning('No components.json: shadcn needs one to add kit components.', 'install.md, path ' + (platform === 'expo' ? 'C' : 'D') + ', step 1, has the file to write.');
|
|
153
|
+
}
|
|
154
|
+
if (components) {
|
|
155
|
+
if (components.style && components.style !== 'new-york') {
|
|
156
|
+
problem(
|
|
157
|
+
`components.json has style "${components.style}". Kit components are built on Radix with the new-york style.`,
|
|
158
|
+
'Set "style": "new-york" (install.md, path D, step 1). A Base UI app can’t use kit components.'
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const upstream = UPSTREAM[platform];
|
|
162
|
+
if (!components.registries?.[upstream.registry]) {
|
|
163
|
+
warning(`components.json has no "${upstream.registry}" registry.`, `Add it: "registries": { "${upstream.registry}": "https://halftonedesignsystem.com/r/${platform === 'expo' ? 'native' : 'web'}/{name}.json" }`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The @/ aliases kit components import through.
|
|
168
|
+
const { file: tsFile, paths } = tsPaths(root);
|
|
169
|
+
const aliases = components?.aliases ?? { ui: '@/components/ui', lib: '@/lib', utils: '@/lib/utils', components: '@/components' };
|
|
170
|
+
const uiDir = aliasDir(paths, aliases.ui ?? '@/components/ui');
|
|
171
|
+
const libDir = aliasDir(paths, aliases.lib ?? '@/lib');
|
|
172
|
+
if (!uiDir) {
|
|
173
|
+
problem(
|
|
174
|
+
`${tsFile ?? 'tsconfig.json'} doesn't map "${aliases.ui ?? '@/components/ui'}": kit components import through the @/ aliases.`,
|
|
175
|
+
`Add "paths": { "@/*": ["./${platform === 'expo' ? '' : 'src/'}*"] } to compilerOptions${platform === 'expo' ? '' : ' (and the same alias to vite.config.ts in a Vite app)'}.`
|
|
176
|
+
);
|
|
177
|
+
} else {
|
|
178
|
+
ok(`The @/ aliases resolve (${aliases.ui} → ${uiDir}).`);
|
|
179
|
+
const vite = ['vite.config.ts', 'vite.config.js', 'vite.config.mts', 'vite.config.mjs'].find((f) => existsSync(join(root, f)));
|
|
180
|
+
if (vite && !/['"]@['"]\s*:|find:\s*['"]@['"]|tsconfigPaths|tsconfig-paths/.test(read(join(root, vite)))) {
|
|
181
|
+
warning(`${vite} has no "@" alias: TypeScript resolves @/ imports, but the build won't.`, "resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }");
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// The tokens: set up, built, up to date.
|
|
186
|
+
const configPath = join(root, flags.config ?? 'tokens/tokens.config.json');
|
|
187
|
+
let config = null;
|
|
188
|
+
if (!existsSync(configPath)) {
|
|
189
|
+
problem('Halftone’s tokens aren’t set up (no tokens/tokens.config.json).', 'npx halftone-tokens init # or: npx halftone-tokens init --theme <code>');
|
|
190
|
+
} else {
|
|
191
|
+
config = JSON.parse(read(configPath));
|
|
192
|
+
const source = config.source ?? 'tokens/tokens.json';
|
|
193
|
+
if (!existsSync(join(root, source))) {
|
|
194
|
+
problem(`${source} is missing.`, 'npx halftone-tokens init --force');
|
|
195
|
+
config = null;
|
|
196
|
+
} else {
|
|
197
|
+
const ctx = await loadContext(root, source);
|
|
198
|
+
const files = await renderTargets(ctx, config);
|
|
199
|
+
const stale = files.filter((f) => !existsSync(join(root, f.path)) || read(join(root, f.path)) !== f.contents);
|
|
200
|
+
if (stale.length) {
|
|
201
|
+
problem(
|
|
202
|
+
`${stale.length} generated file(s) out of date: ${stale.map((f) => f.path).join(', ')}.`,
|
|
203
|
+
'npx halftone-tokens build' + (platform === 'expo' ? ' (after every `shadcn add`: the registry brings lib/theme.ts and lib/fonts.ts with Halftone’s default brand)' : '')
|
|
204
|
+
);
|
|
205
|
+
} else ok(`The tokens are built and up to date (${files.length} files).`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (platform === 'expo') expoChecks({ root, deps, config, components, ok, problem, warning });
|
|
210
|
+
else webChecks({ root, deps, config, components, libDir, ok, problem, warning });
|
|
211
|
+
|
|
212
|
+
// One cn: kit and shadcn files import it from the `cn` package; an older lib/utils.ts has its own.
|
|
213
|
+
if (platform === 'web') {
|
|
214
|
+
const utilsDir = aliasDir(paths, posix.dirname(aliases.utils ?? '@/lib/utils'));
|
|
215
|
+
const utils = utilsDir && ['ts', 'tsx', 'js'].map((ext) => posix.join(utilsDir, `${basename(aliases.utils ?? 'utils')}.${ext}`)).find((f) => existsSync(join(root, f)));
|
|
216
|
+
if (utils) {
|
|
217
|
+
const src = read(join(root, utils));
|
|
218
|
+
if (/\bcn\b/.test(src) && !/from\s+['"]cn['"]/.test(src) && /twMerge|clsx/.test(src)) {
|
|
219
|
+
warning(
|
|
220
|
+
`${utils} has its own cn (clsx + tailwind-merge). Kit and shadcn files import cn from the \`cn\` package, so the app has two.`,
|
|
221
|
+
`Make ${utils} re-export it, as shadcn's own utils does now: export { cn } from 'cn';\nKeep any other helpers in the file. Then remove clsx and tailwind-merge if nothing else imports them.`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (uiDir && !flags.offline) await stockChecks({ root, platform, components, uiDir, ok, problem, info, warning });
|
|
228
|
+
return results;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function webChecks({ root, deps, config, components, libDir, ok, problem, warning }) {
|
|
232
|
+
const cssRel = components?.tailwind?.css ?? STYLESHEETS.find((p) => existsSync(join(root, p)));
|
|
233
|
+
if (!cssRel || !existsSync(join(root, cssRel))) {
|
|
234
|
+
problem(`No stylesheet found${cssRel ? ` at ${cssRel}` : ''}.`, 'Set "tailwind": { "css": "<your main stylesheet>" } in components.json.');
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const css = read(join(root, cssRel));
|
|
238
|
+
const importsOf = [...css.matchAll(/^\s*@import\s+(?:url\()?['"]([^'"]+)['"]/gm)].map((m) => m[1]);
|
|
239
|
+
const wants = (target) => {
|
|
240
|
+
const out = config?.targets?.[target]?.out;
|
|
241
|
+
if (!out) return null;
|
|
242
|
+
const rel = toPosix(relative(posix.dirname(cssRel), out));
|
|
243
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
244
|
+
};
|
|
245
|
+
if (!importsOf.includes('tailwindcss')) problem(`${cssRel} doesn't import tailwindcss: kit components need Tailwind 4.`, `@import 'tailwindcss';`);
|
|
246
|
+
if (!importsOf.includes('tw-animate-css')) {
|
|
247
|
+
warning(`${cssRel} doesn't import tw-animate-css: dialogs, menus and sheets won't animate.`, `npm install tw-animate-css, then @import 'tw-animate-css'; after tailwindcss in ${cssRel}.`);
|
|
248
|
+
}
|
|
249
|
+
const tokens = wants('shadcn-web');
|
|
250
|
+
if (config && tokens) {
|
|
251
|
+
if (!importsOf.includes(tokens)) problem(`${cssRel} doesn't import ${tokens}: kit components get no colours, sizes or type.`, `@import '${tokens}'; after tailwindcss in ${cssRel}.`);
|
|
252
|
+
else if (importsOf.indexOf(tokens) < importsOf.indexOf('tailwindcss')) warning(`${cssRel} imports ${tokens} before tailwindcss.`, `Move @import '${tokens}'; after @import 'tailwindcss';.`);
|
|
253
|
+
else ok(`${cssRel} imports ${tokens}.`);
|
|
254
|
+
}
|
|
255
|
+
// The fonts target writes CSS for a plain web app (platform: 'web'); a Next app loads them in code (next/font).
|
|
256
|
+
const fonts = /\.css$/.test(config?.targets?.fonts?.out ?? '') ? wants('fonts') : null;
|
|
257
|
+
if (config && fonts) {
|
|
258
|
+
if (!importsOf.includes(fonts)) problem(`${cssRel} doesn't import ${fonts}: the theme's fonts won't load.`, `@import '${fonts}'; as the first line of ${cssRel}.`);
|
|
259
|
+
else if (importsOf[0] !== fonts) warning(`${fonts} isn't the first import in ${cssRel}: a font @import after other rules is ignored.`, `Move @import '${fonts}'; to the top.`);
|
|
260
|
+
}
|
|
261
|
+
const overrides = overridingRules(css);
|
|
262
|
+
if (overrides.length) {
|
|
263
|
+
warning(
|
|
264
|
+
`${cssRel} has rules that tokens.css also defines, and they win over it: ${overrides.map((o) => `line ${o.line} ${o.name}`).join(', ')}.`,
|
|
265
|
+
'Delete them unless you mean to override the kit.'
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
// Dark mode: something has to put .dark on <html>.
|
|
269
|
+
const setsDark = deps['next-themes'] || anySource(root, ['src', 'app', '.'].filter((d) => d !== '.' || existsSync(join(root, 'index.html'))), /classList\.(add|toggle)\(\s*['"]dark['"]|class=["'][^"']*\bdark\b/);
|
|
270
|
+
if (!setsDark) warning('Nothing here sets the .dark class, so dark mode never shows.', 'next-themes with attribute="class" (Next.js), or your own code that toggles .dark on <html>.');
|
|
271
|
+
// Kit links: without KitLinkProvider they reload the page.
|
|
272
|
+
if (libDir && existsSync(join(root, libDir, 'link.tsx')) && !anySource(root, ['src', 'app', 'components'], /KitLinkProvider/)) {
|
|
273
|
+
warning('Kit components link through @/lib/link, but nothing sets KitLinkProvider: kit links reload the page.', "Wrap the app once in <KitLinkProvider link={…} usePathname={…}> (install.md, path D, step 5).");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function expoChecks({ root, deps, config, components, ok, problem, warning }) {
|
|
278
|
+
if (!deps.nativewind) problem('NativeWind isn’t installed: kit components are NativeWind classes.', 'npx expo install nativewind');
|
|
279
|
+
const cssRel = components?.tailwind?.css ?? STYLESHEETS_EXPO.find((p) => existsSync(join(root, p)));
|
|
280
|
+
const tokensOut = config?.targets?.nativewind3?.css;
|
|
281
|
+
if (cssRel && existsSync(join(root, cssRel)) && tokensOut) {
|
|
282
|
+
const css = read(join(root, cssRel));
|
|
283
|
+
const rel = toPosix(relative(posix.dirname(cssRel), tokensOut));
|
|
284
|
+
const spec = rel.startsWith('.') ? rel : `./${rel}`;
|
|
285
|
+
const first = css.replace(/\/\*[\s\S]*?\*\//g, '').split('\n').find((l) => l.trim());
|
|
286
|
+
if (!new RegExp(`@import\\s+['"]${escape(spec)}['"]`).test(css)) problem(`${cssRel} doesn't import ${spec}: kit components get no colours or sizes.`, `@import '${spec}'; as the first line of ${cssRel}.`);
|
|
287
|
+
else if (!first?.includes(spec)) warning(`${spec} isn't the first line of ${cssRel}: Tailwind only inlines an @import that comes first.`, `Move @import '${spec}'; to the top.`);
|
|
288
|
+
else ok(`${cssRel} imports ${spec} first.`);
|
|
289
|
+
const overrides = overridingRules(css);
|
|
290
|
+
if (overrides.length) warning(`${cssRel} has rules that win over the kit's: ${overrides.map((o) => `line ${o.line} ${o.name}`).join(', ')}.`, 'Delete them unless you mean to override the kit.');
|
|
291
|
+
}
|
|
292
|
+
const presetOut = config?.targets?.nativewind3?.preset;
|
|
293
|
+
const configRel = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.ts'].find((f) => existsSync(join(root, f)));
|
|
294
|
+
if (presetOut) {
|
|
295
|
+
const spec = `./${presetOut.replace(/\.js$/, '')}`;
|
|
296
|
+
if (!configRel) problem('No tailwind.config.js: NativeWind needs one, with the kit’s preset.', `presets: [require('nativewind/preset'), require('${spec}')]`);
|
|
297
|
+
else {
|
|
298
|
+
const tw = read(join(root, configRel));
|
|
299
|
+
if (!tw.includes(presetOut.replace(/\.js$/, ''))) problem(`${configRel} doesn't use the kit's preset: kit classes like h-button-md don't exist.`, `presets: [require('nativewind/preset'), require('${spec}')]`);
|
|
300
|
+
else ok(`${configRel} uses the kit's preset.`);
|
|
301
|
+
const own = overridingExtends(tw);
|
|
302
|
+
if (own.length) warning(`${configRel} extends ${own.join(', ')} itself, and those win over the kit's preset.`, 'Delete them from theme.extend unless you mean to override the kit.');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const dirs = ['app', 'src'];
|
|
306
|
+
if (!anySource(root, dirs, /KitThemeProvider/)) {
|
|
307
|
+
warning('Nothing wraps the app in KitThemeProvider: light, dark and the system setting won’t follow the kit.', `npx shadcn@latest add @halftone-native/lib-theme-context, then wrap the root layout in <KitThemeProvider>.`);
|
|
308
|
+
}
|
|
309
|
+
if (config?.targets?.fonts && !anySource(root, dirs, /FONT_ASSETS/)) {
|
|
310
|
+
warning("Nothing loads the theme's fonts: text falls back to the system font.", `useFonts(FONT_ASSETS) from '${components?.aliases?.lib ?? '@/lib'}/fonts' at the root (expo-font).`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Kit-changed files in components/ui, compared with the kit's copy and, when they differ, the stock one. */
|
|
315
|
+
async function stockChecks({ root, platform, components, uiDir, ok, problem, info, warning }) {
|
|
316
|
+
const upstream = UPSTREAM[platform];
|
|
317
|
+
const entry = components?.registries?.[upstream.registry];
|
|
318
|
+
const template = typeof entry === 'string' ? entry : entry?.url;
|
|
319
|
+
if (!template) return;
|
|
320
|
+
let index;
|
|
321
|
+
try {
|
|
322
|
+
index = await fetchJson(template.replace('{name}', 'registry'));
|
|
323
|
+
} catch (e) {
|
|
324
|
+
info(`Couldn't read the kit's registry (${e.message}), so kit files weren't compared. --offline skips this.`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const ui = (index.items ?? []).filter((i) => i.type === 'registry:ui').flatMap((i) => (i.files ?? []).map((f) => ({ item: i.name, path: f.path })));
|
|
328
|
+
const installed = ui.map((f) => ({ ...f, local: posix.join(uiDir, posix.basename(f.path)) })).filter((f) => existsSync(join(root, f.local)));
|
|
329
|
+
if (!installed.length) return;
|
|
330
|
+
const replaced = [];
|
|
331
|
+
const edited = [];
|
|
332
|
+
await Promise.all(
|
|
333
|
+
installed.map(async (f) => {
|
|
334
|
+
const local = normalizeSource(read(join(root, f.local)));
|
|
335
|
+
const kit = await fetchJson(template.replace('{name}', f.item)).catch(() => null);
|
|
336
|
+
const kitFile = kit?.files?.find((x) => x.path === f.path);
|
|
337
|
+
if (!kitFile || normalizeSource(kitFile.content) === local) return;
|
|
338
|
+
const name = posix.basename(f.path).replace(/\.tsx?$/, '');
|
|
339
|
+
const stock = await fetchJson(upstream.url.replace('{name}', name)).catch(() => null);
|
|
340
|
+
const stockFile = stock?.files?.find((x) => posix.basename(x.path) === posix.basename(f.path)) ?? stock?.files?.[0];
|
|
341
|
+
if (stockFile && normalizeSource(stockFile.content) === local) replaced.push(f);
|
|
342
|
+
else edited.push(f);
|
|
343
|
+
})
|
|
344
|
+
);
|
|
345
|
+
const ns = upstream.registry;
|
|
346
|
+
if (replaced.length) {
|
|
347
|
+
problem(
|
|
348
|
+
`${replaced.map((f) => f.local).join(', ')}: ${upstream.label} stock version replaced the kit's, so kit components look and behave wrong.`,
|
|
349
|
+
`npx shadcn@latest add ${replaced.map((f) => `${ns}/${f.item}`).join(' ')} --overwrite`
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
if (edited.length) {
|
|
353
|
+
warning(
|
|
354
|
+
`${edited.map((f) => f.local).join(', ')} differ${edited.length === 1 ? 's' : ''} from the kit's version (edited here, or from an older kit).`,
|
|
355
|
+
`Fine if you meant it. To take the kit's again: npx shadcn@latest add ${edited.map((f) => `${ns}/${f.item}`).join(' ')} --overwrite`
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
const same = installed.length - replaced.length - edited.length;
|
|
359
|
+
if (same) ok(`${same} kit file(s) in ${uiDir} match the kit's registry.`);
|
|
360
|
+
}
|
package/lib/generate.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `build` writes, without writing it: every target in tokens.config.json, rendered. `build` writes these,
|
|
3
|
+
* `check` compares them with the files on disk, `doctor` names the stale ones.
|
|
4
|
+
*/
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
|
|
8
|
+
import { loadTokens } from './resolve.mjs';
|
|
9
|
+
|
|
10
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
|
|
12
|
+
/** The resolved tokens, with what every target reads besides them: the app root and the generated-file header. */
|
|
13
|
+
export async function loadContext(root, source) {
|
|
14
|
+
const ctx = await loadTokens(join(root, source));
|
|
15
|
+
ctx.root = root;
|
|
16
|
+
ctx.header = `GENERATED by \`npm run tokens:build\` from ${source} — do not edit by hand.`;
|
|
17
|
+
return ctx;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** [{ path, contents }] for every target in the config, relative to the app root. */
|
|
21
|
+
export async function renderTargets(ctx, config) {
|
|
22
|
+
const files = [];
|
|
23
|
+
for (const [name, options] of Object.entries(config.targets ?? {})) {
|
|
24
|
+
const { default: target } = await import(pathToFileURL(join(here, '..', 'targets', `${name}.mjs`)).href);
|
|
25
|
+
files.push(...(await target(ctx, options ?? {})));
|
|
26
|
+
}
|
|
27
|
+
return files;
|
|
28
|
+
}
|
package/lib/init.mjs
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `halftone-tokens init` — set up Halftone's tokens in an existing app: any React app on Tailwind 4 + shadcn, or an
|
|
3
|
+
* Expo app on NativeWind + react-native-reusables (found from package.json; --platform web|expo overrides).
|
|
4
|
+
*
|
|
5
|
+
* halftone-tokens init [--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--platform web|expo] [--no-install] [--force]
|
|
6
|
+
*
|
|
7
|
+
* 1. writes tokens/tokens.json (Halftone's brand, templates/tokens.json) and tokens/tokens.config.json;
|
|
8
|
+
* 2. applies --theme, if given (the same as `halftone-tokens theme apply`), and builds, contrast checked;
|
|
9
|
+
* 3. web: tokens.css and fonts.css next to the app's stylesheet, imported from it (fonts.css first, tokens.css after
|
|
10
|
+
* Tailwind). Expo: tokens/generated/tokens.css imported first in global.css, a Tailwind preset added to
|
|
11
|
+
* tailwind.config.js (when it has the standard shape; otherwise the line to add is printed), and lib/theme.ts and
|
|
12
|
+
* lib/fonts.ts where the app's `@/lib` points;
|
|
13
|
+
* 4. names any rules in the app's own files that would override the kit, without deleting them.
|
|
14
|
+
* It refuses to replace an existing tokens.json or tokens.config.json without --force.
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import { dirname, join, posix, relative } from 'node:path';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
export const TEMPLATE = join(here, '..', 'templates', 'tokens.json');
|
|
23
|
+
|
|
24
|
+
/** Where a React app keeps its main stylesheet, most likely first (Next.js, then Vite and React Router). */
|
|
25
|
+
export const STYLESHEETS_EXPO = ['global.css', 'src/global.css', 'app/global.css'];
|
|
26
|
+
export const STYLESHEETS = ['app/globals.css', 'src/app/globals.css', 'src/index.css', 'src/app.css', 'app/app.css', 'src/styles/globals.css', 'styles/globals.css', 'src/styles.css'];
|
|
27
|
+
|
|
28
|
+
/** Rules in the app's stylesheet that tokens.css also defines; left there, they win over it. */
|
|
29
|
+
const OVERRIDES = [
|
|
30
|
+
[/^\s*:root\s*\{/, ':root'],
|
|
31
|
+
[/^\s*\.dark\s*\{/, '.dark'],
|
|
32
|
+
[/^\s*\.dark:root\s*\{/, '.dark:root'],
|
|
33
|
+
[/^\s*@theme\b/, '@theme'],
|
|
34
|
+
[/^\s*@layer\s+base\b/, '@layer base'],
|
|
35
|
+
[/^\s*body\s*\{/, 'body'],
|
|
36
|
+
[/^\s*@media\s*\(prefers-color-scheme/, '@media (prefers-color-scheme)'],
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
class InitError extends Error {}
|
|
40
|
+
|
|
41
|
+
const toPosix = (p) => p.split('\\').join('/');
|
|
42
|
+
const importOf = (from, file) => {
|
|
43
|
+
const rel = toPosix(relative(dirname(from), file));
|
|
44
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
45
|
+
};
|
|
46
|
+
const imports = (css, spec) => new RegExp(`@import\\s+(url\\()?['"]${spec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`).test(css);
|
|
47
|
+
|
|
48
|
+
/** Add the token imports to the stylesheet: fonts.css first (URL imports must lead), tokens.css after tailwindcss. */
|
|
49
|
+
export function wireStylesheet(css, { tokens, fonts }) {
|
|
50
|
+
const lines = css.split('\n');
|
|
51
|
+
const added = [];
|
|
52
|
+
if (!imports(css, tokens)) {
|
|
53
|
+
let after = -1;
|
|
54
|
+
lines.forEach((line, i) => {
|
|
55
|
+
if (/^\s*@import\s+['"](tailwindcss|tw-animate-css)['"]/.test(line)) after = i;
|
|
56
|
+
});
|
|
57
|
+
lines.splice(after + 1, 0, `@import '${tokens}';`);
|
|
58
|
+
added.push(tokens);
|
|
59
|
+
}
|
|
60
|
+
if (!imports(css, fonts)) {
|
|
61
|
+
lines.unshift(`@import '${fonts}';`);
|
|
62
|
+
added.push(fonts);
|
|
63
|
+
}
|
|
64
|
+
return { css: lines.join('\n'), added };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Line numbers of rules in the stylesheet that tokens.css also defines. */
|
|
68
|
+
export function overridingRules(css) {
|
|
69
|
+
const found = [];
|
|
70
|
+
css.split('\n').forEach((line, i) => {
|
|
71
|
+
for (const [re, name] of OVERRIDES) if (re.test(line)) found.push({ line: i + 1, name });
|
|
72
|
+
});
|
|
73
|
+
return found;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function initCommand({ root, flags, positional, run }) {
|
|
77
|
+
try {
|
|
78
|
+
await init({ root, flags, positional, run });
|
|
79
|
+
} catch (e) {
|
|
80
|
+
if (!(e instanceof InitError)) throw e;
|
|
81
|
+
console.error(`halftone-tokens init: ${e.message}`);
|
|
82
|
+
process.exit(2);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** web or expo, from the app's package.json (Expo with NativeWind is the native kit's shape). */
|
|
87
|
+
export function detectPlatform(pkg) {
|
|
88
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
89
|
+
return deps.expo && deps.nativewind ? 'expo' : 'web';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Add the kit's Tailwind preset to tailwind.config.js when it lists `presets: [require('nativewind/preset')]`, the
|
|
94
|
+
* shape react-native-reusables and create-expo-app's NativeWind setup write. null: not that shape, nothing changed.
|
|
95
|
+
*/
|
|
96
|
+
export function wirePreset(config, presetSpec) {
|
|
97
|
+
if (config.includes(presetSpec)) return config;
|
|
98
|
+
const re = /presets\s*:\s*\[\s*require\((['"])nativewind\/preset\1\)\s*,?\s*\]/;
|
|
99
|
+
if (!re.test(config)) return null;
|
|
100
|
+
return config.replace(re, (m, q) => `presets: [require(${q}nativewind/preset${q}), require(${q}${presetSpec}${q})]`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Theme keys the app's own tailwind.config.js extends; they win over the preset's. Only the keys directly inside
|
|
105
|
+
* `extend`: a `height` inside `keyframes` is an animation, not the theme's heights.
|
|
106
|
+
*/
|
|
107
|
+
export function overridingExtends(config) {
|
|
108
|
+
const start = /extend\s*:\s*\{/.exec(config);
|
|
109
|
+
if (!start) return [];
|
|
110
|
+
const direct = new Set();
|
|
111
|
+
let depth = 1;
|
|
112
|
+
let token = '';
|
|
113
|
+
for (let i = start.index + start[0].length; i < config.length && depth > 0; i++) {
|
|
114
|
+
const c = config[i];
|
|
115
|
+
if (c === '{' || c === '[' || c === '(') depth++;
|
|
116
|
+
else if (c === '}' || c === ']' || c === ')') depth--;
|
|
117
|
+
else if (depth === 1 && c === ':' && token) direct.add(token);
|
|
118
|
+
if (/[\w'"-]/.test(c)) token += c === "'" || c === '"' ? '' : c;
|
|
119
|
+
else if (!/\s/.test(c)) token = '';
|
|
120
|
+
}
|
|
121
|
+
const keys = ['colors', 'borderRadius', 'borderWidth', 'boxShadow', 'fontSize', 'fontFamily', 'height', 'spacing'];
|
|
122
|
+
return keys.filter((k) => direct.has(k));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Where `@/lib` points in this app (tsconfig paths), so lib/theme.ts lands where kit components import it. */
|
|
126
|
+
function libDir(root) {
|
|
127
|
+
try {
|
|
128
|
+
const tsconfig = JSON.parse(readFileSync(join(root, 'tsconfig.json'), 'utf8').replace(/^\s*\/\/.*$/gm, ''));
|
|
129
|
+
const target = tsconfig.compilerOptions?.paths?.['@/*']?.[0];
|
|
130
|
+
if (typeof target === 'string') return posix.join(posix.normalize(target.replace(/\*$/, '') || '.'), 'lib');
|
|
131
|
+
} catch {
|
|
132
|
+
// no tsconfig, or not plain JSON: the usual place
|
|
133
|
+
}
|
|
134
|
+
return 'lib';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function readPackage(root) {
|
|
138
|
+
try {
|
|
139
|
+
return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
140
|
+
} catch {
|
|
141
|
+
return {};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function init({ root, flags, run }) {
|
|
146
|
+
const tokensPath = join(root, 'tokens/tokens.json');
|
|
147
|
+
const configPath = join(root, 'tokens/tokens.config.json');
|
|
148
|
+
const existing = [tokensPath, configPath].filter(existsSync);
|
|
149
|
+
if (existing.length && !flags.force) {
|
|
150
|
+
throw new InitError(
|
|
151
|
+
`already set up (${existing.map((p) => toPosix(relative(root, p))).join(', ')}). Use \`halftone-tokens build\` to rebuild, \`theme apply\` to re-brand, or --force to start again from Halftone's tokens.`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
const pkg = readPackage(root);
|
|
155
|
+
const platform = flags.platform === 'expo' || flags.platform === 'web' ? flags.platform : detectPlatform(pkg);
|
|
156
|
+
if (flags.platform && flags.platform !== platform) throw new InitError(`--platform is web or expo, not "${flags.platform}".`);
|
|
157
|
+
|
|
158
|
+
const candidates = platform === 'expo' ? STYLESHEETS_EXPO : STYLESHEETS;
|
|
159
|
+
const cssRel = typeof flags.css === 'string' ? toPosix(flags.css) : candidates.find((p) => existsSync(join(root, p)));
|
|
160
|
+
if (!cssRel) throw new InitError(`no stylesheet found (looked for ${candidates.join(', ')}). Pass the app's main CSS file: --css <path>.`);
|
|
161
|
+
const cssPath = join(root, cssRel);
|
|
162
|
+
if (!existsSync(cssPath)) throw new InitError(`${cssRel} does not exist.`);
|
|
163
|
+
|
|
164
|
+
const write = (config) => {
|
|
165
|
+
mkdirSync(dirname(tokensPath), { recursive: true });
|
|
166
|
+
writeFileSync(tokensPath, readFileSync(TEMPLATE, 'utf8'));
|
|
167
|
+
writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
|
|
168
|
+
console.log(`halftone-tokens init: ${platform === 'expo' ? 'an Expo app. ' : ''}wrote tokens/tokens.json and tokens/tokens.config.json`);
|
|
169
|
+
};
|
|
170
|
+
// theme apply writes the theme into tokens.json and rebuilds; otherwise build Halftone's own.
|
|
171
|
+
// --no-install: an Expo theme's font packages are printed, not installed (theme apply's own flag).
|
|
172
|
+
const build = () =>
|
|
173
|
+
typeof flags.theme === 'string'
|
|
174
|
+
? run(['theme', 'apply', flags.theme, '--root', root, ...(flags['no-install'] ? ['--no-install'] : [])])
|
|
175
|
+
: run(['build', '--root', root]);
|
|
176
|
+
const notes = platform === 'expo' ? await initExpo({ root, pkg, cssRel, cssPath, write, build }) : await initWeb({ cssRel, cssPath, write, build });
|
|
177
|
+
notes.push('Re-brand any time: `npx halftone-tokens theme apply <code|preset|file.halftone.json>`.');
|
|
178
|
+
console.log(`\nNext:\n${notes.map((n) => ` - ${n}`).join('\n')}`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function overrideNote(cssRel, css, what) {
|
|
182
|
+
const overrides = overridingRules(css);
|
|
183
|
+
return overrides.length
|
|
184
|
+
? [
|
|
185
|
+
`${cssRel} has rules that ${what} also defines, and they win over it. Delete them unless you mean to override the kit:\n` +
|
|
186
|
+
overrides.map((o) => ` line ${o.line}: ${o.name}`).join('\n'),
|
|
187
|
+
]
|
|
188
|
+
: [];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function initWeb({ cssRel, cssPath, write, build }) {
|
|
192
|
+
const outDir = posix.dirname(cssRel);
|
|
193
|
+
const tokensOut = posix.join(outDir, 'tokens.css');
|
|
194
|
+
const fontsOut = posix.join(outDir, 'fonts.css');
|
|
195
|
+
write({ source: 'tokens/tokens.json', targets: { 'shadcn-web': { out: tokensOut }, fonts: { platform: 'web', out: fontsOut } } });
|
|
196
|
+
await build();
|
|
197
|
+
|
|
198
|
+
const css = readFileSync(cssPath, 'utf8');
|
|
199
|
+
const wired = wireStylesheet(css, { tokens: importOf(cssRel, tokensOut), fonts: importOf(cssRel, fontsOut) });
|
|
200
|
+
if (wired.added.length) {
|
|
201
|
+
writeFileSync(cssPath, wired.css);
|
|
202
|
+
console.log(`halftone-tokens init: ${cssRel} now imports ${wired.added.join(' and ')}`);
|
|
203
|
+
}
|
|
204
|
+
const notes = [];
|
|
205
|
+
if (!/@import\s+['"]tailwindcss['"]/.test(css)) notes.push(`${cssRel} has no \`@import 'tailwindcss'\`: kit components need Tailwind 4.`);
|
|
206
|
+
if (!/@import\s+['"]tw-animate-css['"]/.test(css)) notes.push(`Kit components animate with tw-animate-css: \`npm install tw-animate-css\`, then add \`@import 'tw-animate-css';\` after tailwindcss in ${cssRel}.`);
|
|
207
|
+
notes.push(...overrideNote(cssRel, wired.css, 'tokens.css'));
|
|
208
|
+
notes.push('Dark mode is a `.dark` class on <html> (next-themes with attribute="class", or your own code).');
|
|
209
|
+
return notes;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function initExpo({ root, pkg, cssRel, cssPath, write, build }) {
|
|
213
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
214
|
+
const lib = libDir(root);
|
|
215
|
+
const tokensOut = 'tokens/generated/tokens.css';
|
|
216
|
+
const presetOut = 'tokens/generated/tailwind.preset.js';
|
|
217
|
+
// The navigation theme (NAV_THEME in lib/theme.ts) from wherever this app's React Navigation comes.
|
|
218
|
+
const navTheme = deps['@react-navigation/native'] ? '@react-navigation/native' : deps['expo-router'] ? 'expo-router/react-navigation' : false;
|
|
219
|
+
write({
|
|
220
|
+
source: 'tokens/tokens.json',
|
|
221
|
+
targets: {
|
|
222
|
+
nativewind3: { css: tokensOut, partial: true, preset: presetOut },
|
|
223
|
+
'ts-theme': { out: posix.join(lib, 'theme.ts'), navTheme },
|
|
224
|
+
fonts: { platform: 'expo', out: posix.join(lib, 'fonts.ts') },
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
await build();
|
|
228
|
+
|
|
229
|
+
const notes = [];
|
|
230
|
+
// global.css: the variables first. Tailwind's build (which NativeWind runs) inlines a local @import, so they reach native.
|
|
231
|
+
const css = readFileSync(cssPath, 'utf8');
|
|
232
|
+
const spec = importOf(cssRel, tokensOut);
|
|
233
|
+
const wired = new RegExp(`@import\\s+['"]${spec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`).test(css) ? css : `@import '${spec}';\n${css}`;
|
|
234
|
+
if (wired !== css) {
|
|
235
|
+
writeFileSync(cssPath, wired);
|
|
236
|
+
console.log(`halftone-tokens init: ${cssRel} now imports ${spec} (first, before @tailwind base)`);
|
|
237
|
+
}
|
|
238
|
+
notes.push(...overrideNote(cssRel, wired, 'tokens/generated/tokens.css'));
|
|
239
|
+
|
|
240
|
+
// tailwind.config.js: the preset, one line.
|
|
241
|
+
const configRel = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.ts'].find((f) => existsSync(join(root, f)));
|
|
242
|
+
const presetSpec = `./${presetOut.replace(/\.js$/, '')}`;
|
|
243
|
+
if (!configRel) {
|
|
244
|
+
notes.push(`No tailwind.config.js found. NativeWind needs one; list the kit's preset in it: \`presets: [require('nativewind/preset'), require('${presetSpec}')]\`.`);
|
|
245
|
+
} else {
|
|
246
|
+
const config = readFileSync(join(root, configRel), 'utf8');
|
|
247
|
+
const next = wirePreset(config, presetSpec);
|
|
248
|
+
if (next === null) notes.push(`Add the kit's preset to ${configRel}: \`presets: [require('nativewind/preset'), require('${presetSpec}')]\`.`);
|
|
249
|
+
else if (next !== config) {
|
|
250
|
+
writeFileSync(join(root, configRel), next);
|
|
251
|
+
console.log(`halftone-tokens init: ${configRel} now uses the kit's preset (${presetSpec})`);
|
|
252
|
+
}
|
|
253
|
+
const own = overridingExtends(config);
|
|
254
|
+
if (own.length) {
|
|
255
|
+
notes.push(
|
|
256
|
+
`${configRel} extends ${own.join(', ')} itself, and those win over the kit's preset. Delete them from theme.extend unless you mean to override the kit (the kit's preset maps the same CSS variables, and more).`
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
notes.push(`At the root: wrap the app in \`KitThemeProvider\` (\`npx shadcn@latest add @halftone-native/lib-theme-context\`) and load the theme's fonts with \`useFonts(FONT_ASSETS)\` from \`${posix.join(lib, 'fonts')}\` (expo-font).`);
|
|
262
|
+
notes.push(`After each \`npx shadcn add\`, run \`npx halftone-tokens build\`: the registry brings ${posix.join(lib, 'theme.ts')} and ${posix.join(lib, 'fonts.ts')} with Halftone's default brand, and the build puts yours back.`);
|
|
263
|
+
return notes;
|
|
264
|
+
}
|