@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 CHANGED
@@ -6,12 +6,57 @@ 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)
10
+ npx halftone-tokens doctor # check the app's setup for kit components; says how to fix each problem
9
11
  npx halftone-tokens build # write every output in tokens/tokens.config.json
10
12
  npx halftone-tokens check # write nothing; exit 1 if an output is stale (CI)
11
13
  npx halftone-tokens build --strict # fail on contrast instead of warning (or HALFTONE_STRICT=1)
12
14
  npx halftone-tokens figma # mirror the tokens into Figma Variables
13
15
  ```
14
16
 
17
+ ## Starting in an existing app
18
+
19
+ ```bash
20
+ npx halftone-tokens init [--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--force]
21
+ ```
22
+
23
+ For any React app on Tailwind 4 and shadcn (Next.js, Vite, React Router…). It writes `tokens/tokens.json`
24
+ (Halftone's brand) and a `tokens/tokens.config.json`, applies `--theme` if you give one, and builds `tokens.css`
25
+ and `fonts.css` next to the app's main stylesheet (it looks for `app/globals.css`, `src/index.css`, `src/app.css`
26
+ and a few more, or takes `--css`). Then it adds `@import './fonts.css'` at the top of that stylesheet and
27
+ `@import './tokens.css'` after Tailwind, and names any `:root`, `.dark`, `@theme`, `@layer base` or `body` rules
28
+ there that would override the kit, without deleting them. It refuses to replace existing tokens without `--force`.
29
+
30
+ In an Expo app on NativeWind (`expo` and `nativewind` in `package.json`, or `--platform expo`) it builds
31
+ `tokens/generated/tokens.css`, imported first by `global.css` (Tailwind's build inlines it, so it reaches native),
32
+ and `tokens/generated/tailwind.preset.js`, which it adds to `tailwind.config.js` next to `nativewind/preset` (or
33
+ prints the line, if the config has another shape). `lib/theme.ts` and `lib/fonts.ts` land where the app's `@/lib`
34
+ points. A theme with its own fonts installs their `@expo-google-fonts` packages (`--no-install` prints the command
35
+ instead). After each `npx shadcn add`, run `npx halftone-tokens build`: the registry brings `lib/theme.ts` and
36
+ `lib/fonts.ts` with Halftone's default brand.
37
+
38
+ ## Checking an app
39
+
40
+ ```bash
41
+ npx halftone-tokens doctor [--platform web|expo] [--offline] [--json]
42
+ ```
43
+
44
+ Read-only. It checks what kit components need and prints a fix for each problem (exit 1 if there is one):
45
+
46
+ - the tokens are set up and every generated file is up to date (after a `shadcn add` in an Expo app, `lib/theme.ts`
47
+ and `lib/fonts.ts` are not);
48
+ - the stylesheet imports `tokens.css` after Tailwind and `fonts.css` first (web), or `global.css` imports the
49
+ tokens first and `tailwind.config.js` uses the kit's preset (Expo);
50
+ - `components.json` is on the new-york style, and the `@/` aliases resolve in `tsconfig.json` (and `vite.config.ts`);
51
+ - no kit file in `components/ui` has been replaced by shadcn's or react-native-reusables' stock version: it compares
52
+ each one with the kit's registry (the URL in `components.json`) and the upstream one, ignoring the imports shadcn
53
+ rewrites. `--offline` skips this.
54
+
55
+ It warns, without failing, about rules in the app's own CSS or Tailwind config that win over the kit's, nothing
56
+ setting the `.dark` class, kit links without `KitLinkProvider`, an Expo app without `KitThemeProvider` or
57
+ `useFonts(FONT_ASSETS)`, and a `lib/utils.ts` with its own `cn` (clsx + tailwind-merge) next to the `cn` package
58
+ that kit and shadcn files import. `--json` prints `{ ok, results: [{ level, message, fix }] }` for an agent or CI.
59
+
15
60
  ## Inputs
16
61
 
17
62
  - `tokens/tokens.json`: `primitive` ramps and scales, and `semantic.color.<name>` with a `{ light, dark }`
@@ -24,7 +69,7 @@ npx halftone-tokens figma # mirror the tokens into Figma Variables
24
69
  "source": "tokens/tokens.json",
25
70
  "scan": ["app", "components"],
26
71
  "targets": {
27
- "nativewind3": { "css": "global.css", "tailwind": "tokens/generated/tailwind.theme.js" },
72
+ "nativewind3": { "css": "tokens/generated/tokens.css", "partial": true, "preset": "tokens/generated/tailwind.preset.js" },
28
73
  "ts-theme": { "out": "lib/theme.ts", "navTheme": "expo-router/react-navigation" },
29
74
  "shadcn-web": { "out": "app/tokens.css" },
30
75
  "design-md": { "out": "DESIGN.md", "name": "My Kit" }
@@ -38,13 +83,14 @@ npx halftone-tokens figma # mirror the tokens into Figma Variables
38
83
 
39
84
  | Target | Writes |
40
85
  |---|---|
41
- | `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind colour + radius map |
42
- | `shadcn-web` | Tailwind 4 / shadcn v4 CSS: oklch variables in `:root` + `.dark`, `@theme inline`, base layer |
43
- | `ts-theme` | `THEME` (hex per scheme), `TOKENS` (space, radius, type, motion) and an optional React Navigation theme |
86
+ | `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind theme extension (`duration-fast`, `ease-standard`… included): `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) |
87
+ | `shadcn-web` | Tailwind 4 / shadcn v4 CSS: oklch variables in `:root` + `.dark`, `@theme inline`, base layer; motion as `--duration-*`, `--ease-*` and `--spring-*` (a `linear()` easing and its duration), with `duration-*`, `ease-*` and `spring-*` classes |
88
+ | `ts-theme` | `THEME` (hex per scheme), `TOKENS` (space, radius, type, motion), `MOTION` (durations, easings and springs, typed for Motion and Reanimated) and an optional React Navigation theme |
44
89
  | `registry-theme` | the theme as shadcn registry `cssVars`, native and web |
45
90
  | `design-md` | a [DESIGN.md](https://github.com/google-labs-code/design.md) (spec alpha) |
46
91
  | `llms` | a tokens section for `llms.txt` |
47
- | `figma` | the input `halftone-tokens figma` pushes to Figma Variables |
92
+ | `figma` | the input `halftone-tokens figma` pushes to Figma Variables (durations included; easings and springs have no variable type) |
93
+ | `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
94
 
49
95
  ## Themes
50
96
 
@@ -101,12 +147,19 @@ npx halftone-tokens theme encode ./acme.halftone.json # its ht- code, when it h
101
147
  tracking is em on every platform, so on native it scales with the style's size (NativeWind's own `tracking-*`
102
148
  are fixed px there: `tracking-tight` is -0.25px). `themeVars` carries the styles to live previews
103
149
  (`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.
150
+ - Every theme writes a component layer, `semantic.component.<button|chip|badge|input>`: a corner, a border width,
151
+ heights per size step (Badge S/M, the others S/M/L), padding and the icon gap, a text style with its weight and
152
+ case, an icon size, a shadow and focus ring (Button, Input), Input's placeholder, and each variant's fill, label,
153
+ border and pressed colours (references to semantic colours). Both kits read it as `--button-*`, `--chip-*`,
154
+ `--badge-*` and `--field-*` (`bg-button-primary-bg`, `rounded-chip`, `h-button-md`, `gap-button-gap`,
155
+ `text-type-button` in nativewind3; `type-button` and the same colours in shadcn-web), so a Button looks the same
156
+ in both. A system's `components` sets any of it (roles by name, a Foundations corner or px, `COMPONENTS[name].props`
157
+ lists what each has); until it does, every property draws what the kits always drew, and the icon size and shadow
158
+ (where the kits differed) are one value for both: `ICON_DEFAULT`, `defaultShadow`. The build's contrast gate
159
+ checks every variant's label on its fill and Input's placeholder.
160
+ - Component colours come from the ramps: a default drawn at partial opacity becomes the ramp step nearest to what it
161
+ drew, and a derived hover/pressed colour is the next step of the fill's ramp away from the page whose label still
162
+ reads at AA. Only the focus rings' halos are see-through.
110
163
 
111
164
  From code (`@halftone-ds/tokens/system`, also in `/theme`, browser-safe): `normalizeSystem` / `validateSystem`,
112
165
  `createSystem`, `migrate(recipe | code, brand)` and `systemToRecipe`, `generateSystem(system, tokens)` (the same
package/cli.mjs CHANGED
@@ -2,11 +2,14 @@
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)
6
+ * halftone-tokens doctor check an app's setup for kit components and say how to fix it (see lib/doctor.mjs)
5
7
  * halftone-tokens build resolve, check contrast, write every target in tokens.config.json
6
8
  * halftone-tokens check same, but write nothing; exit 1 if any generated file is stale (CI)
7
9
  * halftone-tokens figma mirror the tokens into Figma Variables (see push-figma.mjs)
8
10
  * halftone-tokens theme apply, show or list themes (see lib/theme-cli.mjs)
9
11
  * halftone-tokens --version
12
+ * halftone-tokens --help (USAGE below)
10
13
  *
11
14
  * --root <dir> app root (default: cwd); every path in the config is relative to it
12
15
  * --config <file> default: tokens/tokens.config.json
@@ -22,14 +25,40 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from
22
25
  import { dirname, join, resolve } from 'node:path';
23
26
  import { fileURLToPath, pathToFileURL } from 'node:url';
24
27
 
25
- import { checkContrast, AA, componentFailures, describeTintLimits, textOnTintLimits } from './lib/contrast.mjs';
28
+ import { checkContrast, AA, componentFailures, describeSubtle, describeTintLimits, textOnSubtle, textOnTintLimits } from './lib/contrast.mjs';
29
+ import { loadContext, renderTargets } from './lib/generate.mjs';
26
30
  import { scanTintText } from './lib/scan.mjs';
27
- import { loadTokens } from './lib/resolve.mjs';
28
31
 
29
32
  const here = dirname(fileURLToPath(import.meta.url));
30
33
 
34
+ /** What `halftone-tokens --help` prints. Keep it in step with the comment at the top of this file. */
35
+ export const USAGE = `halftone-tokens: turns tokens/tokens.json into everything an app reads.
36
+
37
+ Usage: halftone-tokens <command> [options]
38
+
39
+ Commands:
40
+ init set up Halftone's tokens in an existing app (any React app, or Expo with NativeWind)
41
+ [--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--platform web|expo] [--force]
42
+ doctor check the app's setup for kit components (tokens, stylesheet, aliases, stock files that
43
+ replaced kit ones, dark mode, links) and say how to fix each; exit 1 on a problem
44
+ [--platform web|expo] [--offline] [--json]
45
+ build resolve, check contrast, write every target in tokens.config.json (the default)
46
+ check the same, but write nothing; exit 1 if a generated file is stale (for CI)
47
+ theme apply, show or list themes: halftone-tokens theme apply <code|preset|file.halftone.json>
48
+ figma mirror the tokens into Figma Variables
49
+ --version print the version
50
+ --help print this
51
+
52
+ Options:
53
+ --root <dir> app root (default: the current folder); every path in the config is relative to it
54
+ --config <file> default: tokens/tokens.config.json
55
+ --strict fail on contrast below WCAG AA instead of warning (or HALFTONE_STRICT=1)
56
+
57
+ tokens.config.json: { "source": "tokens/tokens.json", "targets": { "<target>": { ...options } } }
58
+ Docs: https://halftonedesignsystem.com/install.md`;
59
+
31
60
  /** Flags that take a value; every other --flag is a boolean. */
32
- const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url']);
61
+ const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform']);
33
62
 
34
63
  function parseArgs(argv) {
35
64
  const [command = 'build', ...rest] = argv;
@@ -49,6 +78,10 @@ export async function run(argv = process.argv.slice(2)) {
49
78
  console.log(JSON.parse(readFileSync(join(here, 'package.json'), 'utf8')).version);
50
79
  return;
51
80
  }
81
+ if (command === '--help' || command === '-h' || command === 'help' || flags.help) {
82
+ console.log(USAGE);
83
+ return;
84
+ }
52
85
  const root = resolve(flags.root ?? process.cwd());
53
86
 
54
87
  if (command === 'figma') {
@@ -56,8 +89,16 @@ export async function run(argv = process.argv.slice(2)) {
56
89
  await import(pathToFileURL(join(here, 'push-figma.mjs')).href);
57
90
  return;
58
91
  }
92
+ if (command === 'doctor') {
93
+ const { doctorCommand } = await import('./lib/doctor.mjs');
94
+ return doctorCommand({ root, flags });
95
+ }
96
+ if (command === 'init') {
97
+ const { initCommand } = await import('./lib/init.mjs');
98
+ return initCommand({ root, flags, positional, run });
99
+ }
59
100
  if (command !== 'build' && command !== 'check' && command !== 'theme') {
60
- console.error(`halftone-tokens: unknown command "${command}". Use build, check, theme or figma.`);
101
+ console.error(`halftone-tokens: unknown command "${command}". Use init, doctor, build, check, theme or figma (halftone-tokens --help for more).`);
61
102
  process.exit(2);
62
103
  }
63
104
 
@@ -74,9 +115,7 @@ export async function run(argv = process.argv.slice(2)) {
74
115
  const rebuild = ['build', '--root', root, ...(flags.config ? ['--config', flags.config] : []), ...(flags.strict ? ['--strict'] : [])];
75
116
  return themeCommand({ positional, flags, root, sourcePath: join(root, source), config, build: () => run(rebuild) });
76
117
  }
77
- const ctx = await loadTokens(join(root, source));
78
- ctx.root = root;
79
- ctx.header = `GENERATED by \`npm run tokens:build\` from ${source} — do not edit by hand.`;
118
+ const ctx = await loadContext(root, source);
80
119
 
81
120
  // Contrast is checked on every build. By default a problem is a warning (the palette is the designer's
82
121
  // call); --strict or HALFTONE_STRICT=1 makes it an error, which is how Halftone's own CI builds the kits.
@@ -107,24 +146,20 @@ export async function run(argv = process.argv.slice(2)) {
107
146
  // Then the source: a tone's text on its own tint, beyond what this palette allows.
108
147
  if (config.scan?.length) {
109
148
  const limits = textOnTintLimits(ctx.colors);
110
- const problems = scanTintText(root, config.scan, limits);
149
+ const problems = scanTintText(root, config.scan, limits, textOnSubtle(ctx.colors));
111
150
  if (problems.length) {
112
151
  gate(
113
152
  'halftone-tokens',
114
153
  `${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' +
154
+ `This palette allows: ${describeTintLimits(limits)} on an alpha tint; tone text on its own -subtle tint: ${describeSubtle(textOnSubtle(ctx.colors))}.\n` +
155
+ 'Use text-foreground on the tint (let the tint, an icon or a dot carry the colour).\n' +
117
156
  'An element that holds only an icon may keep its tone: add a `halftone-tokens-ignore tint-text` comment.\n'
118
157
  );
119
158
  }
120
159
  }
121
160
  const contrast = warnings ? `${warnings} contrast warning(s), run with --strict to fail` : 'contrast AA ✓';
122
161
 
123
- const files = [];
124
- for (const [name, options] of Object.entries(config.targets ?? {})) {
125
- const { default: target } = await import(pathToFileURL(join(here, 'targets', `${name}.mjs`)).href);
126
- files.push(...(await target(ctx, options ?? {})));
127
- }
162
+ const files = await renderTargets(ctx, config);
128
163
 
129
164
  if (command === 'check') {
130
165
  const stale = files.filter((f) => {
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)