@halftone-ds/tokens 1.4.0 → 1.6.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.
@@ -0,0 +1,87 @@
1
+ /**
2
+ * halftone-tokens import <tokens.json> — a brand's own tokens into a Halftone system file.
3
+ *
4
+ * --name <name> the system's name (default: the brand folder's name, or the file's)
5
+ * --out <file> where to write it (default: <name>.halftone.json in the current folder)
6
+ * --google "A,B" families that are on Google Fonts beyond the curated list (others stay in tokens)
7
+ * --offline don't ask Google Fonts about the file's other families (then only --google counts)
8
+ * --force replace --out when it exists
9
+ * --json print { file, system, notes, warnings } instead of the summary
10
+ *
11
+ * It never touches an app's tokens: `halftone-tokens theme apply ./<name>.halftone.json` does that, on purpose.
12
+ * The contrast warnings come from a dry run on the package's default tokens.json.
13
+ */
14
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
15
+ import { basename, dirname, join, resolve } from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { generateSystem } from './system/generate.mjs';
18
+ import { fontFamiliesToCheck, systemFromTokens } from './system/import.mjs';
19
+
20
+ const here = dirname(fileURLToPath(import.meta.url));
21
+ const GENERIC_FOLDERS = new Set(['identity', 'tokens', 'design', 'src', 'styles', '.']);
22
+
23
+ function fail(message, code = 1) {
24
+ console.error(`halftone-tokens import: ${message}`);
25
+ process.exit(code);
26
+ }
27
+
28
+ /** brands/lisbon-tag/identity/tokens.json → "lisbon-tag"; acme.tokens.json → "acme". */
29
+ function nameFromPath(file) {
30
+ const base = basename(file).replace(/\.json$/i, '').replace(/\.?tokens$/i, '');
31
+ if (base) return base;
32
+ let dir = dirname(resolve(file));
33
+ while (GENERIC_FOLDERS.has(basename(dir)) && dirname(dir) !== dir) dir = dirname(dir);
34
+ return basename(dir);
35
+ }
36
+
37
+ const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'brand';
38
+
39
+ /** Does Google Fonts serve this family? Its CSS API answers 200 for a family it has and 400 for one it doesn't. */
40
+ async function onGoogleFonts(family) {
41
+ try {
42
+ const res = await fetch(`https://fonts.googleapis.com/css2?family=${encodeURIComponent(family).replace(/%20/g, '+')}`, { signal: AbortSignal.timeout(10000) });
43
+ return res.ok;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ export async function importCommand({ root, flags, positional }) {
50
+ const file = positional[0];
51
+ if (!file) fail('say which file: halftone-tokens import <tokens.json> [--name <name>] [--out <file>] [--google "A,B"]', 2);
52
+ const path = resolve(root, file);
53
+ if (!existsSync(path)) fail(`no file at ${path}`, 2);
54
+ let dtcg;
55
+ try {
56
+ dtcg = JSON.parse(readFileSync(path, 'utf8'));
57
+ } catch (error) {
58
+ fail(`${file} isn't JSON: ${error.message}`, 2);
59
+ }
60
+
61
+ const name = typeof flags.name === 'string' ? flags.name : nameFromPath(path);
62
+ const google = typeof flags.google === 'string' ? flags.google.split(',').map((f) => f.trim()).filter(Boolean) : [];
63
+ if (!flags.offline) for (const family of fontFamiliesToCheck(dtcg)) if (!google.includes(family) && (await onGoogleFonts(family))) google.push(family);
64
+ const { system, notes } = systemFromTokens(dtcg, { name, google });
65
+
66
+ const base = JSON.parse(readFileSync(join(here, '../templates/tokens.json'), 'utf8'));
67
+ const { warnings } = generateSystem(system, base);
68
+
69
+ const out = resolve(root, typeof flags.out === 'string' ? flags.out : `${slug(name)}.halftone.json`);
70
+ if (existsSync(out) && !flags.force) fail(`${out} exists; pass --force to replace it`, 2);
71
+ writeFileSync(out, `${JSON.stringify(system, null, 2)}\n`);
72
+
73
+ if (flags.json) {
74
+ console.log(JSON.stringify({ file: out, system, notes, warnings }, null, 2));
75
+ return;
76
+ }
77
+ console.log(`Wrote ${out}: "${system.name}".`);
78
+ if (notes.length) {
79
+ console.log('\nWhat it guessed or couldn\'t map (check each one):');
80
+ for (const note of notes) console.log(` - ${note}`);
81
+ }
82
+ if (warnings?.length) {
83
+ console.log('\nBelow WCAG AA with the brand\'s own colours (kept as they are; change them in the Studio if you want AA):');
84
+ for (const w of warnings) console.log(` ${w.mode.padEnd(5)} ${w.label.padEnd(40)} ${w.ratio}:1 (needs ${w.threshold})`);
85
+ }
86
+ console.log(`\nNext: in an app, halftone-tokens theme apply ./${basename(out)}`);
87
+ }
package/lib/init.mjs CHANGED
@@ -100,11 +100,26 @@ export function wirePreset(config, presetSpec) {
100
100
  return config.replace(re, (m, q) => `presets: [require(${q}nativewind/preset${q}), require(${q}${presetSpec}${q})]`);
101
101
  }
102
102
 
103
- /** Theme keys the app's own tailwind.config.js extends; they win over the preset's. */
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
+ */
104
107
  export function overridingExtends(config) {
105
- const extend = /extend\s*:\s*\{([\s\S]*)/.exec(config)?.[1] ?? '';
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
+ }
106
121
  const keys = ['colors', 'borderRadius', 'borderWidth', 'boxShadow', 'fontSize', 'fontFamily', 'height', 'spacing'];
107
- return keys.filter((k) => new RegExp(`\\b${k}\\s*:`).test(extend));
122
+ return keys.filter((k) => direct.has(k));
108
123
  }
109
124
 
110
125
  /** Where `@/lib` points in this app (tsconfig paths), so lib/theme.ts lands where kit components import it. */
package/lib/resolve.mjs CHANGED
@@ -8,6 +8,7 @@ import { readFileSync } from 'node:fs';
8
8
  import { componentLayer, readComponents } from './theme/components.mjs';
9
9
  import { rampsOf } from './theme/generate.mjs';
10
10
  import { extraList } from './theme/extras.mjs';
11
+ import { DURATION_NAMES, EASING_NAMES, MOTION_DEFAULTS, SPRING_KEYS, SPRING_NAMES } from './theme/motion.mjs';
11
12
  import { isDerived, semanticColors, TINT_ROLES } from './theme/semantic.mjs';
12
13
  import { BUTTON, DEFAULT_RECIPE, DENSITY, DEPTH, FIELD, fieldWidth, resolveTextStyles, shadowCss, textEdits, TYPE, typeScale } from './theme/recipe.mjs';
13
14
 
@@ -171,7 +172,23 @@ export async function loadTokens(sourcePath) {
171
172
  const styles = { button: recorded.button ?? DEFAULT_RECIPE.button, field: recorded.field ?? DEFAULT_RECIPE.field };
172
173
  const extras = extraList(source.extra);
173
174
  const components = loadComponents({ source, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, recorded });
174
- return { source, semLight, semDark, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, extras, components };
175
+ const motion = motionOf(prim);
176
+ return { source, semLight, semDark, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, extras, components, motion };
177
+ }
178
+
179
+ /**
180
+ * Durations (ms), easings (cubic-bezier) and springs from primitive.duration, .easing and .spring. A file from before
181
+ * motion was themed (no springs) gets the kits' defaults for what it lacks.
182
+ */
183
+ function motionOf(prim) {
184
+ const value = (path) => prim.find((t) => t.path.join('.') === path)?.$value;
185
+ return {
186
+ durations: Object.fromEntries(DURATION_NAMES.map((n) => [n, value(`primitive.duration.${n}`) ?? MOTION_DEFAULTS.durations[n]])),
187
+ easings: Object.fromEntries(EASING_NAMES.map((n) => [n, value(`primitive.easing.${n}`) ?? MOTION_DEFAULTS.easings[n]])),
188
+ springs: Object.fromEntries(
189
+ SPRING_NAMES.map((n) => [n, Object.fromEntries(SPRING_KEYS.map((k) => [k, value(`primitive.spring.${n}.${k}`) ?? MOTION_DEFAULTS.springs[n][k]]))])
190
+ ),
191
+ };
175
192
  }
176
193
 
177
194
  /** The component layer from the file, or (a file from before it) the defaults on the file's colours and shape. */
@@ -11,11 +11,13 @@
11
11
  * 5. fonts, radius, shadow and border overrides
12
12
  * 6. extras, as the `extra` token group (theme.extra)
13
13
  * 7. the component layer (semantic.component.<name>), with the system's `components` edits on top
14
+ * 8. motion: the recipe's speed, with the system's set durations, easings and springs on top
14
15
  *
15
16
  * A system with no overrides is exactly generateTheme(doc.recipe, base) (a test holds it to that).
16
17
  * The theme's `code` is its recipe's: a lossy handle when the system has overrides (systemCode says so).
17
18
  */
18
19
  import { encodeRecipe } from '../theme/codec.mjs';
20
+ import { motionFor } from '../theme/motion.mjs';
19
21
  import { generateTheme, withComponents } from '../theme/generate.mjs';
20
22
  import { STEPS } from '../theme/palettes.mjs';
21
23
  import { anchorStep, brandRamp, neutralAnchorStep, neutralRamp, neutralSeedRamp } from '../theme/ramp.mjs';
@@ -201,8 +203,10 @@ export function generateSystem(input, base, { fix = true } = {}) {
201
203
  }
202
204
  // 6. Extras.
203
205
  const extra = extraTokens(doc);
206
+ // 8. Motion.
207
+ const motion = motionFor(recipe.speed, doc.motion);
204
208
  // 7. The component layer again, on the edited corners, border and text styles, with the system's own component edits.
205
- return withComponents({ ...theme, semantic, fonts, borderWidth, field, ...(extra ? { extra } : {}) }, base, doc.components);
209
+ return withComponents({ ...theme, semantic, fonts, borderWidth, field, motion, ...(extra ? { extra } : {}) }, base, doc.components);
206
210
  }
207
211
 
208
212
  /** The ht- code for a system with no overrides; null when one would be lost (a code holds only the recipe). */