@halftone-ds/tokens 1.3.2 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -11
- package/cli.mjs +50 -15
- package/lib/contrast.mjs +50 -6
- package/lib/doctor.mjs +360 -0
- package/lib/generate.mjs +28 -0
- package/lib/init.mjs +264 -0
- package/lib/resolve.mjs +31 -2
- package/lib/scan.mjs +15 -11
- package/lib/system/generate.mjs +5 -1
- package/lib/system/index.d.mts +17 -2
- package/lib/system/index.mjs +1 -0
- package/lib/system/schema.mjs +80 -9
- package/lib/theme/apply.mjs +30 -5
- package/lib/theme/codec.mjs +13 -7
- package/lib/theme/components.mjs +276 -52
- package/lib/theme/fix.mjs +26 -3
- package/lib/theme/generate.mjs +14 -1
- package/lib/theme/index.d.mts +72 -3
- package/lib/theme/index.mjs +9 -2
- package/lib/theme/motion.mjs +99 -0
- package/lib/theme/recipe.mjs +11 -1
- package/lib/theme/semantic.mjs +27 -0
- package/lib/theme/vars.mjs +20 -4
- package/lib/usage.mjs +1 -1
- package/package.json +2 -1
- package/targets/design-md.mjs +17 -11
- package/targets/figma.mjs +3 -0
- package/targets/fonts.mjs +28 -1
- package/targets/llms.mjs +6 -6
- package/targets/nativewind3.mjs +43 -13
- package/targets/shadcn-web.mjs +36 -5
- package/targets/ts-theme.mjs +44 -7
- package/templates/tokens.json +2400 -0
package/lib/resolve.mjs
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
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 { DURATION_NAMES, EASING_NAMES, MOTION_DEFAULTS, SPRING_KEYS, SPRING_NAMES } from './theme/motion.mjs';
|
|
12
|
+
import { isDerived, semanticColors, TINT_ROLES } from './theme/semantic.mjs';
|
|
10
13
|
import { BUTTON, DEFAULT_RECIPE, DENSITY, DEPTH, FIELD, fieldWidth, resolveTextStyles, shadowCss, textEdits, TYPE, typeScale } from './theme/recipe.mjs';
|
|
11
14
|
|
|
12
15
|
export const MODES = ['light', 'dark'];
|
|
@@ -123,6 +126,15 @@ export async function loadTokens(sourcePath) {
|
|
|
123
126
|
const byName = Object.fromEntries(colors.map((c) => [c.name, c]));
|
|
124
127
|
const STYLE_FALLBACK = { button: 'primary', 'button-foreground': 'primary-foreground', 'button-edge': 'primary', field: 'input', 'field-edge': 'input' };
|
|
125
128
|
for (const [name, from] of Object.entries(STYLE_FALLBACK)) if (!byName[name] && byName[from]) colors.push({ ...byName[from], name });
|
|
129
|
+
// The tints and pressed fills a token file from before them doesn't have: the theme's steps on the file's ramps.
|
|
130
|
+
const primHex = Object.fromEntries(prim.filter(isColor).map((t) => [t.path.join('.'), t.$value.toLowerCase()]));
|
|
131
|
+
const brandStep = Object.keys(source.primitive?.color?.brand ?? {}).find((step) => primHex[`primitive.color.brand.${step}`] === byName.primary?.light);
|
|
132
|
+
const derived = semanticColors(brandStep ?? '600');
|
|
133
|
+
for (const [name, refs] of Object.entries(derived)) {
|
|
134
|
+
if (byName[name] || !isDerived(name) && !TINT_ROLES.includes(name)) continue;
|
|
135
|
+
const hex = (mode) => primHex[refs[mode].slice(1, -1)];
|
|
136
|
+
if (hex('light') && hex('dark')) colors.push({ name, light: hex('light'), dark: hex('dark') });
|
|
137
|
+
}
|
|
126
138
|
const shadows = (list, mode) =>
|
|
127
139
|
Object.fromEntries(['1', '2', '3'].map((level) => [level, shadowCss(find(list, `shadow-${level}`) ?? DEPTH.soft[level][mode])]));
|
|
128
140
|
const borderWidth = find(semLight, 'border-width') ?? 1;
|
|
@@ -160,13 +172,29 @@ export async function loadTokens(sourcePath) {
|
|
|
160
172
|
const styles = { button: recorded.button ?? DEFAULT_RECIPE.button, field: recorded.field ?? DEFAULT_RECIPE.field };
|
|
161
173
|
const extras = extraList(source.extra);
|
|
162
174
|
const components = loadComponents({ source, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, recorded });
|
|
163
|
-
|
|
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
|
+
};
|
|
164
192
|
}
|
|
165
193
|
|
|
166
194
|
/** The component layer from the file, or (a file from before it) the defaults on the file's colours and shape. */
|
|
167
195
|
function loadComponents({ source, compLight, compDark, prim, colors, radius, shape, type, textStyles, styles, recorded }) {
|
|
168
196
|
const flat = (list) => Object.fromEntries(list.map((t) => [t.path.join('.'), t.$value]));
|
|
169
|
-
const read = readComponents(flat(compLight), flat(compDark), source.semantic?.component);
|
|
197
|
+
const read = readComponents(flat(compLight), flat(compDark), source.semantic?.component, { borderWidth: shape.borderWidth });
|
|
170
198
|
if (read) return read;
|
|
171
199
|
const byName = Object.fromEntries(colors.map((c) => [c.name, c]));
|
|
172
200
|
const primMap = Object.fromEntries(prim.map((t) => [t.path.join('.'), t.$value]));
|
|
@@ -185,6 +213,7 @@ function loadComponents({ source, compLight, compDark, prim, colors, radius, sha
|
|
|
185
213
|
const name = /^\{semantic\.color\.(.+)\}$/.exec(ref)?.[1];
|
|
186
214
|
return String(name ? byName[name]?.[mode] : primMap[ref.slice(1, -1)]).toLowerCase();
|
|
187
215
|
},
|
|
216
|
+
ramps: rampsOf(source.primitive?.color ?? {}, (path) => String(primMap[path]).toLowerCase()),
|
|
188
217
|
}).shape;
|
|
189
218
|
}
|
|
190
219
|
|
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
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
/**
|
|
35
|
-
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
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
|
}
|
package/lib/system/generate.mjs
CHANGED
|
@@ -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). */
|
package/lib/system/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Types for @halftone-ds/tokens/system (index.mjs): the HalftoneSystem v1 document. */
|
|
2
|
-
import type { Mode, Neutral, Recipe, RecipeInput, Theme, TokensJson } from '../theme/index.mjs';
|
|
2
|
+
import type { Mode, MotionEdits, Neutral, Recipe, RecipeInput, Theme, TokensJson } from '../theme/index.mjs';
|
|
3
3
|
|
|
4
4
|
export type ColorRole = 'brand' | 'neutral' | 'danger' | 'success' | 'warning' | 'info';
|
|
5
5
|
export type StatusRole = 'danger' | 'success' | 'warning' | 'info';
|
|
@@ -75,6 +75,8 @@ export type HalftoneSystem = {
|
|
|
75
75
|
brand: SystemBrand;
|
|
76
76
|
/** Component-level edits (Button, Chip, Badge, Input), overrides only. Button and Input styles fold into the recipe. */
|
|
77
77
|
components: SystemComponents;
|
|
78
|
+
/** Set durations, easings and springs over the recipe's speed, overrides only (empty: as the speed draws them). */
|
|
79
|
+
motion: MotionEdits;
|
|
78
80
|
};
|
|
79
81
|
|
|
80
82
|
/** A component colour: a role (any semantic colour), or 'none' for a fill or border. */
|
|
@@ -82,9 +84,21 @@ export type ComponentEdit = {
|
|
|
82
84
|
style?: string;
|
|
83
85
|
/** A Foundations corner, or px. */
|
|
84
86
|
radius?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full' | number;
|
|
85
|
-
|
|
87
|
+
/** Border width (px). */
|
|
88
|
+
border?: number;
|
|
89
|
+
/** Heights per step, then the padding and icon gap every step shares (px). */
|
|
90
|
+
size?: Partial<Record<'sm' | 'md' | 'lg' | 'x' | 'gap', number>>;
|
|
86
91
|
/** A text style (h1…blockquote). */
|
|
87
92
|
text?: string;
|
|
93
|
+
weight?: 400 | 500 | 600 | 700;
|
|
94
|
+
case?: 'none' | 'uppercase';
|
|
95
|
+
/** Icon size (px). */
|
|
96
|
+
icon?: number;
|
|
97
|
+
shadow?: 'none' | '1' | '2' | '3';
|
|
98
|
+
/** The focus ring: width (px) and a role. */
|
|
99
|
+
ring?: { width?: number; role?: string };
|
|
100
|
+
/** Input: the placeholder's role. */
|
|
101
|
+
placeholder?: string;
|
|
88
102
|
variants?: Record<string, Partial<Record<'fill' | 'label' | 'border' | 'pressed', string>>>;
|
|
89
103
|
};
|
|
90
104
|
export type SystemComponents = Partial<Record<'button' | 'chip' | 'badge' | 'input', ComponentEdit>>;
|
|
@@ -133,6 +147,7 @@ export const RADIUS_STEPS: RadiusStep[];
|
|
|
133
147
|
export const SHADOW_LEVELS: ShadowLevel[];
|
|
134
148
|
export const BORDER_STYLES: BorderStyle[];
|
|
135
149
|
export const EXTRA_KINDS: ExtraKind[];
|
|
150
|
+
export const MOTION_GROUPS: ['durations', 'easings', 'springs'];
|
|
136
151
|
|
|
137
152
|
export class SystemError extends Error {
|
|
138
153
|
/** Every problem, as 'path: message'. */
|
package/lib/system/index.mjs
CHANGED
package/lib/system/schema.mjs
CHANGED
|
@@ -27,13 +27,27 @@
|
|
|
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
|
-
*
|
|
31
|
-
*
|
|
30
|
+
* motion { durations?, easings?, springs? } set values on top of the recipe's speed (lib/theme/motion.mjs),
|
|
31
|
+
* overrides only; a document without it moves as its speed says, as every system before motion did:
|
|
32
|
+
* durations { fast|base|slow: ms }
|
|
33
|
+
* easings { standard|emphasized|exit: [x1, y1, x2, y2] } x within 0–1
|
|
34
|
+
* springs { snappy|gentle: { stiffness, damping, mass } } all three
|
|
35
|
+
* components { button|chip|badge|input: { style?, radius?, border?, size?, text?, weight?, case?, icon?,
|
|
36
|
+
* shadow?, ring?, placeholder?, variants? } } component-level edits (lib/theme/components.mjs),
|
|
37
|
+
* overrides only, each where the component has it (COMPONENTS[name].props):
|
|
32
38
|
* style the component's look. Button and Input fold into recipe.button / recipe.field;
|
|
33
39
|
* Chip outline|soft|solid, Badge pill|square|soft
|
|
34
40
|
* radius a Foundations corner (sm…2xl, full) or px
|
|
35
|
-
*
|
|
36
|
-
*
|
|
41
|
+
* border border width, px (Input: its field style's lines)
|
|
42
|
+
* size { sm?, md?, lg?, x?, gap? } heights per step, then the horizontal padding and
|
|
43
|
+
* the icon gap every step shares, px (the keys it has: Badge S/M, Input no gap)
|
|
44
|
+
* text a text style (h1…blockquote): its font, size and tracking
|
|
45
|
+
* weight 400 | 500 | 600 | 700 (the label's; Button, Chip, Badge)
|
|
46
|
+
* case 'none' | 'uppercase' (Button, Badge)
|
|
47
|
+
* icon icon size, px (Button, Chip, Badge)
|
|
48
|
+
* shadow 'none' | '1' | '2' | '3', a Foundations shadow (Button, Input)
|
|
49
|
+
* ring { width?: px, role?: a role } the focus ring (Button, Input)
|
|
50
|
+
* placeholder a role (Input)
|
|
37
51
|
* variants { <variant>: { fill?, label?, border?, pressed? } } roles (ROLE_NAMES), or
|
|
38
52
|
* 'none' for a fill or border. Variants are fixed (Input: its states)
|
|
39
53
|
*
|
|
@@ -43,7 +57,8 @@
|
|
|
43
57
|
import { FONTS } from '../theme/fonts.mjs';
|
|
44
58
|
import { STEPS } from '../theme/palettes.mjs';
|
|
45
59
|
import { anchorStep, neutralAnchorStep } from '../theme/ramp.mjs';
|
|
46
|
-
import { COMPONENT_NAMES, COMPONENTS, CORNERS } from '../theme/components.mjs';
|
|
60
|
+
import { CASES, COMPONENT_NAMES, COMPONENTS, CORNERS, SHADOWS, WEIGHTS } from '../theme/components.mjs';
|
|
61
|
+
import { DURATION_NAMES, EASING_NAMES, SPRING_KEYS, SPRING_NAMES } from '../theme/motion.mjs';
|
|
47
62
|
import { normalizeRecipe, OPTIONS, TEXT_DEFAULTS, TEXT_STYLES } from '../theme/recipe.mjs';
|
|
48
63
|
import { semanticColors } from '../theme/semantic.mjs';
|
|
49
64
|
|
|
@@ -61,6 +76,8 @@ export const SHADOW_LEVELS = ['1', '2', '3'];
|
|
|
61
76
|
export const BORDER_STYLES = ['solid', 'dashed', 'dotted'];
|
|
62
77
|
export const EXTRA_KINDS = ['color', 'text', 'radius', 'shadow', 'border'];
|
|
63
78
|
export const TEXT_KEYS = ['font', 'weight', 'size', 'leading', 'tracking'];
|
|
79
|
+
export const MOTION_GROUPS = ['durations', 'easings', 'springs'];
|
|
80
|
+
export { DURATION_NAMES, EASING_NAMES, SPRING_NAMES };
|
|
64
81
|
export { TEXT_DEFAULTS, TEXT_STYLES };
|
|
65
82
|
|
|
66
83
|
|
|
@@ -346,7 +363,7 @@ function components(r, input, recipe) {
|
|
|
346
363
|
const path = `components.${name}`;
|
|
347
364
|
const def = COMPONENTS[name];
|
|
348
365
|
const v = r.object(path, value);
|
|
349
|
-
r.keys(path, v, ['style', 'radius', 'size', 'text', 'variants']);
|
|
366
|
+
r.keys(path, v, ['style', 'radius', 'size', 'text', 'variants', ...def.props]);
|
|
350
367
|
const entry = {};
|
|
351
368
|
if (v.style !== undefined) {
|
|
352
369
|
const style = r.oneOf(`${path}.style`, v.style, def.styles);
|
|
@@ -358,10 +375,28 @@ function components(r, input, recipe) {
|
|
|
358
375
|
if (v.radius !== undefined) entry.radius = typeof v.radius === 'number' ? r.num(`${path}.radius`, v.radius, 0, 9999) : r.oneOf(`${path}.radius`, v.radius, CORNERS);
|
|
359
376
|
if (v.size !== undefined) {
|
|
360
377
|
const size = {};
|
|
361
|
-
for (const [key, px] of r.keys(`${path}.size`, r.object(`${path}.size`, v.size), def.sizes))
|
|
378
|
+
for (const [key, px] of r.keys(`${path}.size`, r.object(`${path}.size`, v.size), def.sizes)) {
|
|
379
|
+
size[key] = key === 'x' ? r.num(`${path}.size.x`, px, 0, 64) : key === 'gap' ? r.num(`${path}.size.gap`, px, 0, 24) : r.num(`${path}.size.${key}`, px, 12, 120);
|
|
380
|
+
}
|
|
362
381
|
if (Object.keys(size).length) entry.size = size;
|
|
363
382
|
}
|
|
364
383
|
if (v.text !== undefined) entry.text = r.oneOf(`${path}.text`, v.text, TEXT_STYLES);
|
|
384
|
+
if (v.border !== undefined) entry.border = r.num(`${path}.border`, v.border, 0, 8);
|
|
385
|
+
if (v.weight !== undefined) entry.weight = r.oneOf(`${path}.weight`, v.weight, WEIGHTS);
|
|
386
|
+
if (v.case !== undefined) entry.case = r.oneOf(`${path}.case`, v.case, CASES);
|
|
387
|
+
if (v.icon !== undefined) entry.icon = r.num(`${path}.icon`, v.icon, 8, 40);
|
|
388
|
+
if (v.shadow !== undefined) entry.shadow = r.oneOf(`${path}.shadow`, String(v.shadow), SHADOWS);
|
|
389
|
+
if (v.placeholder !== undefined) entry.placeholder = r.oneOf(`${path}.placeholder`, v.placeholder, ROLE_NAMES);
|
|
390
|
+
if (v.ring !== undefined) {
|
|
391
|
+
const ring = {};
|
|
392
|
+
const at = `${path}.ring`;
|
|
393
|
+
const value = r.object(at, v.ring);
|
|
394
|
+
r.keys(at, value, ['width', 'role']);
|
|
395
|
+
if (value.width !== undefined) ring.width = r.num(`${at}.width`, value.width, 0, 8);
|
|
396
|
+
if (value.role !== undefined) ring.role = r.oneOf(`${at}.role`, value.role, ROLE_NAMES);
|
|
397
|
+
for (const key of Object.keys(ring)) if (ring[key] === undefined) delete ring[key];
|
|
398
|
+
if (Object.keys(ring).length) entry.ring = ring;
|
|
399
|
+
}
|
|
365
400
|
if (v.variants !== undefined) {
|
|
366
401
|
const variants = {};
|
|
367
402
|
for (const [variant, slots] of r.keys(`${path}.variants`, r.object(`${path}.variants`, v.variants), Object.keys(def.variants))) {
|
|
@@ -378,6 +413,39 @@ function components(r, input, recipe) {
|
|
|
378
413
|
return out;
|
|
379
414
|
}
|
|
380
415
|
|
|
416
|
+
/** motion: set durations, easings and springs (each whole), over the recipe's speed. */
|
|
417
|
+
function motion(r, input) {
|
|
418
|
+
const out = {};
|
|
419
|
+
const v = r.object('motion', input);
|
|
420
|
+
for (const [group, value] of r.keys('motion', v, MOTION_GROUPS)) {
|
|
421
|
+
const path = `motion.${group}`;
|
|
422
|
+
const entries = {};
|
|
423
|
+
if (group === 'durations') for (const [name, ms] of r.keys(path, r.object(path, value), DURATION_NAMES)) entries[name] = r.num(`${path}.${name}`, ms, 0, 5000);
|
|
424
|
+
if (group === 'easings') {
|
|
425
|
+
for (const [name, curve] of r.keys(path, r.object(path, value), EASING_NAMES)) {
|
|
426
|
+
const at = `${path}.${name}`;
|
|
427
|
+
const ok = Array.isArray(curve) && curve.length === 4 && curve.every(isNumber) && curve[0] >= 0 && curve[0] <= 1 && curve[2] >= 0 && curve[2] <= 1 && [curve[1], curve[3]].every((y) => y >= -2 && y <= 3);
|
|
428
|
+
entries[name] = ok ? curve.map((n) => Number(n.toFixed(3))) : r.fail(at, `must be [x1, y1, x2, y2] with x from 0 to 1 and y from -2 to 3, got ${JSON.stringify(curve)}`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (group === 'springs') {
|
|
432
|
+
for (const [name, spring] of r.keys(path, r.object(path, value), SPRING_NAMES)) {
|
|
433
|
+
const at = `${path}.${name}`;
|
|
434
|
+
const s = r.object(at, spring);
|
|
435
|
+
r.keys(at, s, SPRING_KEYS);
|
|
436
|
+
entries[name] = {
|
|
437
|
+
stiffness: r.num(`${at}.stiffness`, s.stiffness, 1, 2000),
|
|
438
|
+
damping: r.num(`${at}.damping`, s.damping, 0, 200),
|
|
439
|
+
mass: r.num(`${at}.mass`, s.mass ?? 1, 0.1, 20),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
for (const key of Object.keys(entries)) if (entries[key] === undefined) delete entries[key];
|
|
444
|
+
if (Object.keys(entries).length) out[group] = entries;
|
|
445
|
+
}
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
|
|
381
449
|
/** Is this a system document (rather than a bare recipe)? */
|
|
382
450
|
export const isSystem = (value) => isObject(value) && (value.kind === SYSTEM_KIND || isObject(value.recipe));
|
|
383
451
|
|
|
@@ -387,7 +455,7 @@ function read(input) {
|
|
|
387
455
|
if (input.kind !== undefined && input.kind !== SYSTEM_KIND) r.fail('kind', `must be "${SYSTEM_KIND}"`);
|
|
388
456
|
if (input.v !== undefined && !(Number.isInteger(input.v) && input.v >= 1)) r.fail('v', 'must be a version number');
|
|
389
457
|
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`]);
|
|
390
|
-
r.keys('', input, ['$schema', 'kind', 'v', 'id', 'name', 'preset', 'updatedAt', 'recipe', 'colors', 'roles', 'type', 'fonts', 'radius', 'shadow', 'border', 'extras', 'brand', 'components']);
|
|
458
|
+
r.keys('', input, ['$schema', 'kind', 'v', 'id', 'name', 'preset', 'updatedAt', 'recipe', 'colors', 'roles', 'type', 'fonts', 'radius', 'shadow', 'border', 'extras', 'brand', 'components', 'motion']);
|
|
391
459
|
|
|
392
460
|
let recipe;
|
|
393
461
|
try {
|
|
@@ -451,6 +519,7 @@ function read(input) {
|
|
|
451
519
|
doc.brand = brand(r, input.brand);
|
|
452
520
|
|
|
453
521
|
doc.components = components(r, input.components, recipe);
|
|
522
|
+
doc.motion = motion(r, input.motion);
|
|
454
523
|
return { doc, errors: r.errors };
|
|
455
524
|
}
|
|
456
525
|
|
|
@@ -495,10 +564,12 @@ export function systemOverrides(input) {
|
|
|
495
564
|
for (const section of ['fonts', 'radius', 'shadow', 'border']) for (const key of Object.keys(doc[section])) paths.push(`${section}.${key}`);
|
|
496
565
|
for (const kind of EXTRA_KINDS) for (const item of doc.extras[kind]) paths.push(`extras.${kind}.${item.name}`);
|
|
497
566
|
for (const [name, entry] of Object.entries(doc.components)) {
|
|
498
|
-
for (const key of ['style', 'radius', 'text']) if (entry[key] !== undefined) paths.push(`components.${name}.${key}`);
|
|
567
|
+
for (const key of ['style', 'radius', 'text', 'border', 'weight', 'case', 'icon', 'shadow', 'placeholder']) if (entry[key] !== undefined) paths.push(`components.${name}.${key}`);
|
|
568
|
+
for (const key of Object.keys(entry.ring ?? {})) paths.push(`components.${name}.ring.${key}`);
|
|
499
569
|
for (const key of Object.keys(entry.size ?? {})) paths.push(`components.${name}.size.${key}`);
|
|
500
570
|
for (const [variant, slots] of Object.entries(entry.variants ?? {})) for (const slot of Object.keys(slots)) paths.push(`components.${name}.variants.${variant}.${slot}`);
|
|
501
571
|
}
|
|
572
|
+
for (const [group, entries] of Object.entries(doc.motion)) for (const name of Object.keys(entries)) paths.push(`motion.${group}.${name}`);
|
|
502
573
|
return paths;
|
|
503
574
|
}
|
|
504
575
|
|
package/lib/theme/apply.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Commit a theme into a tokens.json object. Only the paths a theme owns are written; everything else
|
|
3
|
-
* (status ramps, spacing, type sizes,
|
|
3
|
+
* (status ramps, spacing, type sizes, descriptions) is left exactly as it was. Motion (primitive.duration, .easing and
|
|
4
|
+
* .spring) is the theme's: its speed scales it, and a system can set each value. The recipe is
|
|
4
5
|
* recorded under `$extensions["com.halftonedesignsystem.theme"]`, so the docs picker and `halftone-tokens theme show`
|
|
5
6
|
* can tell which theme is applied, and whether anyone has hand-edited it since (drift).
|
|
6
7
|
*
|
|
@@ -13,6 +14,7 @@
|
|
|
13
14
|
import { generateSystem, systemCode } from '../system/generate.mjs';
|
|
14
15
|
import { normalizeSystem, withoutBrandImages } from '../system/schema.mjs';
|
|
15
16
|
import { generateTheme } from './generate.mjs';
|
|
17
|
+
import { MOTION_USE } from './motion.mjs';
|
|
16
18
|
import { BRAND_RAMPS } from './palettes.mjs';
|
|
17
19
|
import { normalizeRecipe } from './recipe.mjs';
|
|
18
20
|
import { flatten } from './refs.mjs';
|
|
@@ -58,6 +60,10 @@ function ownedValues(theme) {
|
|
|
58
60
|
}
|
|
59
61
|
};
|
|
60
62
|
walk(theme.semantic.component, 'semantic.component');
|
|
63
|
+
// Motion: durations (ms), easings (cubic-bezier) and springs (stiffness, damping, mass).
|
|
64
|
+
for (const [name, ms] of Object.entries(theme.motion.durations)) out[`primitive.duration.${name}`] = ms;
|
|
65
|
+
for (const [name, curve] of Object.entries(theme.motion.easings)) out[`primitive.easing.${name}`] = curve;
|
|
66
|
+
for (const [name, spring] of Object.entries(theme.motion.springs)) for (const [key, value] of Object.entries(spring)) out[`primitive.spring.${name}.${key}`] = value;
|
|
61
67
|
if (theme.extra) Object.assign(out, flatValues(theme.extra, 'extra'));
|
|
62
68
|
return out;
|
|
63
69
|
}
|
|
@@ -65,7 +71,7 @@ function ownedValues(theme) {
|
|
|
65
71
|
/** The `$type` of each token an `extra` group holds, by path. */
|
|
66
72
|
const extraTypes = (theme) => Object.fromEntries(flatten(theme.extra ?? {}).map((t) => [['extra', ...t.path].join('.'), t.$type]));
|
|
67
73
|
|
|
68
|
-
const TYPES = { radius: 'number', border: 'number', icon: 'number', density: 'number', type: 'number', button: 'number', field: 'number', shadow: 'shadow', font: 'fontFamily', color: 'color' };
|
|
74
|
+
const TYPES = { duration: 'number', easing: 'cubicBezier', spring: 'number', radius: 'number', border: 'number', icon: 'number', density: 'number', type: 'number', button: 'number', field: 'number', shadow: 'shadow', font: 'fontFamily', color: 'color' };
|
|
69
75
|
const DESCRIPTIONS = {
|
|
70
76
|
'semantic.radius.control': 'Corner radius of mobile buttons and chips: rounded-control. 9999 = pills; otherwise the base radius.',
|
|
71
77
|
'semantic.border.width': 'Width of `border` (px). border-2 and border-hairline stay explicit.',
|
|
@@ -96,11 +102,11 @@ function typeOf(path) {
|
|
|
96
102
|
const parts = path.split('.');
|
|
97
103
|
if (parts[0] === 'semantic' && parts[1] === 'type' && parts.length === 4) return { font: 'fontFamily', weight: 'fontWeight' }[parts[3]] ?? 'number';
|
|
98
104
|
if (path === 'semantic.border.style') return 'strokeStyle';
|
|
99
|
-
if (parts[1] === 'component') return COLOR_SLOTS.has(parts.at(-1)) ? 'color' :
|
|
105
|
+
if (parts[1] === 'component') return COLOR_SLOTS.has(parts.at(-1)) ? 'color' : { font: 'fontFamily', weight: 'fontWeight' }[parts.at(-1)] ?? 'number';
|
|
100
106
|
return TYPES[parts[1]] ?? 'color';
|
|
101
107
|
}
|
|
102
108
|
|
|
103
|
-
const COLOR_SLOTS = new Set(['fill', 'label', 'border', 'pressed', 'ring']);
|
|
109
|
+
const COLOR_SLOTS = new Set(['fill', 'label', 'border', 'pressed', 'ring', 'focus-border', 'placeholder']);
|
|
104
110
|
/** What a component token is, for its $description (semantic.component.<name>.…). */
|
|
105
111
|
const COMPONENT_DESCRIPTION = {
|
|
106
112
|
radius: 'corner radius (px; 9999 = a pill)',
|
|
@@ -115,6 +121,16 @@ const COMPONENT_DESCRIPTION = {
|
|
|
115
121
|
'text.leading': 'line height (px), fitted to the control',
|
|
116
122
|
'text.tracking': 'letter spacing (em)',
|
|
117
123
|
'text.font': "the text style's font",
|
|
124
|
+
'text.weight': "the label's font weight",
|
|
125
|
+
'text.uppercase': '1 = uppercase labels',
|
|
126
|
+
'gap.sm': 'small gap between an icon and the label (px)',
|
|
127
|
+
'gap.md': 'gap between an icon and the label (px)',
|
|
128
|
+
'gap.lg': 'large gap between an icon and the label (px)',
|
|
129
|
+
icon: 'icon size (px)',
|
|
130
|
+
shadow: 'shadow level (0 = none)',
|
|
131
|
+
'ring-width': 'focus ring width (px)',
|
|
132
|
+
'focus-border': 'border colour when focused (the focus ring role)',
|
|
133
|
+
placeholder: 'placeholder text colour (a role)',
|
|
118
134
|
fill: 'fill colour (a role)',
|
|
119
135
|
'fill-alpha': 'fill opacity',
|
|
120
136
|
label: 'label colour (a role)',
|
|
@@ -124,7 +140,7 @@ const COMPONENT_DESCRIPTION = {
|
|
|
124
140
|
'edge-width': 'bottom edge width (px)',
|
|
125
141
|
pressed: 'pressed and hover fill (derived from the fill unless set)',
|
|
126
142
|
'pressed-alpha': 'pressed and hover opacity',
|
|
127
|
-
ring: 'focus ring colour (the border, faded)',
|
|
143
|
+
ring: 'focus ring colour (a role or the border, faded)',
|
|
128
144
|
'ring-alpha': 'focus ring opacity',
|
|
129
145
|
alpha: "the style's fill opacity",
|
|
130
146
|
round: '1 = rounded top corners, 0 = square',
|
|
@@ -139,9 +155,18 @@ const TEXT_DESCRIPTION = {
|
|
|
139
155
|
tracking: 'letter spacing (em)',
|
|
140
156
|
font: 'font family (a role: heading, body or mono)',
|
|
141
157
|
};
|
|
158
|
+
const SPRING_DESCRIPTION = {
|
|
159
|
+
stiffness: 'stiffness (how hard it pulls toward rest)',
|
|
160
|
+
damping: 'damping (how quickly the bounce dies)',
|
|
161
|
+
mass: 'mass',
|
|
162
|
+
};
|
|
142
163
|
function describe(path) {
|
|
143
164
|
if (DESCRIPTIONS[path]) return DESCRIPTIONS[path];
|
|
144
165
|
const parts = path.split('.');
|
|
166
|
+
if (parts[0] === 'primitive' && parts[1] === 'duration') return `Duration (ms) for ${MOTION_USE.durations[parts[2]] ?? parts[2]}. Scaled by the theme's speed.`;
|
|
167
|
+
if (parts[0] === 'primitive' && parts[1] === 'easing') return `Easing for ${MOTION_USE.easings[parts[2]] ?? parts[2]}.`;
|
|
168
|
+
if (parts[0] === 'primitive' && parts[1] === 'spring' && parts.length === 4)
|
|
169
|
+
return `Spring ${parts[2]} (${MOTION_USE.springs[parts[2]] ?? 'a spring'}): ${SPRING_DESCRIPTION[parts[3]] ?? parts[3]}. DTCG has no spring type, so it is three numbers.`;
|
|
145
170
|
if (parts[1] === 'type' && parts.length === 4) return `Text ${parts[2]}: ${TEXT_DESCRIPTION[parts[3]] ?? parts[3]}. Edited in the system.`;
|
|
146
171
|
if (parts[1] === 'radius' && parts.length === 3) return `rounded-${parts[2]} (px), edited in the system; otherwise a multiple of the base radius.`;
|
|
147
172
|
if (path === 'semantic.border.style') return 'Border style: solid, dashed or dotted.';
|
package/lib/theme/codec.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* ht1- 12 characters, 60 bits: a theme with the default typeset (every code made before the typeset)
|
|
6
6
|
* ht2- 16 characters, 80 bits: a theme with the default styles (solid buttons, outline fields)
|
|
7
|
-
* ht3- 18 characters, 90 bits: any theme
|
|
7
|
+
* ht3- 18 characters, 90 bits: any theme (motion's speed included)
|
|
8
8
|
*
|
|
9
9
|
* bits field ht1 ht2 ht3
|
|
10
10
|
* recipe version (RECIPE_VERSION) 4 4 4
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
* stroke, depth, density, border 2+2+2+2 2+2+2+2 2+2+2+2
|
|
15
15
|
* size, leading, flow, measure – 3+3+3+3 3+3+3+3
|
|
16
16
|
* button, field – – 2+2
|
|
17
|
-
* reserved
|
|
17
|
+
* speed – – 2 (was reserved: an older ht3 reads as normal)
|
|
18
|
+
* reserved (zero: room for more styles) – – 4
|
|
18
19
|
* checksum (payload mod 127) 7 7 7 a typo is caught instead of making another theme
|
|
19
20
|
*
|
|
20
21
|
* encodeRecipe writes the shortest code that holds the theme (ht1, then ht2, then ht3), so a theme keeps the
|
|
@@ -22,7 +23,7 @@
|
|
|
22
23
|
* whichever preset it started from.
|
|
23
24
|
*/
|
|
24
25
|
import { FONTS } from './fonts.mjs';
|
|
25
|
-
import { defaultStyles, defaultTypeset, normalizeRecipe, OPTIONS, RECIPE_VERSION } from './recipe.mjs';
|
|
26
|
+
import { defaultMotion, defaultStyles, defaultTypeset, normalizeRecipe, OPTIONS, RECIPE_VERSION } from './recipe.mjs';
|
|
26
27
|
|
|
27
28
|
const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
28
29
|
const LAYOUT = [
|
|
@@ -46,7 +47,9 @@ const STYLES = [
|
|
|
46
47
|
['button', 2],
|
|
47
48
|
['field', 2],
|
|
48
49
|
];
|
|
49
|
-
|
|
50
|
+
/** Motion, in what were the first two reserved bits: zero is Speed normal, so every older ht3 code reads the same. */
|
|
51
|
+
const MOTION = [['speed', 2]];
|
|
52
|
+
const RESERVED = 4;
|
|
50
53
|
/** Per format: prefix, characters, font width, whether the typeset is in it. */
|
|
51
54
|
const FORMATS = {
|
|
52
55
|
ht1: { prefix: 'ht1-', chars: 12, font: 5, typeset: false, styles: false },
|
|
@@ -58,8 +61,9 @@ const fontIndex = (id) => FONTS.findIndex((f) => f.id === id);
|
|
|
58
61
|
|
|
59
62
|
export function encodeRecipe(input) {
|
|
60
63
|
const r = normalizeRecipe(input);
|
|
61
|
-
const
|
|
62
|
-
const
|
|
64
|
+
const plain = defaultStyles(r) && defaultMotion(r);
|
|
65
|
+
const ht1 = plain && defaultTypeset(r) && fontIndex(r.font.heading) < 32 && fontIndex(r.font.body) < 32;
|
|
66
|
+
const format = ht1 ? FORMATS.ht1 : plain ? FORMATS.ht2 : FORMATS.ht3;
|
|
63
67
|
let bits = BigInt(r.v);
|
|
64
68
|
const push = (value, width) => {
|
|
65
69
|
if (value < 0 || value >= 2 ** width) throw new Error(`encodeRecipe: ${value} does not fit in ${width} bits`);
|
|
@@ -74,6 +78,7 @@ export function encodeRecipe(input) {
|
|
|
74
78
|
if (format.typeset) for (const [key, width] of TYPESET) push(OPTIONS[key].indexOf(r[key]), width);
|
|
75
79
|
if (format.styles) {
|
|
76
80
|
for (const [key, width] of STYLES) push(OPTIONS[key].indexOf(r[key]), width);
|
|
81
|
+
for (const [key, width] of MOTION) push(OPTIONS[key].indexOf(r[key]), width);
|
|
77
82
|
push(0, RESERVED);
|
|
78
83
|
}
|
|
79
84
|
bits = (bits << 7n) | (bits % 127n);
|
|
@@ -121,6 +126,7 @@ export function decodeRecipe(code) {
|
|
|
121
126
|
const fields = (list) => Object.fromEntries([...list].reverse().map(([key, width]) => [key, opt(key, width)]));
|
|
122
127
|
// Read back to front. Reserved bits set means a newer halftone-tokens wrote styles this one doesn't know.
|
|
123
128
|
if (format.styles && pull(RESERVED) !== 0) throw new Error(`"${code}" is a newer theme code than this halftone-tokens reads. Update @halftone-ds/tokens.`);
|
|
129
|
+
const motion = format.styles ? fields(MOTION) : {};
|
|
124
130
|
const styles = format.styles ? fields(STYLES) : {};
|
|
125
131
|
const typeset = format.typeset ? fields(TYPESET) : {};
|
|
126
132
|
const tail = fields(TAIL);
|
|
@@ -131,7 +137,7 @@ export function decodeRecipe(code) {
|
|
|
131
137
|
const brand = '#' + pull(24).toString(16).padStart(6, '0');
|
|
132
138
|
const v = Number(bits);
|
|
133
139
|
if (v !== RECIPE_VERSION) throw new Error(`"${code}" is a version ${v} theme; this halftone-tokens reads version ${RECIPE_VERSION}. Update @halftone-ds/tokens.`);
|
|
134
|
-
return normalizeRecipe({ v, brand, ...head, font: { heading, body, ...(mono ? { mono } : {}) }, ...tail, ...typeset, ...styles });
|
|
140
|
+
return normalizeRecipe({ v, brand, ...head, font: { heading, body, ...(mono ? { mono } : {}) }, ...tail, ...typeset, ...styles, ...motion });
|
|
135
141
|
}
|
|
136
142
|
|
|
137
143
|
export const isThemeCode = (value) => /^(ht1-?[0-9a-z]{12}|ht2-?[0-9a-z]{16}|ht3-?[0-9a-z]{18})$/i.test(String(value).trim());
|