@halftone-ds/tokens 1.3.2 → 1.4.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 CHANGED
@@ -6,12 +6,34 @@ and every build checks the palette against WCAG AA.
6
6
 
7
7
  ```bash
8
8
  npm install -D @halftone-ds/tokens
9
+ npx halftone-tokens init # set up an existing app, web or Expo (below)
9
10
  npx halftone-tokens build # write every output in tokens/tokens.config.json
10
11
  npx halftone-tokens check # write nothing; exit 1 if an output is stale (CI)
11
12
  npx halftone-tokens build --strict # fail on contrast instead of warning (or HALFTONE_STRICT=1)
12
13
  npx halftone-tokens figma # mirror the tokens into Figma Variables
13
14
  ```
14
15
 
16
+ ## Starting in an existing app
17
+
18
+ ```bash
19
+ npx halftone-tokens init [--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--force]
20
+ ```
21
+
22
+ For any React app on Tailwind 4 and shadcn (Next.js, Vite, React Router…). It writes `tokens/tokens.json`
23
+ (Halftone's brand) and a `tokens/tokens.config.json`, applies `--theme` if you give one, and builds `tokens.css`
24
+ and `fonts.css` next to the app's main stylesheet (it looks for `app/globals.css`, `src/index.css`, `src/app.css`
25
+ and a few more, or takes `--css`). Then it adds `@import './fonts.css'` at the top of that stylesheet and
26
+ `@import './tokens.css'` after Tailwind, and names any `:root`, `.dark`, `@theme`, `@layer base` or `body` rules
27
+ there that would override the kit, without deleting them. It refuses to replace existing tokens without `--force`.
28
+
29
+ In an Expo app on NativeWind (`expo` and `nativewind` in `package.json`, or `--platform expo`) it builds
30
+ `tokens/generated/tokens.css`, imported first by `global.css` (Tailwind's build inlines it, so it reaches native),
31
+ and `tokens/generated/tailwind.preset.js`, which it adds to `tailwind.config.js` next to `nativewind/preset` (or
32
+ prints the line, if the config has another shape). `lib/theme.ts` and `lib/fonts.ts` land where the app's `@/lib`
33
+ points. A theme with its own fonts installs their `@expo-google-fonts` packages (`--no-install` prints the command
34
+ instead). After each `npx shadcn add`, run `npx halftone-tokens build`: the registry brings `lib/theme.ts` and
35
+ `lib/fonts.ts` with Halftone's default brand.
36
+
15
37
  ## Inputs
16
38
 
17
39
  - `tokens/tokens.json`: `primitive` ramps and scales, and `semantic.color.<name>` with a `{ light, dark }`
@@ -24,7 +46,7 @@ npx halftone-tokens figma # mirror the tokens into Figma Variables
24
46
  "source": "tokens/tokens.json",
25
47
  "scan": ["app", "components"],
26
48
  "targets": {
27
- "nativewind3": { "css": "global.css", "tailwind": "tokens/generated/tailwind.theme.js" },
49
+ "nativewind3": { "css": "tokens/generated/tokens.css", "partial": true, "preset": "tokens/generated/tailwind.preset.js" },
28
50
  "ts-theme": { "out": "lib/theme.ts", "navTheme": "expo-router/react-navigation" },
29
51
  "shadcn-web": { "out": "app/tokens.css" },
30
52
  "design-md": { "out": "DESIGN.md", "name": "My Kit" }
@@ -38,13 +60,14 @@ npx halftone-tokens figma # mirror the tokens into Figma Variables
38
60
 
39
61
  | Target | Writes |
40
62
  |---|---|
41
- | `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind colour + radius map |
63
+ | `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind theme extension: `css` + `tailwind` (the whole stylesheet and a map to spread), or `css` + `partial: true` + `preset` (variables only, imported first by the app's `global.css`, and a Tailwind preset) |
42
64
  | `shadcn-web` | Tailwind 4 / shadcn v4 CSS: oklch variables in `:root` + `.dark`, `@theme inline`, base layer |
43
65
  | `ts-theme` | `THEME` (hex per scheme), `TOKENS` (space, radius, type, motion) and an optional React Navigation theme |
44
66
  | `registry-theme` | the theme as shadcn registry `cssVars`, native and web |
45
67
  | `design-md` | a [DESIGN.md](https://github.com/google-labs-code/design.md) (spec alpha) |
46
68
  | `llms` | a tokens section for `llms.txt` |
47
69
  | `figma` | the input `halftone-tokens figma` pushes to Figma Variables |
70
+ | `fonts` | the theme's fonts as loading code: `platform: 'expo'` (expo-google-fonts), `'next'` (next/font) or `'web'` (a Google Fonts `@import` and `--kit-font-*`, imported first in the app's stylesheet) |
48
71
 
49
72
  ## Themes
50
73
 
@@ -101,12 +124,19 @@ npx halftone-tokens theme encode ./acme.halftone.json # its ht- code, when it h
101
124
  tracking is em on every platform, so on native it scales with the style's size (NativeWind's own `tracking-*`
102
125
  are fixed px there: `tracking-tight` is -0.25px). `themeVars` carries the styles to live previews
103
126
  (`textStyleVars`, `themeTextStyles`).
104
- - Every theme writes a component layer, `semantic.component.<button|chip|badge|input>`: a corner, heights and
105
- padding, a text style and each variant's fill, label, border and pressed colours (references to semantic
106
- colours). Both kits read it as `--button-*`, `--chip-*`, `--badge-*` and `--field-*` (`bg-button-primary-bg`,
107
- `rounded-chip`, `h-button-md`, `text-type-button` in nativewind3; `type-button` and the same colours in
108
- shadcn-web), so a Button looks the same in both. A system's `components` sets any of it (roles by name, a
109
- Foundations corner or px). The build's contrast gate checks every variant's label on its fill.
127
+ - Every theme writes a component layer, `semantic.component.<button|chip|badge|input>`: a corner, a border width,
128
+ heights per size step (Badge S/M, the others S/M/L), padding and the icon gap, a text style with its weight and
129
+ case, an icon size, a shadow and focus ring (Button, Input), Input's placeholder, and each variant's fill, label,
130
+ border and pressed colours (references to semantic colours). Both kits read it as `--button-*`, `--chip-*`,
131
+ `--badge-*` and `--field-*` (`bg-button-primary-bg`, `rounded-chip`, `h-button-md`, `gap-button-gap`,
132
+ `text-type-button` in nativewind3; `type-button` and the same colours in shadcn-web), so a Button looks the same
133
+ in both. A system's `components` sets any of it (roles by name, a Foundations corner or px, `COMPONENTS[name].props`
134
+ lists what each has); until it does, every property draws what the kits always drew, and the icon size and shadow
135
+ (where the kits differed) are one value for both: `ICON_DEFAULT`, `defaultShadow`. The build's contrast gate
136
+ checks every variant's label on its fill and Input's placeholder.
137
+ - Component colours come from the ramps: a default drawn at partial opacity becomes the ramp step nearest to what it
138
+ drew, and a derived hover/pressed colour is the next step of the fill's ramp away from the page whose label still
139
+ reads at AA. Only the focus rings' halos are see-through.
110
140
 
111
141
  From code (`@halftone-ds/tokens/system`, also in `/theme`, browser-safe): `normalizeSystem` / `validateSystem`,
112
142
  `createSystem`, `migrate(recipe | code, brand)` and `systemToRecipe`, `generateSystem(system, tokens)` (the same
package/cli.mjs CHANGED
@@ -2,11 +2,13 @@
2
2
  /**
3
3
  * halftone-tokens — turns tokens/tokens.json into everything an app reads.
4
4
  *
5
+ * halftone-tokens init set up tokens in an existing app, web or Expo (see lib/init.mjs)
5
6
  * halftone-tokens build resolve, check contrast, write every target in tokens.config.json
6
7
  * halftone-tokens check same, but write nothing; exit 1 if any generated file is stale (CI)
7
8
  * halftone-tokens figma mirror the tokens into Figma Variables (see push-figma.mjs)
8
9
  * halftone-tokens theme apply, show or list themes (see lib/theme-cli.mjs)
9
10
  * halftone-tokens --version
11
+ * halftone-tokens --help (USAGE below)
10
12
  *
11
13
  * --root <dir> app root (default: cwd); every path in the config is relative to it
12
14
  * --config <file> default: tokens/tokens.config.json
@@ -22,14 +24,37 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from
22
24
  import { dirname, join, resolve } from 'node:path';
23
25
  import { fileURLToPath, pathToFileURL } from 'node:url';
24
26
 
25
- import { checkContrast, AA, componentFailures, describeTintLimits, textOnTintLimits } from './lib/contrast.mjs';
27
+ import { checkContrast, AA, componentFailures, describeSubtle, describeTintLimits, textOnSubtle, textOnTintLimits } from './lib/contrast.mjs';
26
28
  import { scanTintText } from './lib/scan.mjs';
27
29
  import { loadTokens } from './lib/resolve.mjs';
28
30
 
29
31
  const here = dirname(fileURLToPath(import.meta.url));
30
32
 
33
+ /** What `halftone-tokens --help` prints. Keep it in step with the comment at the top of this file. */
34
+ export const USAGE = `halftone-tokens: turns tokens/tokens.json into everything an app reads.
35
+
36
+ Usage: halftone-tokens <command> [options]
37
+
38
+ Commands:
39
+ init set up Halftone's tokens in an existing app (any React app, or Expo with NativeWind)
40
+ [--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--platform web|expo] [--force]
41
+ build resolve, check contrast, write every target in tokens.config.json (the default)
42
+ check the same, but write nothing; exit 1 if a generated file is stale (for CI)
43
+ theme apply, show or list themes: halftone-tokens theme apply <code|preset|file.halftone.json>
44
+ figma mirror the tokens into Figma Variables
45
+ --version print the version
46
+ --help print this
47
+
48
+ Options:
49
+ --root <dir> app root (default: the current folder); every path in the config is relative to it
50
+ --config <file> default: tokens/tokens.config.json
51
+ --strict fail on contrast below WCAG AA instead of warning (or HALFTONE_STRICT=1)
52
+
53
+ tokens.config.json: { "source": "tokens/tokens.json", "targets": { "<target>": { ...options } } }
54
+ Docs: https://halftonedesignsystem.com/install.md`;
55
+
31
56
  /** Flags that take a value; every other --flag is a boolean. */
32
- const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url']);
57
+ const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform']);
33
58
 
34
59
  function parseArgs(argv) {
35
60
  const [command = 'build', ...rest] = argv;
@@ -49,6 +74,10 @@ export async function run(argv = process.argv.slice(2)) {
49
74
  console.log(JSON.parse(readFileSync(join(here, 'package.json'), 'utf8')).version);
50
75
  return;
51
76
  }
77
+ if (command === '--help' || command === '-h' || command === 'help' || flags.help) {
78
+ console.log(USAGE);
79
+ return;
80
+ }
52
81
  const root = resolve(flags.root ?? process.cwd());
53
82
 
54
83
  if (command === 'figma') {
@@ -56,8 +85,12 @@ export async function run(argv = process.argv.slice(2)) {
56
85
  await import(pathToFileURL(join(here, 'push-figma.mjs')).href);
57
86
  return;
58
87
  }
88
+ if (command === 'init') {
89
+ const { initCommand } = await import('./lib/init.mjs');
90
+ return initCommand({ root, flags, positional, run });
91
+ }
59
92
  if (command !== 'build' && command !== 'check' && command !== 'theme') {
60
- console.error(`halftone-tokens: unknown command "${command}". Use build, check, theme or figma.`);
93
+ console.error(`halftone-tokens: unknown command "${command}". Use init, build, check, theme or figma (halftone-tokens --help for more).`);
61
94
  process.exit(2);
62
95
  }
63
96
 
@@ -107,13 +140,13 @@ export async function run(argv = process.argv.slice(2)) {
107
140
  // Then the source: a tone's text on its own tint, beyond what this palette allows.
108
141
  if (config.scan?.length) {
109
142
  const limits = textOnTintLimits(ctx.colors);
110
- const problems = scanTintText(root, config.scan, limits);
143
+ const problems = scanTintText(root, config.scan, limits, textOnSubtle(ctx.colors));
111
144
  if (problems.length) {
112
145
  gate(
113
146
  'halftone-tokens',
114
147
  `${problems.length} class string(s) put a tone's text on its own tint below WCAG AA (${AA}:1):\n\n${problems.join('\n')}\n\n` +
115
- `This palette allows: ${describeTintLimits(limits)}.\n` +
116
- 'Use text-foreground on the tint (let the tint, an icon or a dot carry the colour), or a lighter tint.\n' +
148
+ `This palette allows: ${describeTintLimits(limits)} on an alpha tint; tone text on its own -subtle tint: ${describeSubtle(textOnSubtle(ctx.colors))}.\n` +
149
+ 'Use text-foreground on the tint (let the tint, an icon or a dot carry the colour).\n' +
117
150
  'An element that holds only an icon may keep its tone: add a `halftone-tokens-ignore tint-text` comment.\n'
118
151
  );
119
152
  }
package/lib/contrast.mjs CHANGED
@@ -10,7 +10,7 @@ import { componentPairs } from './theme/components.mjs';
10
10
  export const AA = 4.5; // WCAG 2.1 AA, normal text. Kit labels are 16px — not "large text".
11
11
  export const AA_NON_TEXT = 3; // WCAG 1.4.11, icons and other meaningful non-text.
12
12
 
13
- /** The alpha values the kit actually tints with (bg-<tone>/10 etc). */
13
+ /** The alpha tints a token file from before the tint roles (bg-<tone>/10 etc) is checked at. */
14
14
  const TINTS = [0.1, 0.15, 0.2];
15
15
  /** Tones that get used as ink — text-<tone> and coloured icons — not just as fills. */
16
16
  export const TONES = ['primary', 'success', 'warning', 'info', 'destructive'];
@@ -20,7 +20,8 @@ export const TONES = ['primary', 'success', 'warning', 'info', 'destructive'];
20
20
  * 1. a fill and its own -foreground label
21
21
  * 2. body and muted text on each surface
22
22
  * 3. a tone used as INK — text-<tone> and coloured icons — on the page and on a card
23
- * 4. a tone's icon sitting on that same tone's tint, as Alert and IconCircle do
23
+ * 4. a tone's icon sitting on that same tone's tint (`<tone>-subtle`), as Alert and IconCircle do
24
+ * 5. body and muted text on a tint (`<tone>-subtle`, `muted-subtle`), and a label on its pressed fill
24
25
  *
25
26
  * 3 and 4 are the ones that matter most for a re-brand: a colour can be a perfectly good
26
27
  * fill and still be unreadable as text, which is exactly how an amber warning gets in.
@@ -62,13 +63,30 @@ export function contrastPairs(hex, mode, { strict = false, fg: only } = {}) {
62
63
  }
63
64
  }
64
65
 
65
- // A tone's icon on that tone's own tint — Alert, IconCircle, SwipeToConfirm.
66
+ // A tone's icon on that tone's own tint — Alert, IconCircle, SwipeToConfirm. A token file from before the tint
67
+ // roles tinted with an alpha (bg-<tone>/15): that blend over the page.
66
68
  for (const tone of TONES) {
67
- if (!hex[tone] || !hex.background) continue;
68
- for (const alpha of TINTS) {
69
- add(`${tone} icon on ${tone}/${alpha * 100}`, tone, `${tone}/${alpha * 100}`, hex[tone], blend(hex[tone], hex.background, alpha), AA_NON_TEXT);
69
+ if (!hex[tone]) continue;
70
+ const tint = `${tone}-subtle`;
71
+ if (hex[tint]) add(`${tone} icon on ${tint}`, tone, tint, hex[tone], hex[tint], AA_NON_TEXT);
72
+ else if (hex.background) {
73
+ for (const alpha of TINTS) {
74
+ add(`${tone} icon on ${tone}/${alpha * 100}`, tone, `${tone}/${alpha * 100}`, hex[tone], blend(hex[tone], hex.background, alpha), AA_NON_TEXT);
75
+ }
70
76
  }
71
77
  }
78
+
79
+ // Text on a tint: an Alert's title and description, a selected card, a promo.
80
+ for (const tint of [...TONES.map((tone) => `${tone}-subtle`), 'muted-subtle']) {
81
+ if (!hex[tint]) continue;
82
+ for (const ink of ['foreground', 'muted-foreground']) if (hex[ink]) add(`${ink} on ${tint}`, ink, tint, hex[ink], hex[tint], AA);
83
+ }
84
+ // A pressed fill keeps its label.
85
+ for (const name of ['primary', 'secondary']) {
86
+ const fill = `${name}-pressed`;
87
+ const fg = `${name}-foreground`;
88
+ if (hex[fill] && hex[fg]) add(`${fg} on ${fill}`, fg, fill, hex[fg], hex[fill], AA);
89
+ }
72
90
  return out;
73
91
  }
74
92
 
@@ -115,6 +133,32 @@ export function textOnTintLimits(colors) {
115
133
  return limits;
116
134
  }
117
135
 
136
+ /**
137
+ * Which tones' TEXT reads on that tone's own tint role (`text-success` on `bg-success-subtle`) in both themes:
138
+ * `{ primary: false, info: true, … }`. A tone without the role (a token file from before it) is left out.
139
+ */
140
+ export function textOnSubtle(colors) {
141
+ const modes = ['light', 'dark'].map((mode) => Object.fromEntries(colors.map((c) => [c.name, c[mode]])));
142
+ const out = {};
143
+ for (const tone of TONES) {
144
+ if (!modes.every((hex) => hex[tone] && hex[`${tone}-subtle`])) continue;
145
+ out[tone] = modes.every((hex) => contrast(hex[tone], hex[`${tone}-subtle`]) >= AA);
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /** `{ primary: false, success: true, info: true }` → "success and info" (the tones whose text reads on their own -subtle). */
151
+ export const describeSubtle = (subtle) => {
152
+ const ok = Object.entries(subtle).filter(([, reads]) => reads).map(([tone]) => tone);
153
+ return ok.length ? ok.join(', ').replace(/, ([^,]+)$/, ' and $1') : 'none';
154
+ };
155
+
156
+ /** One sentence for the generated guides: where a tone's own text may sit on its tint. */
157
+ export const subtleLine = (subtle) =>
158
+ Object.keys(subtle).length
159
+ ? `With this palette a tone's own text clears AA on its tint (\`text-success\` on \`bg-success-subtle\`) for ${describeSubtle(subtle) === 'none' ? 'no tone' : `${describeSubtle(subtle)} only`}.`
160
+ : '';
161
+
118
162
  /** `{ primary: 0.05, destructive: 0 }` → "primary up to /5, destructive never". */
119
163
  export const describeTintLimits = (limits) =>
120
164
  Object.entries(limits)
package/lib/init.mjs ADDED
@@ -0,0 +1,249 @@
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
+ /** Theme keys the app's own tailwind.config.js extends; they win over the preset's. */
104
+ export function overridingExtends(config) {
105
+ const extend = /extend\s*:\s*\{([\s\S]*)/.exec(config)?.[1] ?? '';
106
+ const keys = ['colors', 'borderRadius', 'borderWidth', 'boxShadow', 'fontSize', 'fontFamily', 'height', 'spacing'];
107
+ return keys.filter((k) => new RegExp(`\\b${k}\\s*:`).test(extend));
108
+ }
109
+
110
+ /** Where `@/lib` points in this app (tsconfig paths), so lib/theme.ts lands where kit components import it. */
111
+ function libDir(root) {
112
+ try {
113
+ const tsconfig = JSON.parse(readFileSync(join(root, 'tsconfig.json'), 'utf8').replace(/^\s*\/\/.*$/gm, ''));
114
+ const target = tsconfig.compilerOptions?.paths?.['@/*']?.[0];
115
+ if (typeof target === 'string') return posix.join(posix.normalize(target.replace(/\*$/, '') || '.'), 'lib');
116
+ } catch {
117
+ // no tsconfig, or not plain JSON: the usual place
118
+ }
119
+ return 'lib';
120
+ }
121
+
122
+ function readPackage(root) {
123
+ try {
124
+ return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
125
+ } catch {
126
+ return {};
127
+ }
128
+ }
129
+
130
+ async function init({ root, flags, run }) {
131
+ const tokensPath = join(root, 'tokens/tokens.json');
132
+ const configPath = join(root, 'tokens/tokens.config.json');
133
+ const existing = [tokensPath, configPath].filter(existsSync);
134
+ if (existing.length && !flags.force) {
135
+ throw new InitError(
136
+ `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.`
137
+ );
138
+ }
139
+ const pkg = readPackage(root);
140
+ const platform = flags.platform === 'expo' || flags.platform === 'web' ? flags.platform : detectPlatform(pkg);
141
+ if (flags.platform && flags.platform !== platform) throw new InitError(`--platform is web or expo, not "${flags.platform}".`);
142
+
143
+ const candidates = platform === 'expo' ? STYLESHEETS_EXPO : STYLESHEETS;
144
+ const cssRel = typeof flags.css === 'string' ? toPosix(flags.css) : candidates.find((p) => existsSync(join(root, p)));
145
+ if (!cssRel) throw new InitError(`no stylesheet found (looked for ${candidates.join(', ')}). Pass the app's main CSS file: --css <path>.`);
146
+ const cssPath = join(root, cssRel);
147
+ if (!existsSync(cssPath)) throw new InitError(`${cssRel} does not exist.`);
148
+
149
+ const write = (config) => {
150
+ mkdirSync(dirname(tokensPath), { recursive: true });
151
+ writeFileSync(tokensPath, readFileSync(TEMPLATE, 'utf8'));
152
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
153
+ console.log(`halftone-tokens init: ${platform === 'expo' ? 'an Expo app. ' : ''}wrote tokens/tokens.json and tokens/tokens.config.json`);
154
+ };
155
+ // theme apply writes the theme into tokens.json and rebuilds; otherwise build Halftone's own.
156
+ // --no-install: an Expo theme's font packages are printed, not installed (theme apply's own flag).
157
+ const build = () =>
158
+ typeof flags.theme === 'string'
159
+ ? run(['theme', 'apply', flags.theme, '--root', root, ...(flags['no-install'] ? ['--no-install'] : [])])
160
+ : run(['build', '--root', root]);
161
+ const notes = platform === 'expo' ? await initExpo({ root, pkg, cssRel, cssPath, write, build }) : await initWeb({ cssRel, cssPath, write, build });
162
+ notes.push('Re-brand any time: `npx halftone-tokens theme apply <code|preset|file.halftone.json>`.');
163
+ console.log(`\nNext:\n${notes.map((n) => ` - ${n}`).join('\n')}`);
164
+ }
165
+
166
+ function overrideNote(cssRel, css, what) {
167
+ const overrides = overridingRules(css);
168
+ return overrides.length
169
+ ? [
170
+ `${cssRel} has rules that ${what} also defines, and they win over it. Delete them unless you mean to override the kit:\n` +
171
+ overrides.map((o) => ` line ${o.line}: ${o.name}`).join('\n'),
172
+ ]
173
+ : [];
174
+ }
175
+
176
+ async function initWeb({ cssRel, cssPath, write, build }) {
177
+ const outDir = posix.dirname(cssRel);
178
+ const tokensOut = posix.join(outDir, 'tokens.css');
179
+ const fontsOut = posix.join(outDir, 'fonts.css');
180
+ write({ source: 'tokens/tokens.json', targets: { 'shadcn-web': { out: tokensOut }, fonts: { platform: 'web', out: fontsOut } } });
181
+ await build();
182
+
183
+ const css = readFileSync(cssPath, 'utf8');
184
+ const wired = wireStylesheet(css, { tokens: importOf(cssRel, tokensOut), fonts: importOf(cssRel, fontsOut) });
185
+ if (wired.added.length) {
186
+ writeFileSync(cssPath, wired.css);
187
+ console.log(`halftone-tokens init: ${cssRel} now imports ${wired.added.join(' and ')}`);
188
+ }
189
+ const notes = [];
190
+ if (!/@import\s+['"]tailwindcss['"]/.test(css)) notes.push(`${cssRel} has no \`@import 'tailwindcss'\`: kit components need Tailwind 4.`);
191
+ 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}.`);
192
+ notes.push(...overrideNote(cssRel, wired.css, 'tokens.css'));
193
+ notes.push('Dark mode is a `.dark` class on <html> (next-themes with attribute="class", or your own code).');
194
+ return notes;
195
+ }
196
+
197
+ async function initExpo({ root, pkg, cssRel, cssPath, write, build }) {
198
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
199
+ const lib = libDir(root);
200
+ const tokensOut = 'tokens/generated/tokens.css';
201
+ const presetOut = 'tokens/generated/tailwind.preset.js';
202
+ // The navigation theme (NAV_THEME in lib/theme.ts) from wherever this app's React Navigation comes.
203
+ const navTheme = deps['@react-navigation/native'] ? '@react-navigation/native' : deps['expo-router'] ? 'expo-router/react-navigation' : false;
204
+ write({
205
+ source: 'tokens/tokens.json',
206
+ targets: {
207
+ nativewind3: { css: tokensOut, partial: true, preset: presetOut },
208
+ 'ts-theme': { out: posix.join(lib, 'theme.ts'), navTheme },
209
+ fonts: { platform: 'expo', out: posix.join(lib, 'fonts.ts') },
210
+ },
211
+ });
212
+ await build();
213
+
214
+ const notes = [];
215
+ // global.css: the variables first. Tailwind's build (which NativeWind runs) inlines a local @import, so they reach native.
216
+ const css = readFileSync(cssPath, 'utf8');
217
+ const spec = importOf(cssRel, tokensOut);
218
+ const wired = new RegExp(`@import\\s+['"]${spec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`).test(css) ? css : `@import '${spec}';\n${css}`;
219
+ if (wired !== css) {
220
+ writeFileSync(cssPath, wired);
221
+ console.log(`halftone-tokens init: ${cssRel} now imports ${spec} (first, before @tailwind base)`);
222
+ }
223
+ notes.push(...overrideNote(cssRel, wired, 'tokens/generated/tokens.css'));
224
+
225
+ // tailwind.config.js: the preset, one line.
226
+ const configRel = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.ts'].find((f) => existsSync(join(root, f)));
227
+ const presetSpec = `./${presetOut.replace(/\.js$/, '')}`;
228
+ if (!configRel) {
229
+ notes.push(`No tailwind.config.js found. NativeWind needs one; list the kit's preset in it: \`presets: [require('nativewind/preset'), require('${presetSpec}')]\`.`);
230
+ } else {
231
+ const config = readFileSync(join(root, configRel), 'utf8');
232
+ const next = wirePreset(config, presetSpec);
233
+ if (next === null) notes.push(`Add the kit's preset to ${configRel}: \`presets: [require('nativewind/preset'), require('${presetSpec}')]\`.`);
234
+ else if (next !== config) {
235
+ writeFileSync(join(root, configRel), next);
236
+ console.log(`halftone-tokens init: ${configRel} now uses the kit's preset (${presetSpec})`);
237
+ }
238
+ const own = overridingExtends(config);
239
+ if (own.length) {
240
+ notes.push(
241
+ `${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).`
242
+ );
243
+ }
244
+ }
245
+
246
+ 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).`);
247
+ 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.`);
248
+ return notes;
249
+ }
package/lib/resolve.mjs CHANGED
@@ -6,7 +6,9 @@
6
6
  import StyleDictionary from 'style-dictionary';
7
7
  import { readFileSync } from 'node:fs';
8
8
  import { componentLayer, readComponents } from './theme/components.mjs';
9
+ import { rampsOf } from './theme/generate.mjs';
9
10
  import { extraList } from './theme/extras.mjs';
11
+ import { isDerived, semanticColors, TINT_ROLES } from './theme/semantic.mjs';
10
12
  import { BUTTON, DEFAULT_RECIPE, DENSITY, DEPTH, FIELD, fieldWidth, resolveTextStyles, shadowCss, textEdits, TYPE, typeScale } from './theme/recipe.mjs';
11
13
 
12
14
  export const MODES = ['light', 'dark'];
@@ -123,6 +125,15 @@ export async function loadTokens(sourcePath) {
123
125
  const byName = Object.fromEntries(colors.map((c) => [c.name, c]));
124
126
  const STYLE_FALLBACK = { button: 'primary', 'button-foreground': 'primary-foreground', 'button-edge': 'primary', field: 'input', 'field-edge': 'input' };
125
127
  for (const [name, from] of Object.entries(STYLE_FALLBACK)) if (!byName[name] && byName[from]) colors.push({ ...byName[from], name });
128
+ // The tints and pressed fills a token file from before them doesn't have: the theme's steps on the file's ramps.
129
+ const primHex = Object.fromEntries(prim.filter(isColor).map((t) => [t.path.join('.'), t.$value.toLowerCase()]));
130
+ const brandStep = Object.keys(source.primitive?.color?.brand ?? {}).find((step) => primHex[`primitive.color.brand.${step}`] === byName.primary?.light);
131
+ const derived = semanticColors(brandStep ?? '600');
132
+ for (const [name, refs] of Object.entries(derived)) {
133
+ if (byName[name] || !isDerived(name) && !TINT_ROLES.includes(name)) continue;
134
+ const hex = (mode) => primHex[refs[mode].slice(1, -1)];
135
+ if (hex('light') && hex('dark')) colors.push({ name, light: hex('light'), dark: hex('dark') });
136
+ }
126
137
  const shadows = (list, mode) =>
127
138
  Object.fromEntries(['1', '2', '3'].map((level) => [level, shadowCss(find(list, `shadow-${level}`) ?? DEPTH.soft[level][mode])]));
128
139
  const borderWidth = find(semLight, 'border-width') ?? 1;
@@ -166,7 +177,7 @@ export async function loadTokens(sourcePath) {
166
177
  /** The component layer from the file, or (a file from before it) the defaults on the file's colours and shape. */
167
178
  function loadComponents({ source, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, recorded }) {
168
179
  const flat = (list) => Object.fromEntries(list.map((t) => [t.path.join('.'), t.$value]));
169
- const read = readComponents(flat(compLight), flat(compDark), source.semantic?.component);
180
+ const read = readComponents(flat(compLight), flat(compDark), source.semantic?.component, { borderWidth: shape.borderWidth });
170
181
  if (read) return read;
171
182
  const byName = Object.fromEntries(colors.map((c) => [c.name, c]));
172
183
  const primMap = Object.fromEntries(prim.map((t) => [t.path.join('.'), t.$value]));
@@ -185,6 +196,7 @@ function loadComponents({ source, compLight, compDark, prim, colors, radius, sha
185
196
  const name = /^\{semantic\.color\.(.+)\}$/.exec(ref)?.[1];
186
197
  return String(name ? byName[name]?.[mode] : primMap[ref.slice(1, -1)]).toLowerCase();
187
198
  },
199
+ ramps: rampsOf(source.primitive?.color ?? {}, (path) => String(primMap[path]).toLowerCase()),
188
200
  }).shape;
189
201
  }
190
202
 
package/lib/scan.mjs CHANGED
@@ -2,9 +2,10 @@
2
2
  * Source scan: a tone's text on that tone's own tint, beyond what the palette allows.
3
3
  *
4
4
  * The contrast gate proves the palette's pairings; it cannot see how components combine classes.
5
- * `bg-success/15 text-success` looks deliberate and fails AA (4.09:1 with the default palette), so this
6
- * reads every class string in the configured folders and flags that combination wherever the tint is
7
- * stronger than `textOnTintLimits` allows. Only unprefixed classes count (`hover:bg-…` is another state).
5
+ * `bg-success-subtle text-success` looks deliberate and can fail AA, so this reads every class string in the
6
+ * configured folders and flags that combination wherever the palette can't carry it: on a tint role when
7
+ * `textOnSubtle` says no, on an alpha tint (`bg-success/15`) stronger than `textOnTintLimits` allows. Only
8
+ * unprefixed classes count (`hover:bg-…` is another state).
8
9
  *
9
10
  * An element that holds only an icon may keep its tone (icons need 3:1, which the gate checks): put
10
11
  * `halftone-tokens-ignore tint-text` in a comment on that line or the line above.
@@ -31,8 +32,11 @@ function files(dir) {
31
32
  return out;
32
33
  }
33
34
 
34
- /** Returns one line per offending class string: `components/x.tsx:12 text-success on bg-success/15 (allowed: up to /5)`. */
35
- export function scanTintText(root, paths, limits) {
35
+ /**
36
+ * Returns one line per offending class string: `components/x.tsx:12 text-success on bg-success/15 (allowed: up to /5)`.
37
+ * `limits` from textOnTintLimits, `subtle` from textOnSubtle.
38
+ */
39
+ export function scanTintText(root, paths, limits, subtle = {}) {
36
40
  const problems = [];
37
41
  for (const path of paths) {
38
42
  let list;
@@ -49,15 +53,15 @@ export function scanTintText(root, paths, limits) {
49
53
  const texts = new Set(classes.map((c) => /^text-([a-z]+)$/.exec(c)?.[1]).filter((t) => TONES.includes(t)));
50
54
  if (!texts.size) continue;
51
55
  for (const c of classes) {
56
+ const role = /^bg-([a-z]+)-subtle$/.exec(c);
52
57
  const tint = /^bg-([a-z]+)\/(\d+)$/.exec(c);
53
- if (!tint || !texts.has(tint[1])) continue;
54
- const [, tone, pct] = tint;
55
- const alpha = Number(pct) / 100;
56
- if (alpha <= limits[tone]) continue;
58
+ const tone = (role ?? tint)?.[1];
59
+ if (!tone || !texts.has(tone)) continue;
60
+ if (role ? subtle[tone] !== false : Number(tint[2]) / 100 <= limits[tone]) continue;
57
61
  const lineNo = source.slice(0, m.index).split('\n').length;
58
62
  if (`${lines[lineNo - 1]}\n${lines[lineNo - 2] ?? ''}`.includes(PRAGMA)) continue;
59
- const allowed = limits[tone] ? `up to /${Math.round(limits[tone] * 100)}` : 'never';
60
- problems.push(` ${relative(root, file)}:${lineNo} text-${tone} on bg-${tone}/${pct} (allowed: ${allowed})`);
63
+ const allowed = role ? 'text-foreground on it' : limits[tone] ? `up to /${Math.round(limits[tone] * 100)}` : 'never';
64
+ problems.push(` ${relative(root, file)}:${lineNo} text-${tone} on ${c} (allowed: ${allowed})`);
61
65
  }
62
66
  }
63
67
  }
@@ -82,9 +82,21 @@ export type ComponentEdit = {
82
82
  style?: string;
83
83
  /** A Foundations corner, or px. */
84
84
  radius?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full' | number;
85
- size?: Partial<Record<'sm' | 'md' | 'lg' | 'x', number>>;
85
+ /** Border width (px). */
86
+ border?: number;
87
+ /** Heights per step, then the padding and icon gap every step shares (px). */
88
+ size?: Partial<Record<'sm' | 'md' | 'lg' | 'x' | 'gap', number>>;
86
89
  /** A text style (h1…blockquote). */
87
90
  text?: string;
91
+ weight?: 400 | 500 | 600 | 700;
92
+ case?: 'none' | 'uppercase';
93
+ /** Icon size (px). */
94
+ icon?: number;
95
+ shadow?: 'none' | '1' | '2' | '3';
96
+ /** The focus ring: width (px) and a role. */
97
+ ring?: { width?: number; role?: string };
98
+ /** Input: the placeholder's role. */
99
+ placeholder?: string;
88
100
  variants?: Record<string, Partial<Record<'fill' | 'label' | 'border' | 'pressed', string>>>;
89
101
  };
90
102
  export type SystemComponents = Partial<Record<'button' | 'chip' | 'badge' | 'input', ComponentEdit>>;