@halftone-ds/tokens 1.5.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.
- package/README.md +27 -2
- package/cli.mjs +10 -3
- package/lib/import-cli.mjs +87 -0
- package/lib/system/import.mjs +552 -0
- package/lib/system/index.d.mts +16 -0
- package/lib/system/index.mjs +1 -0
- package/lib/system/schema.mjs +24 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@ and every build checks the palette against WCAG AA.
|
|
|
8
8
|
npm install -D @halftone-ds/tokens
|
|
9
9
|
npx halftone-tokens init # set up an existing app, web or Expo (below)
|
|
10
10
|
npx halftone-tokens doctor # check the app's setup for kit components; says how to fix each problem
|
|
11
|
+
npx halftone-tokens import ./brand/tokens.json # a brand's own DTCG tokens into a system file (below)
|
|
11
12
|
npx halftone-tokens build # write every output in tokens/tokens.config.json
|
|
12
13
|
npx halftone-tokens check # write nothing; exit 1 if an output is stale (CI)
|
|
13
14
|
npx halftone-tokens build --strict # fail on contrast instead of warning (or HALFTONE_STRICT=1)
|
|
@@ -163,8 +164,32 @@ npx halftone-tokens theme encode ./acme.halftone.json # its ht- code, when it h
|
|
|
163
164
|
|
|
164
165
|
From code (`@halftone-ds/tokens/system`, also in `/theme`, browser-safe): `normalizeSystem` / `validateSystem`,
|
|
165
166
|
`createSystem`, `migrate(recipe | code, brand)` and `systemToRecipe`, `generateSystem(system, tokens)` (the same
|
|
166
|
-
shape as `generateTheme`, plus `warnings`), `systemRamps`, `textStyles`, `systemRadii`, `systemCode
|
|
167
|
-
`applySystem
|
|
167
|
+
shape as `generateTheme`, plus `warnings`), `systemRamps`, `textStyles`, `systemRadii`, `systemCode`,
|
|
168
|
+
`applySystem`, and `systemFromTokens` / `fontFamiliesToCheck` (the import, below). The document's shape is
|
|
169
|
+
described in `lib/system/schema.mjs`.
|
|
170
|
+
|
|
171
|
+
### Importing a brand's own tokens
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
npx halftone-tokens import ./brand/tokens.json --name "Acme" # writes acme.halftone.json
|
|
175
|
+
npx halftone-tokens import ./tokens.json --google "Lato" --offline --json # for an agent; no network
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
It reads any DTCG `tokens.json` (hex strings or 2025.10 colour objects, aliases, inherited `$type`) in the brand's own
|
|
179
|
+
words, and writes a system:
|
|
180
|
+
- **Colour sets:** the lightest page is light and the darkest is dark. A third set, or a colour no role takes, is an
|
|
181
|
+
extra colour. With no dark set, dark is generated.
|
|
182
|
+
- **Roles by name** (`background-secondary` → muted, `stroke` → border, `brand` → primary when there's no `primary`),
|
|
183
|
+
as the brand's exact hex: the fixer never moves them, so a pairing below AA is a warning. A "muted" that reads as
|
|
184
|
+
text on the page becomes `muted-foreground`. A see-through colour is mixed onto its page.
|
|
185
|
+
- **Ramps:** brand from primary, neutral and the statuses from a numbered family that holds their colour, its steps
|
|
186
|
+
kept.
|
|
187
|
+
- **Fonts** when the family is on Google Fonts (the CLI asks; `--offline` skips, `--google` vouches); others stay out.
|
|
188
|
+
**Corners and shadows** by name or by size.
|
|
189
|
+
- **Everything else** (spacing, a line weight, a grid) goes in the system's `tokens` section, whole: not drawn by the
|
|
190
|
+
kits, carried into `tokens.json`'s record. A system with it has no `ht-` code.
|
|
191
|
+
|
|
192
|
+
It prints one line per guess. Check them before `theme apply`.
|
|
168
193
|
|
|
169
194
|
## Guarantees
|
|
170
195
|
|
package/cli.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* halftone-tokens check same, but write nothing; exit 1 if any generated file is stale (CI)
|
|
9
9
|
* halftone-tokens figma mirror the tokens into Figma Variables (see push-figma.mjs)
|
|
10
10
|
* halftone-tokens theme apply, show or list themes (see lib/theme-cli.mjs)
|
|
11
|
+
* halftone-tokens import a brand's own tokens.json into a system file (see lib/import-cli.mjs)
|
|
11
12
|
* halftone-tokens --version
|
|
12
13
|
* halftone-tokens --help (USAGE below)
|
|
13
14
|
*
|
|
@@ -45,7 +46,9 @@ Commands:
|
|
|
45
46
|
build resolve, check contrast, write every target in tokens.config.json (the default)
|
|
46
47
|
check the same, but write nothing; exit 1 if a generated file is stale (for CI)
|
|
47
48
|
theme apply, show or list themes: halftone-tokens theme apply <code|preset|file.halftone.json>
|
|
48
|
-
|
|
49
|
+
import a brand's own tokens.json (DTCG) into a system file, and what it guessed:
|
|
50
|
+
halftone-tokens import <tokens.json> [--name <name>] [--out <file>] [--google "A,B"] [--offline] [--force] [--json]
|
|
51
|
+
figma mirror the tokens into Figma Variables
|
|
49
52
|
--version print the version
|
|
50
53
|
--help print this
|
|
51
54
|
|
|
@@ -58,7 +61,7 @@ tokens.config.json: { "source": "tokens/tokens.json", "targets": { "<target>": {
|
|
|
58
61
|
Docs: https://halftonedesignsystem.com/install.md`;
|
|
59
62
|
|
|
60
63
|
/** Flags that take a value; every other --flag is a boolean. */
|
|
61
|
-
const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform']);
|
|
64
|
+
const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform', 'name', 'google']);
|
|
62
65
|
|
|
63
66
|
function parseArgs(argv) {
|
|
64
67
|
const [command = 'build', ...rest] = argv;
|
|
@@ -97,8 +100,12 @@ export async function run(argv = process.argv.slice(2)) {
|
|
|
97
100
|
const { initCommand } = await import('./lib/init.mjs');
|
|
98
101
|
return initCommand({ root, flags, positional, run });
|
|
99
102
|
}
|
|
103
|
+
if (command === 'import') {
|
|
104
|
+
const { importCommand } = await import('./lib/import-cli.mjs');
|
|
105
|
+
return importCommand({ root, flags, positional });
|
|
106
|
+
}
|
|
100
107
|
if (command !== 'build' && command !== 'check' && command !== 'theme') {
|
|
101
|
-
console.error(`halftone-tokens: unknown command "${command}". Use init, doctor, build, check, theme or figma (halftone-tokens --help for more).`);
|
|
108
|
+
console.error(`halftone-tokens: unknown command "${command}". Use init, doctor, build, check, theme, import or figma (halftone-tokens --help for more).`);
|
|
102
109
|
process.exit(2);
|
|
103
110
|
}
|
|
104
111
|
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* import — a HalftoneSystem from a brand's own tokens.json (DTCG). Pure ESM with no Node APIs, so the Studio can
|
|
3
|
+
* run it in the browser too.
|
|
4
|
+
*
|
|
5
|
+
* systemFromTokens(dtcg, { name?, google? }) → { system, notes }
|
|
6
|
+
* dtcg a tokens.json object: hex strings or 2025.10 colour objects ({ colorSpace, components, hex }),
|
|
7
|
+
* {aliases}, $type inherited from groups
|
|
8
|
+
* google families known to be on Google Fonts beyond the curated list: an array, a Set or a function. A font
|
|
9
|
+
* not known to be there stays under `tokens` with a note, so a brand's own font file never becomes
|
|
10
|
+
* a family the kits try to load
|
|
11
|
+
* notes one plain line per guess or loss, written so an agent can ask the person about each one
|
|
12
|
+
*
|
|
13
|
+
* What it maps, in order:
|
|
14
|
+
* 1. Colour modes: groups of role colours (a `background` beside other colours). The lightest background is
|
|
15
|
+
* light; the darkest is dark when it is dark enough. Any other mode becomes extra colours. With no dark mode,
|
|
16
|
+
* the theme generates one from the ramps, as it does for every recipe.
|
|
17
|
+
* 2. Roles by name (ROLES below), as hex per mode, so the brand's colours stay exactly as they are: the contrast
|
|
18
|
+
* fixer never moves a colour mapped by hand, and names a failing pair instead. `primary` wins over `brand`
|
|
19
|
+
* and `accent`.
|
|
20
|
+
* 3. Ramp seeds: brand from primary; neutral and each status from a numbered palette family that holds the
|
|
21
|
+
* mode's colour, its steps kept as edited steps.
|
|
22
|
+
* 4. Every other colour in a mode, and every other palette family, as an extra colour.
|
|
23
|
+
* 5. Fonts, corner radii and shadows, by name.
|
|
24
|
+
* 6. Everything else under `tokens`, aliases resolved, unchanged otherwise.
|
|
25
|
+
*/
|
|
26
|
+
import { blend, contrast, hexToOklchParts, relativeLuminance } from '../color.mjs';
|
|
27
|
+
import { FONTS } from '../theme/fonts.mjs';
|
|
28
|
+
import { STEPS } from '../theme/palettes.mjs';
|
|
29
|
+
import { createSystem, extraNameProblem, RADIUS_STEPS } from './schema.mjs';
|
|
30
|
+
|
|
31
|
+
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
32
|
+
const norm = (key) =>
|
|
33
|
+
String(key)
|
|
34
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
37
|
+
.replace(/^-+|-+$/g, '');
|
|
38
|
+
const slug = (s) => norm(s).slice(0, 40).replace(/-+$/, '');
|
|
39
|
+
|
|
40
|
+
/** Each role the kits draw, and the names brands give it (normalised). The first is the role's own name. */
|
|
41
|
+
const ROLES = {
|
|
42
|
+
background: ['background', 'bg', 'page', 'canvas', 'surface', 'base', 'background-primary', 'bg-primary', 'background-default', 'surface-app', 'background-app', 'app'],
|
|
43
|
+
foreground: ['foreground', 'fg', 'text', 'ink', 'text-primary', 'foreground-primary', 'on-background', 'body'],
|
|
44
|
+
card: ['card', 'surface-raised', 'raised', 'panel', 'background-card', 'elevated', 'surface-panel', 'surface-card'],
|
|
45
|
+
'card-foreground': ['card-foreground', 'on-card', 'on-surface'],
|
|
46
|
+
muted: ['muted', 'background-secondary', 'bg-secondary', 'surface-secondary', 'background-muted', 'surface-muted', 'subtle'],
|
|
47
|
+
'muted-foreground': ['muted-foreground', 'foreground-secondary', 'text-secondary', 'text-muted', 'fg-muted', 'foreground-muted', 'secondary-text', 'ink-secondary', 'ink-muted'],
|
|
48
|
+
border: ['border', 'stroke', 'line', 'divider', 'outline', 'border-default', 'stroke-default'],
|
|
49
|
+
input: ['input', 'field-border', 'input-border'],
|
|
50
|
+
ring: ['ring', 'focus', 'focus-ring'],
|
|
51
|
+
primary: ['primary'],
|
|
52
|
+
'primary-foreground': ['primary-foreground', 'on-primary'],
|
|
53
|
+
destructive: ['destructive', 'danger', 'error', 'negative', 'critical'],
|
|
54
|
+
'destructive-foreground': ['destructive-foreground', 'on-destructive', 'on-danger', 'on-error'],
|
|
55
|
+
success: ['success', 'positive', 'ok'],
|
|
56
|
+
'success-foreground': ['success-foreground', 'on-success'],
|
|
57
|
+
warning: ['warning', 'caution', 'warn'],
|
|
58
|
+
'warning-foreground': ['warning-foreground', 'on-warning'],
|
|
59
|
+
info: ['info', 'informative', 'notice'],
|
|
60
|
+
'info-foreground': ['info-foreground', 'on-info'],
|
|
61
|
+
};
|
|
62
|
+
/** Used for primary only when the file has no `primary`: primary wins. */
|
|
63
|
+
const PRIMARY_FALLBACK = { primary: ['brand', 'accent', 'brand-primary'], 'primary-foreground': ['brand-foreground', 'on-brand', 'on-accent', 'accent-foreground'] };
|
|
64
|
+
const BACKGROUND = new Set(ROLES.background);
|
|
65
|
+
/** A status role and the ramp it seeds. */
|
|
66
|
+
const STATUS = { destructive: 'danger', success: 'success', warning: 'warning', info: 'info' };
|
|
67
|
+
const NEUTRAL_FAMILY = /^(neutral|neutrals|gray|grey|slate|zinc|stone|sand|base|mono)$/;
|
|
68
|
+
/** Darker than this, a background is a dark theme's page (navy #054895 is about 0.07, a near-black 0.01). */
|
|
69
|
+
const DARK_LUMINANCE = 0.18;
|
|
70
|
+
/** A group by one of these names is a mode, background or not. */
|
|
71
|
+
const MODE_NAMES = { light: 'light', day: 'light', dark: 'dark', night: 'dark' };
|
|
72
|
+
/**
|
|
73
|
+
* Brands use "muted" and "subtle" for a quiet surface and for quiet text alike. Halftone's `muted` is a surface,
|
|
74
|
+
* so a muted colour this far from the page (WCAG ratio) is text: it maps to muted-foreground instead.
|
|
75
|
+
*/
|
|
76
|
+
const TEXT_CONTRAST = 3;
|
|
77
|
+
const RAMP_KEYS = new Set([...STEPS, '0', '1000']);
|
|
78
|
+
|
|
79
|
+
const FONT_GROUP = /^(font|fonts|font-family|font-families|family|families|typeface|typefaces|typography)$/;
|
|
80
|
+
const FONT_ROLE = { heading: ['heading', 'headings', 'display', 'title', 'headline'], body: ['body', 'sans', 'text', 'base', 'ui', 'copy', 'paragraph', 'primary'], mono: ['mono', 'code', 'monospace'] };
|
|
81
|
+
/** Families every platform has: nothing to load, so nothing to set. */
|
|
82
|
+
const PLATFORM_FONTS = /^(system-ui|-apple-system|blinkmacsystemfont|sans-serif|serif|monospace|cursive|fantasy|ui-sans-serif|ui-serif|ui-monospace|ui-rounded|segoe ui|helvetica|helvetica neue|arial|georgia|times|times new roman|menlo|monaco|consolas|courier|courier new|sf mono|sf pro|sf pro text|sf pro display|iowan old style)$/i;
|
|
83
|
+
const RADIUS_GROUP = /^(radius|radii|corner|corners|rounded|rounding|border-radius|borderradius)$/;
|
|
84
|
+
const FULL_RADIUS = new Set(['full', 'pill', 'round', 'circle']);
|
|
85
|
+
|
|
86
|
+
/** Every token: { path: string[], key, type, value, node }. $type is inherited from groups. */
|
|
87
|
+
function leavesOf(root) {
|
|
88
|
+
const out = [];
|
|
89
|
+
const walk = (node, path, type) => {
|
|
90
|
+
for (const [key, child] of Object.entries(node)) {
|
|
91
|
+
if (key.startsWith('$') || !isObject(child)) continue;
|
|
92
|
+
const childType = child.$type ?? type;
|
|
93
|
+
if ('$value' in child) out.push({ path: [...path, key], key, type: childType, value: child.$value, node: child });
|
|
94
|
+
else walk(child, [...path, key], childType);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
walk(root, [], root.$type);
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A colour as { hex, alpha }, or null. */
|
|
102
|
+
function colorOf(value) {
|
|
103
|
+
if (typeof value === 'string') {
|
|
104
|
+
const m = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(value.trim());
|
|
105
|
+
if (!m) return null;
|
|
106
|
+
let h = m[1].toLowerCase();
|
|
107
|
+
if (h.length === 3) h = [...h].map((c) => c + c).join('');
|
|
108
|
+
return { hex: `#${h.slice(0, 6)}`, alpha: h.length === 8 ? Number((parseInt(h.slice(6), 16) / 255).toFixed(3)) : 1 };
|
|
109
|
+
}
|
|
110
|
+
if (isObject(value)) {
|
|
111
|
+
const alpha = typeof value.alpha === 'number' ? value.alpha : 1;
|
|
112
|
+
if (typeof value.hex === 'string') {
|
|
113
|
+
const c = colorOf(value.hex);
|
|
114
|
+
return c && { hex: c.hex, alpha };
|
|
115
|
+
}
|
|
116
|
+
if ((value.colorSpace === 'srgb' || value.colorSpace === undefined) && Array.isArray(value.components) && value.components.length === 3 && value.components.every((n) => typeof n === 'number')) {
|
|
117
|
+
const hex = '#' + value.components.map((n) => Math.round(Math.min(1, Math.max(0, n)) * 255).toString(16).padStart(2, '0')).join('');
|
|
118
|
+
return { hex, alpha };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** px from a dimension: 4, "4px", "0.25rem", { value, unit }. Null when it isn't one. */
|
|
125
|
+
function pxOf(value) {
|
|
126
|
+
if (typeof value === 'number') return value;
|
|
127
|
+
if (typeof value === 'string') {
|
|
128
|
+
const m = /^(-?[\d.]+)(px|rem|em)?$/.exec(value.trim());
|
|
129
|
+
return m ? Number(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1) : null;
|
|
130
|
+
}
|
|
131
|
+
if (isObject(value) && typeof value.value === 'number') return value.unit === 'rem' || value.unit === 'em' ? value.value * 16 : value.value;
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** An `is this family on Google Fonts` test: the curated list, plus whatever the caller knows. */
|
|
136
|
+
function googleTest(google) {
|
|
137
|
+
const curated = new Set(FONTS.filter((f) => !f.system).map((f) => f.family.toLowerCase()));
|
|
138
|
+
const extra = typeof google === 'function' ? google : (family) => new Set([...(google ?? [])].map((f) => String(f).toLowerCase())).has(family.toLowerCase());
|
|
139
|
+
return (family) => curated.has(family.toLowerCase()) || Boolean(extra(family));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The tokens, an index by path, and alias resolution: what every step reads. */
|
|
143
|
+
function context(input) {
|
|
144
|
+
const leaves = leavesOf(input);
|
|
145
|
+
const byPath = new Map(leaves.map((l) => [l.path.join('.'), l]));
|
|
146
|
+
const resolve = (value, seen = new Set()) => {
|
|
147
|
+
if (typeof value === 'string') {
|
|
148
|
+
const m = /^\{([^}]+)\}$/.exec(value);
|
|
149
|
+
if (!m) return value;
|
|
150
|
+
const target = byPath.get(m[1]);
|
|
151
|
+
if (!target || seen.has(m[1])) return value;
|
|
152
|
+
return resolve(target.value, new Set([...seen, m[1]]));
|
|
153
|
+
}
|
|
154
|
+
if (Array.isArray(value)) return value.map((v) => resolve(v, seen));
|
|
155
|
+
if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolve(v, seen)]));
|
|
156
|
+
return value;
|
|
157
|
+
};
|
|
158
|
+
const typeOf = (leaf, hops = 0) => {
|
|
159
|
+
if (leaf.type) return leaf.type;
|
|
160
|
+
const m = typeof leaf.value === 'string' && /^\{([^}]+)\}$/.exec(leaf.value);
|
|
161
|
+
const target = m && byPath.get(m[1]);
|
|
162
|
+
return target && hops < 16 ? typeOf(target, hops + 1) : undefined;
|
|
163
|
+
};
|
|
164
|
+
return { leaves, byPath, resolve, typeOf };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Each font token with a role: { leaf, role, family }. The family is the first in its stack, without " Variable". */
|
|
168
|
+
function fontTokens({ leaves, resolve, typeOf }) {
|
|
169
|
+
const out = [];
|
|
170
|
+
const roles = new Set();
|
|
171
|
+
for (const leaf of leaves) {
|
|
172
|
+
const type = typeOf(leaf);
|
|
173
|
+
const inGroup = leaf.path.slice(0, -1).some((p) => FONT_GROUP.test(norm(p)));
|
|
174
|
+
if (type !== 'fontFamily' && !(inGroup && !type)) continue;
|
|
175
|
+
const value = resolve(leaf.value);
|
|
176
|
+
const list = (Array.isArray(value) ? value : String(value).split(',')).map((f) => String(f).trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
|
|
177
|
+
const role = Object.entries(FONT_ROLE).find(([, names]) => names.includes(norm(leaf.key)))?.[0];
|
|
178
|
+
if (!role || roles.has(role) || !list.length) continue;
|
|
179
|
+
roles.add(role);
|
|
180
|
+
out.push({ leaf, role, family: list[0].replace(/ Variable$/i, '') });
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The font families a tokens file names that need checking: not the platform's own, not in the curated list.
|
|
187
|
+
* The CLI asks Google Fonts about these and passes the ones it has as `google`.
|
|
188
|
+
*/
|
|
189
|
+
export function fontFamiliesToCheck(input) {
|
|
190
|
+
if (!isObject(input)) return [];
|
|
191
|
+
const curated = googleTest([]);
|
|
192
|
+
return [...new Set(fontTokens(context(input)).map((f) => f.family))].filter((f) => !PLATFORM_FONTS.test(f) && !curated(f));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function systemFromTokens(input, { name, google } = {}) {
|
|
196
|
+
if (!isObject(input)) throw new Error('systemFromTokens: the tokens must be a JSON object');
|
|
197
|
+
const notes = [];
|
|
198
|
+
const ctx = context(input);
|
|
199
|
+
const { leaves, byPath, resolve, typeOf } = ctx;
|
|
200
|
+
const consumed = new Set();
|
|
201
|
+
const take = (leaf) => {
|
|
202
|
+
// A token that points at another (a role at a palette colour) uses that one up too.
|
|
203
|
+
for (let l = leaf, hops = 0; l && hops < 16; hops++) {
|
|
204
|
+
consumed.add(l.path.join('.'));
|
|
205
|
+
const m = typeof l.value === 'string' && /^\{([^}]+)\}$/.exec(l.value);
|
|
206
|
+
l = m ? byPath.get(m[1]) : null;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const colorLeaf = (leaf) => {
|
|
211
|
+
const type = typeOf(leaf);
|
|
212
|
+
if (type && type !== 'color') return null;
|
|
213
|
+
return colorOf(resolve(leaf.value));
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// 1. Colour modes. A group is a mode when it holds a background colour beside at least one other colour.
|
|
217
|
+
const groups = new Map();
|
|
218
|
+
for (const leaf of leaves) {
|
|
219
|
+
const c = colorLeaf(leaf);
|
|
220
|
+
if (!c) continue;
|
|
221
|
+
const parent = leaf.path.slice(0, -1).join('.');
|
|
222
|
+
if (!groups.has(parent)) groups.set(parent, { path: leaf.path.slice(0, -1), name: leaf.path.at(-2) ?? 'colors', colors: new Map() });
|
|
223
|
+
groups.get(parent).colors.set(norm(leaf.key), { ...c, leaf });
|
|
224
|
+
}
|
|
225
|
+
const hasBackground = (g) => [...g.colors.keys()].some((k) => BACKGROUND.has(k));
|
|
226
|
+
const modes = [...groups.values()].filter((g) => (g.colors.size >= 2 && hasBackground(g)) || (g.colors.size >= 3 && MODE_NAMES[norm(g.name)]));
|
|
227
|
+
// Halftone's own shape: one token per role, its value { light, dark }.
|
|
228
|
+
const moded = leaves.filter((l) => isObject(resolve(l.value)) && colorOf(resolve(l.value).light) && colorOf(resolve(l.value).dark));
|
|
229
|
+
if (moded.some((l) => BACKGROUND.has(norm(l.key)))) {
|
|
230
|
+
for (const mode of ['light', 'dark']) {
|
|
231
|
+
const colors = new Map(moded.map((l) => [norm(l.key), { ...colorOf(resolve(l.value)[mode]), leaf: l }]));
|
|
232
|
+
modes.push({ path: [], name: mode, colors, shared: true });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// The page colour: the background, else (a mode known by its name) the lightest or darkest colour in it.
|
|
236
|
+
const bgOf = (mode) => {
|
|
237
|
+
const named = [...mode.colors.entries()].find(([k]) => BACKGROUND.has(k));
|
|
238
|
+
if (named) return named[1].hex;
|
|
239
|
+
const sorted = [...mode.colors.values()].map((c) => c.hex).sort((a, b) => relativeLuminance(b) - relativeLuminance(a));
|
|
240
|
+
return MODE_NAMES[norm(mode.name)] === 'dark' ? sorted.at(-1) : sorted[0];
|
|
241
|
+
};
|
|
242
|
+
let light;
|
|
243
|
+
let dark;
|
|
244
|
+
// Named modes; where several groups share a name (a UI's light beside an icon set's light), the one with a page wins.
|
|
245
|
+
const byName = (which) => {
|
|
246
|
+
const all = modes.filter((m) => MODE_NAMES[norm(m.name)] === which);
|
|
247
|
+
const paged = all.filter(hasBackground);
|
|
248
|
+
return paged.length ? paged : all;
|
|
249
|
+
};
|
|
250
|
+
if (byName('light').length === 1 && byName('dark').length === 1) [light, dark] = [byName('light')[0], byName('dark')[0]];
|
|
251
|
+
else {
|
|
252
|
+
const byLight = [...modes].sort((a, b) => relativeLuminance(bgOf(b)) - relativeLuminance(bgOf(a)));
|
|
253
|
+
light = byLight[0];
|
|
254
|
+
const darkest = byLight.at(-1);
|
|
255
|
+
dark = darkest && darkest !== light && relativeLuminance(bgOf(darkest)) < DARK_LUMINANCE ? darkest : undefined;
|
|
256
|
+
}
|
|
257
|
+
const others = modes.filter((m) => m !== light && m !== dark);
|
|
258
|
+
if (light && light.name !== 'light') notes.push(`Light theme: "${light.name}" (its background ${bgOf(light)} is the lightest).`);
|
|
259
|
+
if (dark && dark.name !== 'dark') notes.push(`Dark theme: "${dark.name}" (its background ${bgOf(dark)} is the darkest).`);
|
|
260
|
+
for (const mode of [light, dark]) if (mode && !hasBackground(mode)) notes.push(`"${mode.name}" names no background, so the page colour is generated. Name one in the Studio if a colour in it is the page.`);
|
|
261
|
+
if (light && !dark) notes.push('No dark set of colours, so the dark theme is generated from the ramps. Check it in the Studio.');
|
|
262
|
+
if (!light) notes.push('No set of role colours (a background beside other colours) was found, so only the palette was used.');
|
|
263
|
+
|
|
264
|
+
// 2. Roles, per mode.
|
|
265
|
+
const roles = {};
|
|
266
|
+
const extraColors = [];
|
|
267
|
+
const takenNames = [];
|
|
268
|
+
const extraName = (raw) => {
|
|
269
|
+
const base = slug(raw) || 'colour';
|
|
270
|
+
for (const candidate of [base, `brand-${base}`, ...Array.from({ length: 8 }, (_, i) => `brand-${base}-${i + 2}`)]) {
|
|
271
|
+
const n = candidate.slice(0, 40);
|
|
272
|
+
if (!extraNameProblem('color', n, takenNames)) {
|
|
273
|
+
takenNames.push(n);
|
|
274
|
+
return n;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return null;
|
|
278
|
+
};
|
|
279
|
+
const opaque = (c, mode, label) => {
|
|
280
|
+
if (c.alpha >= 1) return c.hex;
|
|
281
|
+
const page = mode ? bgOf(mode) : '#ffffff';
|
|
282
|
+
notes.push(`"${label}" is ${Math.round(c.alpha * 100)}% opaque; Halftone draws no colour at partial opacity, so it is mixed onto ${page}.`);
|
|
283
|
+
return blend(c.hex, page, c.alpha);
|
|
284
|
+
};
|
|
285
|
+
const renamed = new Set();
|
|
286
|
+
const mapMode = (mode, which) => {
|
|
287
|
+
const used = new Set();
|
|
288
|
+
const page = hasBackground(mode) ? bgOf(mode) : null;
|
|
289
|
+
// A "muted" that reads as text against the page is muted text, not the muted surface.
|
|
290
|
+
const textual = new Set(ROLES.muted.filter((n) => page && mode.colors.has(n) && contrast(mode.colors.get(n).hex, page) >= TEXT_CONTRAST));
|
|
291
|
+
for (const [role, names] of Object.entries(ROLES)) {
|
|
292
|
+
const candidates = role === 'muted' ? names.filter((n) => !textual.has(n)) : role === 'muted-foreground' ? [...names, ...textual] : names;
|
|
293
|
+
let key = candidates.find((n) => mode.colors.has(n) && !used.has(n));
|
|
294
|
+
if (!key && PRIMARY_FALLBACK[role]) key = PRIMARY_FALLBACK[role].find((n) => mode.colors.has(n) && !used.has(n));
|
|
295
|
+
if (!key) continue;
|
|
296
|
+
used.add(key);
|
|
297
|
+
const c = mode.colors.get(key);
|
|
298
|
+
take(c.leaf);
|
|
299
|
+
(roles[role] ??= {})[which] = opaque(c, mode, c.leaf.path.join('.'));
|
|
300
|
+
if (key !== role && !renamed.has(`${key}>${role}`)) {
|
|
301
|
+
renamed.add(`${key}>${role}`);
|
|
302
|
+
const why = PRIMARY_FALLBACK[role]?.includes(key) ? ' (the file has no "primary")' : textual.has(key) ? ' (it reads as text on the page, so it is quiet text, not a surface)' : '';
|
|
303
|
+
notes.push(`"${key}" → ${role}${why}.`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return used;
|
|
307
|
+
};
|
|
308
|
+
const leftoverInModes = new Map();
|
|
309
|
+
for (const [mode, which] of [
|
|
310
|
+
[light, 'light'],
|
|
311
|
+
[dark, 'dark'],
|
|
312
|
+
]) {
|
|
313
|
+
if (!mode) continue;
|
|
314
|
+
const used = mapMode(mode, which);
|
|
315
|
+
for (const [key, c] of mode.colors) if (!used.has(key)) (leftoverInModes.get(key) ?? leftoverInModes.set(key, {}).get(key))[which] = { c, mode };
|
|
316
|
+
}
|
|
317
|
+
// Colours in a mode that no role took: one extra each, light and dark where both have it.
|
|
318
|
+
for (const [key, entry] of leftoverInModes) {
|
|
319
|
+
const n = extraName(key);
|
|
320
|
+
if (!n) continue;
|
|
321
|
+
const l = entry.light && opaque(entry.light.c, entry.light.mode, key);
|
|
322
|
+
const d = entry.dark && opaque(entry.dark.c, entry.dark.mode, key);
|
|
323
|
+
extraColors.push({ name: n, value: l && d ? { light: l, dark: d } : (l ?? d) });
|
|
324
|
+
for (const e of [entry.light, entry.dark]) if (e) take(e.c.leaf);
|
|
325
|
+
}
|
|
326
|
+
// Any other mode (Lisbon Tag's navy pages): its colours as extras, named after the mode.
|
|
327
|
+
for (const mode of others) {
|
|
328
|
+
const names = [];
|
|
329
|
+
// An icon set's "light" is named with its parent (icon-light), so it doesn't read as the theme's.
|
|
330
|
+
const label = MODE_NAMES[norm(mode.name)] && mode.path.length > 1 ? mode.path.slice(-2).join('-') : mode.name;
|
|
331
|
+
for (const [key, c] of mode.colors) {
|
|
332
|
+
const n = extraName(`${label}-${key}`);
|
|
333
|
+
if (!n) continue;
|
|
334
|
+
extraColors.push({ name: n, value: opaque(c, mode, `${mode.path.join('.')}.${key}`) });
|
|
335
|
+
take(c.leaf);
|
|
336
|
+
names.push(n);
|
|
337
|
+
}
|
|
338
|
+
notes.push(`"${mode.path.join('.') || mode.name}" is neither the light nor the dark theme (Halftone has those two), so its colours are extras: ${names.join(', ')}.`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 3. Ramps. A palette family is a group of numbered colour steps.
|
|
342
|
+
const families = [];
|
|
343
|
+
for (const g of groups.values()) {
|
|
344
|
+
const steps = {};
|
|
345
|
+
for (const [key, c] of g.colors) if (RAMP_KEYS.has(key)) steps[key] = c;
|
|
346
|
+
if (Object.keys(steps).filter((s) => STEPS.includes(s)).length >= 3) families.push({ name: g.name, path: g.path.join('.'), steps });
|
|
347
|
+
}
|
|
348
|
+
const familyOf = (hex) => families.filter((f) => Object.values(f.steps).some((c) => c.hex === hex)).sort((a, b) => Object.keys(b.steps).length - Object.keys(a.steps).length)[0];
|
|
349
|
+
const usedFamilies = new Set();
|
|
350
|
+
const rampFrom = (family, keys) => {
|
|
351
|
+
usedFamilies.add(family);
|
|
352
|
+
for (const c of Object.values(family.steps)) take(c.leaf);
|
|
353
|
+
return Object.fromEntries(Object.entries(family.steps).filter(([s]) => keys.has(s)).map(([s, c]) => [s, c.hex]));
|
|
354
|
+
};
|
|
355
|
+
const nearest = (family, target) => {
|
|
356
|
+
const order = [...STEPS];
|
|
357
|
+
const have = order.filter((s) => s in family.steps);
|
|
358
|
+
return have.sort((a, b) => Math.abs(order.indexOf(a) - order.indexOf(target)) - Math.abs(order.indexOf(b) - order.indexOf(target)))[0];
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const colors = {};
|
|
362
|
+
// Brand: primary in light, else dark; with no modes, a family named for the brand.
|
|
363
|
+
let brandSeed = roles.primary?.light ?? roles.primary?.dark;
|
|
364
|
+
let brandFamily = brandSeed && familyOf(brandSeed);
|
|
365
|
+
if (!brandSeed) {
|
|
366
|
+
brandFamily = families.find((f) => /^(brand|primary|accent)$/.test(norm(f.name)));
|
|
367
|
+
if (brandFamily) brandSeed = brandFamily.steps[nearest(brandFamily, '600')].hex;
|
|
368
|
+
}
|
|
369
|
+
if (brandSeed) {
|
|
370
|
+
colors.brand = { seed: brandSeed };
|
|
371
|
+
if (brandFamily) {
|
|
372
|
+
const step = Object.entries(brandFamily.steps).find(([, c]) => c.hex === brandSeed)?.[0];
|
|
373
|
+
if (STEPS.includes(step)) colors.brand.anchor = step;
|
|
374
|
+
colors.brand.steps = rampFrom(brandFamily, new Set(STEPS));
|
|
375
|
+
notes.push(`Brand ramp: seed ${brandSeed}, with steps ${Object.keys(colors.brand.steps).join(', ')} from "${brandFamily.path}".`);
|
|
376
|
+
} else notes.push(`Brand ramp: generated from ${brandSeed}.`);
|
|
377
|
+
} else notes.push("No brand colour found (no primary, brand or accent), so Halftone's default brand stays.");
|
|
378
|
+
|
|
379
|
+
// Neutral: a family named for it, or the one holding the light background or text.
|
|
380
|
+
const neutralFamily =
|
|
381
|
+
families.find((f) => !usedFamilies.has(f) && NEUTRAL_FAMILY.test(norm(f.name))) ??
|
|
382
|
+
[roles.background?.light, roles.foreground?.light, roles.background?.dark].map((h) => h && familyOf(h)).find((f) => f && !usedFamilies.has(f));
|
|
383
|
+
if (neutralFamily) {
|
|
384
|
+
const steps = rampFrom(neutralFamily, RAMP_KEYS);
|
|
385
|
+
const mid = nearest(neutralFamily, '500');
|
|
386
|
+
colors.neutral = { seed: neutralFamily.steps[mid].hex, steps };
|
|
387
|
+
notes.push(`Neutral ramp: steps ${Object.keys(steps).join(', ')} from "${neutralFamily.path}".`);
|
|
388
|
+
} else if (roles.background?.light && hexToOklchParts(roles.background.light)[1] > 0.005) {
|
|
389
|
+
colors.neutral = { seed: roles.background.light };
|
|
390
|
+
notes.push(`Neutral ramp: generated from the light background ${roles.background.light}, so the greys share its tint.`);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Status ramps: from the role colour, with its family's steps where it has one.
|
|
394
|
+
for (const [role, ramp] of Object.entries(STATUS)) {
|
|
395
|
+
const seed = roles[role]?.light ?? roles[role]?.dark;
|
|
396
|
+
if (!seed) continue;
|
|
397
|
+
const family = familyOf(seed);
|
|
398
|
+
colors[ramp] = { seed };
|
|
399
|
+
if (family && !usedFamilies.has(family)) colors[ramp].steps = rampFrom(family, new Set(STEPS));
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// 4. Palette colours nothing used: a family as an extra ramp, a single colour as an extra colour.
|
|
403
|
+
for (const family of families) {
|
|
404
|
+
if (usedFamilies.has(family) || Object.values(family.steps).every((c) => consumed.has(c.leaf.path.join('.')))) continue;
|
|
405
|
+
const n = extraName(family.name);
|
|
406
|
+
if (!n) continue;
|
|
407
|
+
const steps = Object.fromEntries(Object.entries(family.steps).filter(([s]) => STEPS.includes(s)).map(([s, c]) => [s, c.hex]));
|
|
408
|
+
const mid = nearest(family, '500');
|
|
409
|
+
extraColors.push({ name: n, seed: family.steps[mid].hex, steps });
|
|
410
|
+
for (const c of Object.values(family.steps)) take(c.leaf);
|
|
411
|
+
}
|
|
412
|
+
for (const leaf of leaves) {
|
|
413
|
+
if (consumed.has(leaf.path.join('.'))) continue;
|
|
414
|
+
const c = colorLeaf(leaf);
|
|
415
|
+
if (!c) continue;
|
|
416
|
+
const n = extraName(leaf.path.length > 1 && !['palette', 'color', 'colors', 'colour', 'colours'].includes(norm(leaf.path.at(-2))) ? `${leaf.path.at(-2)}-${leaf.key}` : leaf.key);
|
|
417
|
+
if (!n) continue;
|
|
418
|
+
extraColors.push({ name: n, value: opaque(c, null, leaf.path.join('.')) });
|
|
419
|
+
take(leaf);
|
|
420
|
+
}
|
|
421
|
+
if (extraColors.length) notes.push(`Extra colours (exported, never drawn by the kits; promote any in the Studio): ${extraColors.map((e) => e.name).join(', ')}.`);
|
|
422
|
+
|
|
423
|
+
// 5. Fonts.
|
|
424
|
+
const isGoogle = googleTest(google);
|
|
425
|
+
const fonts = {};
|
|
426
|
+
for (const { leaf, role, family } of fontTokens(ctx)) {
|
|
427
|
+
if (PLATFORM_FONTS.test(family)) {
|
|
428
|
+
take(leaf);
|
|
429
|
+
notes.push(`Font (${role}): "${family}" is the platform's own font, so the theme's default stays.`);
|
|
430
|
+
} else if (isGoogle(family)) {
|
|
431
|
+
fonts[role] = family;
|
|
432
|
+
take(leaf);
|
|
433
|
+
} else notes.push(`Font (${role}): "${family}" isn't on Google Fonts as far as this import knows, so it stays in tokens (a brand's own font file needs uploading). If it is on Google Fonts, name it in google (--google "${family}").`);
|
|
434
|
+
}
|
|
435
|
+
if (fonts.body && !fonts.heading) {
|
|
436
|
+
fonts.heading = fonts.body;
|
|
437
|
+
notes.push(`Headings use ${fonts.body}, the body font, until the file's own heading font is set.`);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Radius: named steps directly; other names in size order.
|
|
441
|
+
const radius = {};
|
|
442
|
+
const radiusLeaves = leaves.filter((l) => l.path.slice(0, -1).some((p) => RADIUS_GROUP.test(norm(p))) || RADIUS_GROUP.test(norm(l.path[0])));
|
|
443
|
+
const unnamed = [];
|
|
444
|
+
for (const leaf of radiusLeaves) {
|
|
445
|
+
const px = pxOf(resolve(leaf.value));
|
|
446
|
+
if (px === null) continue;
|
|
447
|
+
const key = norm(leaf.key);
|
|
448
|
+
if (FULL_RADIUS.has(key) || px >= 999) take(leaf);
|
|
449
|
+
else if (RADIUS_STEPS.includes(key)) {
|
|
450
|
+
radius[key] = px;
|
|
451
|
+
take(leaf);
|
|
452
|
+
} else unnamed.push({ leaf, px });
|
|
453
|
+
}
|
|
454
|
+
if (unnamed.length && unnamed.length <= RADIUS_STEPS.length - Object.keys(radius).length) {
|
|
455
|
+
const free = RADIUS_STEPS.filter((s) => !(s in radius));
|
|
456
|
+
unnamed.sort((a, b) => a.px - b.px).forEach(({ leaf, px }, i) => {
|
|
457
|
+
radius[free[i]] = px;
|
|
458
|
+
take(leaf);
|
|
459
|
+
});
|
|
460
|
+
notes.push(`Corners mapped by size: ${unnamed.map(({ leaf }, i) => `${leaf.key} → ${free[i]}`).join(', ')}.`);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Shadows: up to three, smallest blur first.
|
|
464
|
+
const shadow = {};
|
|
465
|
+
const layerOf = (v) => {
|
|
466
|
+
if (!isObject(v)) return null;
|
|
467
|
+
const c = colorOf(v.color ?? '#000000');
|
|
468
|
+
const nums = ['offsetX', 'offsetY', 'blur', 'spread'].map((k) => (v[k] === undefined ? 0 : pxOf(v[k])));
|
|
469
|
+
if (!c || nums.some((n) => n === null)) return null;
|
|
470
|
+
const [x, y, blur, spread] = nums;
|
|
471
|
+
return { x, y, blur, spread, color: c.hex, alpha: c.alpha, ...(v.inset ? { inset: true } : {}) };
|
|
472
|
+
};
|
|
473
|
+
const layersOf = (value) => {
|
|
474
|
+
const layers = (Array.isArray(value) ? value : [value]).map(layerOf);
|
|
475
|
+
return layers.length && layers.every(Boolean) ? layers : null;
|
|
476
|
+
};
|
|
477
|
+
const found = [];
|
|
478
|
+
for (const leaf of leaves) {
|
|
479
|
+
if (typeOf(leaf) !== 'shadow') continue;
|
|
480
|
+
const value = resolve(leaf.value);
|
|
481
|
+
// A value of { light, dark } is one shadow in both modes.
|
|
482
|
+
const moded = isObject(value) && 'light' in value && 'dark' in value ? { light: layersOf(value.light), dark: layersOf(value.dark) } : null;
|
|
483
|
+
const layers = moded ? moded.light && moded.dark && moded : layersOf(value);
|
|
484
|
+
if (layers) found.push({ leaf, layers });
|
|
485
|
+
}
|
|
486
|
+
// Siblings named light and dark (`shadow.light`, `shadow.dark`) are one shadow too.
|
|
487
|
+
const shadows = [];
|
|
488
|
+
const byParent = new Map();
|
|
489
|
+
for (const s of found) {
|
|
490
|
+
const parent = s.leaf.path.slice(0, -1).join('.');
|
|
491
|
+
(byParent.get(parent) ?? byParent.set(parent, []).get(parent)).push(s);
|
|
492
|
+
}
|
|
493
|
+
for (const [parent, list] of byParent) {
|
|
494
|
+
const l = list.find((s) => MODE_NAMES[norm(s.leaf.key)] === 'light');
|
|
495
|
+
const d = list.find((s) => MODE_NAMES[norm(s.leaf.key)] === 'dark');
|
|
496
|
+
if (l && d && Array.isArray(l.layers) && Array.isArray(d.layers)) {
|
|
497
|
+
shadows.push({ leaves: [l.leaf, d.leaf], key: parent.split('.').at(-1) || 'shadow', layers: { light: l.layers, dark: d.layers } });
|
|
498
|
+
list.splice(list.indexOf(l), 1);
|
|
499
|
+
list.splice(list.indexOf(d), 1);
|
|
500
|
+
}
|
|
501
|
+
for (const s of list) shadows.push({ leaves: [s.leaf], key: s.leaf.key, layers: s.layers });
|
|
502
|
+
}
|
|
503
|
+
const blurOf = (layers) => Math.max(...(Array.isArray(layers) ? layers : layers.light).map((x) => x.blur));
|
|
504
|
+
if (shadows.length && shadows.length <= 3) {
|
|
505
|
+
shadows.sort((a, b) => blurOf(a.layers) - blurOf(b.layers)).forEach((s, i) => {
|
|
506
|
+
shadow[String(i + 1)] = s.layers;
|
|
507
|
+
s.leaves.forEach(take);
|
|
508
|
+
});
|
|
509
|
+
notes.push(`Shadows by size: ${shadows.map((s, i) => `${s.key} → ${i + 1}`).join(', ')}.`);
|
|
510
|
+
} else if (shadows.length > 3) notes.push(`${shadows.length} shadows; Halftone has three levels, so they stay in tokens. Pick three in the Studio.`);
|
|
511
|
+
|
|
512
|
+
// 6. Everything else, aliases resolved.
|
|
513
|
+
const leftover = (node, path) => {
|
|
514
|
+
const out = {};
|
|
515
|
+
for (const [key, child] of Object.entries(node)) {
|
|
516
|
+
if (key.startsWith('$')) {
|
|
517
|
+
if (key !== '$value') out[key] = child;
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (!isObject(child)) continue;
|
|
521
|
+
const at = [...path, key].join('.');
|
|
522
|
+
if ('$value' in child) {
|
|
523
|
+
if (consumed.has(at)) continue;
|
|
524
|
+
out[key] = { ...child, $value: resolve(child.$value) };
|
|
525
|
+
const type = typeOf(byPath.get(at));
|
|
526
|
+
if (type && !child.$type) out[key].$type = type;
|
|
527
|
+
} else {
|
|
528
|
+
const inner = leftover(child, [...path, key]);
|
|
529
|
+
if (Object.keys(inner).some((k) => !k.startsWith('$'))) out[key] = inner;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return out;
|
|
533
|
+
};
|
|
534
|
+
const tokens = leftover(input, []);
|
|
535
|
+
const kept = Object.keys(tokens).filter((k) => !k.startsWith('$'));
|
|
536
|
+
if (!kept.length) for (const k of Object.keys(tokens)) delete tokens[k];
|
|
537
|
+
else notes.push(`Kept as they are, under tokens (not drawn by the kits): ${kept.join(', ')}.`);
|
|
538
|
+
|
|
539
|
+
const label = typeof name === 'string' && name.trim() ? name.trim() : 'Imported brand';
|
|
540
|
+
const system = createSystem({
|
|
541
|
+
name: label,
|
|
542
|
+
colors,
|
|
543
|
+
roles,
|
|
544
|
+
fonts,
|
|
545
|
+
radius,
|
|
546
|
+
shadow,
|
|
547
|
+
extras: { color: extraColors },
|
|
548
|
+
brand: { name: label },
|
|
549
|
+
...(kept.length ? { tokens } : {}),
|
|
550
|
+
});
|
|
551
|
+
return { system, notes };
|
|
552
|
+
}
|
package/lib/system/index.d.mts
CHANGED
|
@@ -77,6 +77,11 @@ export type HalftoneSystem = {
|
|
|
77
77
|
components: SystemComponents;
|
|
78
78
|
/** Set durations, easings and springs over the recipe's speed, overrides only (empty: as the speed draws them). */
|
|
79
79
|
motion: MotionEdits;
|
|
80
|
+
/**
|
|
81
|
+
* A brand's own DTCG tokens that no slot above holds (spacing, a line weight, a third set of colours), kept whole
|
|
82
|
+
* and never drawn by the kits: what `halftone-tokens import` couldn't map. Present only when there are some.
|
|
83
|
+
*/
|
|
84
|
+
tokens?: Record<string, unknown>;
|
|
80
85
|
};
|
|
81
86
|
|
|
82
87
|
/** A component colour: a role (any semantic colour), or 'none' for a fill or border. */
|
|
@@ -179,5 +184,16 @@ export function systemRadii(system: HalftoneSystemInput | HalftoneSystem, base:
|
|
|
179
184
|
export function migrate(input: RecipeInput | string | HalftoneSystemInput, brand?: Partial<SystemBrand>, options?: { id?: string; name?: string; updatedAt?: string }): HalftoneSystem;
|
|
180
185
|
/** The recipe under a system, its code (null with overrides) and the overrides a recipe loses. */
|
|
181
186
|
export function systemToRecipe(system: HalftoneSystemInput | HalftoneSystem): { recipe: Recipe; code: string | null; lost: string[] };
|
|
187
|
+
/**
|
|
188
|
+
* A system from a brand's own tokens.json (DTCG): role colours kept exactly, ramps seeded from them, other colours
|
|
189
|
+
* as extras, fonts, corners and shadows by name, everything else under `tokens`. `notes` says each guess and loss.
|
|
190
|
+
* `google`: families known to be on Google Fonts beyond the curated list; others stay under `tokens`.
|
|
191
|
+
*/
|
|
192
|
+
export function systemFromTokens(
|
|
193
|
+
dtcg: Record<string, unknown>,
|
|
194
|
+
options?: { name?: string; google?: Iterable<string> | ((family: string) => boolean) }
|
|
195
|
+
): { system: HalftoneSystem; notes: string[] };
|
|
196
|
+
/** The font families a tokens file names that may or may not be on Google Fonts (not the platform's, not curated). */
|
|
197
|
+
export function fontFamiliesToCheck(dtcg: Record<string, unknown>): string[];
|
|
182
198
|
/** Commit a system into tokens.json; the record keeps the document without brand images. */
|
|
183
199
|
export function applySystem(tokens: TokensJson, system: HalftoneSystemInput | HalftoneSystem): { tokens: TokensJson; theme: Theme; system: HalftoneSystem };
|
package/lib/system/index.mjs
CHANGED
|
@@ -31,4 +31,5 @@ export {
|
|
|
31
31
|
} from './schema.mjs';
|
|
32
32
|
export { generateSystem, systemCode, systemRadii, systemRamps, textStyles } from './generate.mjs';
|
|
33
33
|
export { migrate, systemToRecipe } from './migrate.mjs';
|
|
34
|
+
export { fontFamiliesToCheck, systemFromTokens } from './import.mjs';
|
|
34
35
|
export { applySystem } from '../theme/apply.mjs';
|
package/lib/system/schema.mjs
CHANGED
|
@@ -27,6 +27,9 @@
|
|
|
27
27
|
* extras { color: [], text: [], radius: [], shadow: [], border: [] } named tokens of your own,
|
|
28
28
|
* exported (tokens.json `extra.*`) and never drawn by the kits
|
|
29
29
|
* brand { name, iconBackground, logo?, logoDark?, mark?, markDark? } (the Studio's BrandState)
|
|
30
|
+
* tokens? a brand's own DTCG tokens that no slot above holds (spacing, a line weight, a grid, a third
|
|
31
|
+
* set of colours), kept whole and never drawn by the kits: what `halftone-tokens import` couldn't
|
|
32
|
+
* map. Present only when there are some; at most 256 KB as JSON.
|
|
30
33
|
* motion { durations?, easings?, springs? } set values on top of the recipe's speed (lib/theme/motion.mjs),
|
|
31
34
|
* overrides only; a document without it moves as its speed says, as every system before motion did:
|
|
32
35
|
* durations { fast|base|slow: ms }
|
|
@@ -446,6 +449,23 @@ function motion(r, input) {
|
|
|
446
449
|
return out;
|
|
447
450
|
}
|
|
448
451
|
|
|
452
|
+
const TOKENS_LIMIT = 256 * 1024;
|
|
453
|
+
|
|
454
|
+
/** tokens: a plain DTCG object, copied as JSON. Undefined when there's nothing in it. */
|
|
455
|
+
function tokens(r, input) {
|
|
456
|
+
if (input === undefined) return undefined;
|
|
457
|
+
if (!isObject(input)) return r.fail('tokens', 'must be an object of DTCG tokens');
|
|
458
|
+
let text;
|
|
459
|
+
try {
|
|
460
|
+
text = JSON.stringify(input);
|
|
461
|
+
} catch {
|
|
462
|
+
return r.fail('tokens', 'must be plain JSON');
|
|
463
|
+
}
|
|
464
|
+
if (text.length > TOKENS_LIMIT) return r.fail('tokens', `is ${Math.round(text.length / 1024)} KB; the most a system keeps is 256 KB`);
|
|
465
|
+
const copy = JSON.parse(text);
|
|
466
|
+
return Object.keys(copy).length ? copy : undefined;
|
|
467
|
+
}
|
|
468
|
+
|
|
449
469
|
/** Is this a system document (rather than a bare recipe)? */
|
|
450
470
|
export const isSystem = (value) => isObject(value) && (value.kind === SYSTEM_KIND || isObject(value.recipe));
|
|
451
471
|
|
|
@@ -455,7 +475,7 @@ function read(input) {
|
|
|
455
475
|
if (input.kind !== undefined && input.kind !== SYSTEM_KIND) r.fail('kind', `must be "${SYSTEM_KIND}"`);
|
|
456
476
|
if (input.v !== undefined && !(Number.isInteger(input.v) && input.v >= 1)) r.fail('v', 'must be a version number');
|
|
457
477
|
if (input.v > SYSTEM_VERSION) throw new SystemError([`v: this system is version ${input.v}, from a newer @halftone-ds/tokens; update it to read the system`]);
|
|
458
|
-
r.keys('', input, ['$schema', 'kind', 'v', 'id', 'name', 'preset', 'updatedAt', 'recipe', 'colors', 'roles', 'type', 'fonts', 'radius', 'shadow', 'border', 'extras', 'brand', 'components', 'motion']);
|
|
478
|
+
r.keys('', input, ['$schema', 'kind', 'v', 'id', 'name', 'preset', 'updatedAt', 'recipe', 'colors', 'roles', 'type', 'fonts', 'radius', 'shadow', 'border', 'extras', 'brand', 'components', 'motion', 'tokens']);
|
|
459
479
|
|
|
460
480
|
let recipe;
|
|
461
481
|
try {
|
|
@@ -520,6 +540,8 @@ function read(input) {
|
|
|
520
540
|
|
|
521
541
|
doc.components = components(r, input.components, recipe);
|
|
522
542
|
doc.motion = motion(r, input.motion);
|
|
543
|
+
const leftover = tokens(r, input.tokens);
|
|
544
|
+
if (leftover) doc.tokens = leftover;
|
|
523
545
|
return { doc, errors: r.errors };
|
|
524
546
|
}
|
|
525
547
|
|
|
@@ -570,6 +592,7 @@ export function systemOverrides(input) {
|
|
|
570
592
|
for (const [variant, slots] of Object.entries(entry.variants ?? {})) for (const slot of Object.keys(slots)) paths.push(`components.${name}.variants.${variant}.${slot}`);
|
|
571
593
|
}
|
|
572
594
|
for (const [group, entries] of Object.entries(doc.motion)) for (const name of Object.keys(entries)) paths.push(`motion.${group}.${name}`);
|
|
595
|
+
for (const key of Object.keys(doc.tokens ?? {})) paths.push(`tokens.${key}`);
|
|
573
596
|
return paths;
|
|
574
597
|
}
|
|
575
598
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@halftone-ds/tokens",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Design tokens (W3C DTCG) to NativeWind, Tailwind 4 / shadcn, TypeScript, DESIGN.md and Figma, with a WCAG AA contrast gate. The token build behind Halftone.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|