@halftone-ds/tokens 1.4.0 → 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.
@@ -27,6 +27,11 @@
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
+ * 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
30
35
  * components { button|chip|badge|input: { style?, radius?, border?, size?, text?, weight?, case?, icon?,
31
36
  * shadow?, ring?, placeholder?, variants? } } component-level edits (lib/theme/components.mjs),
32
37
  * overrides only, each where the component has it (COMPONENTS[name].props):
@@ -53,6 +58,7 @@ import { FONTS } from '../theme/fonts.mjs';
53
58
  import { STEPS } from '../theme/palettes.mjs';
54
59
  import { anchorStep, neutralAnchorStep } from '../theme/ramp.mjs';
55
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';
56
62
  import { normalizeRecipe, OPTIONS, TEXT_DEFAULTS, TEXT_STYLES } from '../theme/recipe.mjs';
57
63
  import { semanticColors } from '../theme/semantic.mjs';
58
64
 
@@ -70,6 +76,8 @@ export const SHADOW_LEVELS = ['1', '2', '3'];
70
76
  export const BORDER_STYLES = ['solid', 'dashed', 'dotted'];
71
77
  export const EXTRA_KINDS = ['color', 'text', 'radius', 'shadow', 'border'];
72
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 };
73
81
  export { TEXT_DEFAULTS, TEXT_STYLES };
74
82
 
75
83
 
@@ -405,6 +413,39 @@ function components(r, input, recipe) {
405
413
  return out;
406
414
  }
407
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
+
408
449
  /** Is this a system document (rather than a bare recipe)? */
409
450
  export const isSystem = (value) => isObject(value) && (value.kind === SYSTEM_KIND || isObject(value.recipe));
410
451
 
@@ -414,7 +455,7 @@ function read(input) {
414
455
  if (input.kind !== undefined && input.kind !== SYSTEM_KIND) r.fail('kind', `must be "${SYSTEM_KIND}"`);
415
456
  if (input.v !== undefined && !(Number.isInteger(input.v) && input.v >= 1)) r.fail('v', 'must be a version number');
416
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`]);
417
- 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']);
418
459
 
419
460
  let recipe;
420
461
  try {
@@ -478,6 +519,7 @@ function read(input) {
478
519
  doc.brand = brand(r, input.brand);
479
520
 
480
521
  doc.components = components(r, input.components, recipe);
522
+ doc.motion = motion(r, input.motion);
481
523
  return { doc, errors: r.errors };
482
524
  }
483
525
 
@@ -527,6 +569,7 @@ export function systemOverrides(input) {
527
569
  for (const key of Object.keys(entry.size ?? {})) paths.push(`components.${name}.size.${key}`);
528
570
  for (const [variant, slots] of Object.entries(entry.variants ?? {})) for (const slot of Object.keys(slots)) paths.push(`components.${name}.variants.${variant}.${slot}`);
529
571
  }
572
+ for (const [group, entries] of Object.entries(doc.motion)) for (const name of Object.keys(entries)) paths.push(`motion.${group}.${name}`);
530
573
  return paths;
531
574
  }
532
575
 
@@ -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, motion, descriptions) is left exactly as it was. The recipe is
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.',
@@ -149,9 +155,18 @@ const TEXT_DESCRIPTION = {
149
155
  tracking: 'letter spacing (em)',
150
156
  font: 'font family (a role: heading, body or mono)',
151
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
+ };
152
163
  function describe(path) {
153
164
  if (DESCRIPTIONS[path]) return DESCRIPTIONS[path];
154
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.`;
155
170
  if (parts[1] === 'type' && parts.length === 4) return `Text ${parts[2]}: ${TEXT_DESCRIPTION[parts[3]] ?? parts[3]}. Edited in the system.`;
156
171
  if (parts[1] === 'radius' && parts.length === 3) return `rounded-${parts[2]} (px), edited in the system; otherwise a multiple of the base radius.`;
157
172
  if (path === 'semantic.border.style') return 'Border style: solid, dashed or dotted.';
@@ -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 (zero: room for more styles) – – 6
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
- const RESERVED = 6;
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 ht1 = defaultStyles(r) && defaultTypeset(r) && fontIndex(r.font.heading) < 32 && fontIndex(r.font.body) < 32;
62
- const format = ht1 ? FORMATS.ht1 : defaultStyles(r) ? FORMATS.ht2 : FORMATS.ht3;
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());
@@ -17,6 +17,7 @@ import { fixContrast } from './fix.mjs';
17
17
  import { encodeRecipe } from './codec.mjs';
18
18
  import { fontById } from './fonts.mjs';
19
19
  import { componentLayer } from './components.mjs';
20
+ import { motionFor } from './motion.mjs';
20
21
  import { BORDER, BUTTON, DENSITY, DEPTH, FIELD, fieldWidth, FLOW, LEADING, normalizeRecipe, RADIUS, resolveTextStyles, STROKE, textEdits, typeScale } from './recipe.mjs';
21
22
  import { anchorStep, brandRamp, neutralRamp } from './ramp.mjs';
22
23
  import { resolvedMap } from './refs.mjs';
@@ -144,6 +145,8 @@ export function generateTheme(input, base, { fix = true, colors: system } = {})
144
145
  button,
145
146
  field: { ...field, radius: lookup(radiusValue) * md * fld.round, radiusBottom: lookup(radiusValue) * md * fld.roundBottom },
146
147
  stroke: STROKE[recipe.stroke],
148
+ // Durations, easings and springs at the recipe's speed (a system's motion edits go on top in generateSystem).
149
+ motion: motionFor(recipe.speed),
147
150
  adjustments,
148
151
  warnings,
149
152
  };
@@ -16,6 +16,17 @@ export type Flow = 'normal' | 'tight' | 'loose';
16
16
  export type Measure = '70' | '60' | '80' | '90';
17
17
  export type ButtonStyle = 'solid' | 'soft' | 'outline' | 'raised';
18
18
  export type FieldStyle = 'outline' | 'filled' | 'underline';
19
+ /** Motion's speed: every duration and spring at ×1, ×0.75, ×1.25 or ×1.5. */
20
+ export type Speed = 'normal' | 'snappy' | 'relaxed' | 'slow';
21
+ export type DurationName = 'fast' | 'base' | 'slow';
22
+ export type EasingName = 'standard' | 'emphasized' | 'exit';
23
+ export type SpringName = 'snappy' | 'gentle';
24
+ export type CubicBezier = [number, number, number, number];
25
+ export type SpringPhysics = { stiffness: number; damping: number; mass: number };
26
+ /** Durations (ms), easings and springs, as a theme draws them. */
27
+ export type Motion = { durations: Record<DurationName, number>; easings: Record<EasingName, CubicBezier>; springs: Record<SpringName, SpringPhysics> };
28
+ /** A system's motion edits: set values, over the speed. */
29
+ export type MotionEdits = { durations?: Partial<Record<DurationName, number>>; easings?: Partial<Record<EasingName, CubicBezier>>; springs?: Partial<Record<SpringName, SpringPhysics>> };
19
30
  export type Mode = 'light' | 'dark';
20
31
  export type CvdType = 'protanopia' | 'deuteranopia' | 'tritanopia';
21
32
  /** A pair of tones as one vision sees them: `fg` and `bg` are the simulated hex of `a` and `b`. */
@@ -41,6 +52,8 @@ export type Recipe = {
41
52
  button: ButtonStyle;
42
53
  /** Text fields' style (inputs, text areas, select triggers). */
43
54
  field: FieldStyle;
55
+ /** Motion: how quick every duration and spring is. */
56
+ speed: Speed;
44
57
  preset?: string;
45
58
  };
46
59
  export type RecipeInput = Partial<Omit<Recipe, 'font'>> & { font?: Partial<Recipe['font']> };
@@ -76,6 +89,8 @@ export type Theme = {
76
89
  field: { alpha: Record<Mode, number>; border: number; edge: number; inset: number; radius: number; radiusBottom: number };
77
90
  /** The component layer (Button, Chip, Badge, Input), resolved: what both kits draw. */
78
91
  components: ComponentShapes;
92
+ /** Durations, easings and springs at the recipe's speed, with a system's motion edits on top. */
93
+ motion: Motion;
79
94
  [key: string]: unknown;
80
95
  };
81
96
 
@@ -199,9 +214,30 @@ export const OPTIONS: {
199
214
  measure: Measure[];
200
215
  button: ButtonStyle[];
201
216
  field: FieldStyle[];
217
+ speed: Speed[];
202
218
  };
203
219
  export const TYPESET_KEYS: ['size', 'leading', 'flow', 'measure'];
204
220
  export const STYLE_KEYS: ['button', 'field'];
221
+ export const MOTION_KEYS: ['speed'];
222
+ export function defaultMotion(recipe: Recipe): boolean;
223
+ /** Speed's factor per step. */
224
+ export const SPEED: Record<Speed, number>;
225
+ export const DURATION_NAMES: DurationName[];
226
+ export const EASING_NAMES: EasingName[];
227
+ export const SPRING_NAMES: SpringName[];
228
+ /** The kits' timings at Speed normal. */
229
+ export const MOTION_DEFAULTS: Readonly<Motion>;
230
+ /** What each duration, easing and spring is for. */
231
+ export const MOTION_USE: { durations: Record<DurationName, string>; easings: Record<EasingName, string>; springs: Record<SpringName, string> };
232
+ /** The motion a speed and a system's edits make. */
233
+ export function motionFor(speed?: Speed, edits?: MotionEdits): Motion;
234
+ /** A spring that plays `factor` times as long, with the same bounce. */
235
+ export function scaleSpring(spring: SpringPhysics, factor: number): SpringPhysics;
236
+ /** A spring as CSS: a linear() easing and its duration (ms). */
237
+ export function springCss(spring: SpringPhysics, points?: number): { easing: string; duration: number };
238
+ export function bezierCss(curve: CubicBezier): string;
239
+ /** --duration-*, --ease-* and --spring-* (with --spring-*-duration). */
240
+ export function motionVars(motion: Motion): Record<string, string>;
205
241
  export const LEADING: Record<Leading, number>;
206
242
  export const FLOW: Record<Flow, number>;
207
243
  export const FONTS: Font[];
@@ -5,10 +5,11 @@
5
5
  */
6
6
  export { generateTheme } from './generate.mjs';
7
7
  export { encodeRecipe, decodeRecipe, isThemeCode } from './codec.mjs';
8
- export { DEFAULT_RECIPE, defaultStyles, defaultTypeset, FLOW, LEADING, OPTIONS, normalizeRecipe, sameRecipe, RECIPE_VERSION, resolveTextStyles, STYLE_KEYS, TEXT_DEFAULTS, TEXT_STYLES, textEdits, TYPESET_KEYS } from './recipe.mjs';
8
+ export { bezierCss, DURATION_NAMES, EASING_NAMES, MOTION_DEFAULTS, MOTION_USE, motionFor, scaleSpring, SPEED, SPRING_NAMES, springCss } from './motion.mjs';
9
+ export { DEFAULT_RECIPE, defaultMotion, defaultStyles, defaultTypeset, MOTION_KEYS, FLOW, LEADING, OPTIONS, normalizeRecipe, sameRecipe, RECIPE_VERSION, resolveTextStyles, STYLE_KEYS, TEXT_DEFAULTS, TEXT_STYLES, textEdits, TYPESET_KEYS } from './recipe.mjs';
9
10
  export { FONTS, fontByFamily, fontById, googleFontsHref } from './fonts.mjs';
10
11
  export { PRESETS, presetById } from './presets.mjs';
11
- export { styleVars, textStyleVars, themeTextStyles, themeVars, themeCss, themeHex, typeVars } from './vars.mjs';
12
+ export { motionVars, styleVars, textStyleVars, themeTextStyles, themeVars, themeCss, themeHex, typeVars } from './vars.mjs';
12
13
  export { applyRecipe, themeStatus, THEME_EXTENSION } from './apply.mjs';
13
14
  // Systems (lib/system): also @halftone-ds/tokens/system.
14
15
  export * from '../system/index.mjs';
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Motion: the durations, easings and springs a theme sets, and the Speed knob that scales them. Pure ESM.
3
+ *
4
+ * durations fast | base | slow, ms primitive.duration.* (number)
5
+ * easings standard | emphasized | exit, cubic-bezier primitive.easing.* (cubicBezier)
6
+ * springs snappy | gentle, { stiffness, damping, mass } primitive.spring.*.* (numbers: DTCG has no spring type)
7
+ *
8
+ * The recipe's `speed` scales every duration and every spring's time (a spring's stiffness by 1 / f², its damping by
9
+ * 1 / f, so it keeps its bounce). A system's motion edits are set values on top, not scaled.
10
+ */
11
+
12
+ /** Speed: how much longer (> 1) or shorter (< 1) everything takes than the kits' own timings. */
13
+ export const SPEED = { normal: 1, snappy: 0.75, relaxed: 1.25, slow: 1.5 };
14
+
15
+ export const DURATION_NAMES = ['fast', 'base', 'slow'];
16
+ export const EASING_NAMES = ['standard', 'emphasized', 'exit'];
17
+ export const SPRING_NAMES = ['snappy', 'gentle'];
18
+ export const SPRING_KEYS = ['stiffness', 'damping', 'mass'];
19
+
20
+ /** The kits' timings at Speed normal: what tokens.json has always had, plus the two springs. */
21
+ export const MOTION_DEFAULTS = Object.freeze({
22
+ durations: Object.freeze({ fast: 150, base: 200, slow: 300 }),
23
+ easings: Object.freeze({ standard: [0.2, 0, 0, 1], emphasized: [0.3, 0, 0, 1], exit: [0.4, 0, 1, 1] }),
24
+ springs: Object.freeze({
25
+ // A press, a toggle, a chip: quick, barely past the mark.
26
+ snappy: Object.freeze({ stiffness: 400, damping: 36, mass: 1 }),
27
+ // A sheet, a card settling in: slower, with a little give.
28
+ gentle: Object.freeze({ stiffness: 120, damping: 18, mass: 1 }),
29
+ }),
30
+ });
31
+
32
+ /** What each value is for: tokens.json's $description and the guides. */
33
+ export const MOTION_USE = {
34
+ durations: { fast: 'hover and small feedback', base: 'most transitions', slow: 'sheets and large surfaces' },
35
+ easings: { standard: 'most movement', emphasized: 'entering, drawing the eye', exit: 'leaving the screen' },
36
+ springs: { snappy: 'presses, toggles, small moves', gentle: 'sheets, cards settling in' },
37
+ };
38
+
39
+ const round = (n, places = 2) => Number(n.toFixed(places));
40
+
41
+ /** A spring that plays `factor` times as long, with the same bounce. */
42
+ export function scaleSpring({ stiffness, damping, mass }, factor) {
43
+ return { stiffness: round(stiffness / factor ** 2), damping: round(damping / factor), mass };
44
+ }
45
+
46
+ /**
47
+ * The motion a recipe's speed and a system's edits make: { durations, easings, springs }. `edits` is a system's
48
+ * `motion` ({ durations?, easings?, springs? }), set values that Speed doesn't scale.
49
+ */
50
+ export function motionFor(speed = 'normal', edits = {}) {
51
+ const f = SPEED[speed] ?? 1;
52
+ const d = MOTION_DEFAULTS;
53
+ return {
54
+ durations: Object.fromEntries(DURATION_NAMES.map((n) => [n, edits.durations?.[n] ?? Math.round(d.durations[n] * f)])),
55
+ easings: Object.fromEntries(EASING_NAMES.map((n) => [n, (edits.easings?.[n] ?? d.easings[n]).slice()])),
56
+ springs: Object.fromEntries(SPRING_NAMES.map((n) => [n, edits.springs?.[n] ? { ...edits.springs[n] } : f === 1 ? { ...d.springs[n] } : scaleSpring(d.springs[n], f)])),
57
+ };
58
+ }
59
+
60
+ /** Where a spring released from 0 at rest is after `t` seconds, heading for 1 (the damped oscillator, exactly). */
61
+ export function springAt({ stiffness, damping, mass }, t) {
62
+ if (t <= 0) return 0;
63
+ const m = Math.max(mass, 0.001);
64
+ const k = Math.max(stiffness, 1e-9);
65
+ const w0 = Math.sqrt(k / m);
66
+ const zeta = damping / (2 * Math.sqrt(k * m));
67
+ if (zeta < 1 - 1e-9) {
68
+ const wd = w0 * Math.sqrt(1 - zeta * zeta);
69
+ return 1 - Math.exp(-zeta * w0 * t) * (Math.cos(wd * t) + ((zeta * w0) / wd) * Math.sin(wd * t));
70
+ }
71
+ if (zeta <= 1 + 1e-9) return 1 - Math.exp(-w0 * t) * (1 + w0 * t);
72
+ const s = Math.sqrt(zeta * zeta - 1);
73
+ const r1 = -w0 * (zeta - s);
74
+ const r2 = -w0 * (zeta + s);
75
+ return 1 - (r2 * Math.exp(r1 * t) - r1 * Math.exp(r2 * t)) / (r2 - r1);
76
+ }
77
+
78
+ /** Seconds until the spring stays within 0.001 of rest (capped at 10 for one that never settles). */
79
+ export function settleTime(spring, { restDelta = 0.001, max = 10 } = {}) {
80
+ const dt = 1 / 240;
81
+ let last = 0;
82
+ for (let t = 0; t <= max; t += dt) if (Math.abs(springAt(spring, t) - 1) > restDelta) last = t;
83
+ return round(Math.min(max, last + dt), 3);
84
+ }
85
+
86
+ /**
87
+ * A spring as CSS: a `linear()` easing and its duration in ms, so a plain transition plays it (the web kit's
88
+ * --spring-<name> and --spring-<name>-duration).
89
+ */
90
+ export function springCss(spring, points = 32) {
91
+ const span = Math.max(settleTime(spring), 0.05);
92
+ const values = Array.from({ length: points + 1 }, (_, i) => round(springAt(spring, (i / points) * span), 4));
93
+ // At rest it is within 0.001 of the end: land exactly on it, so the transition doesn't jump when it finishes.
94
+ values[points] = 1;
95
+ return { easing: `linear(${values.join(', ')})`, duration: Math.round(span * 1000) };
96
+ }
97
+
98
+ /** `cubic-bezier(0.2, 0, 0, 1)` */
99
+ export const bezierCss = (curve) => `cubic-bezier(${curve.join(', ')})`;
@@ -7,7 +7,8 @@
7
7
  * The typeset (font.mono, size, leading, flow, measure) came later. A recipe without it gets the defaults,
8
8
  * which are what the kits always had, and a theme with the default typeset still encodes as a ht1 code.
9
9
  * So did the styles (button, field): their defaults are the kits' original look, and a theme that keeps them
10
- * encodes as ht1 or ht2 as before.
10
+ * encodes as ht1 or ht2 as before. Motion's speed came last, in two of ht3's reserved bits: a theme at Speed normal
11
+ * keeps the code it had.
11
12
  */
12
13
  import { FONTS } from './fonts.mjs';
13
14
 
@@ -40,12 +41,16 @@ export const OPTIONS = {
40
41
  button: ['solid', 'soft', 'outline', 'raised'],
41
42
  /** Style: text fields (inputs, text areas, select triggers). A box, a tinted field with a line, or a line. */
42
43
  field: ['outline', 'filled', 'underline'],
44
+ /** Motion: every duration and spring, quicker or slower than the kits' own (lib/theme/motion.mjs SPEED). */
45
+ speed: ['normal', 'snappy', 'relaxed', 'slow'],
43
46
  };
44
47
 
45
48
  /** The recipe keys that make up the typeset, besides font.mono. */
46
49
  export const TYPESET_KEYS = ['size', 'leading', 'flow', 'measure'];
47
50
  /** The recipe keys that are component styles (ht3 codes). */
48
51
  export const STYLE_KEYS = ['button', 'field'];
52
+ /** The recipe keys that are motion (ht3 codes, in bits that were reserved). */
53
+ export const MOTION_KEYS = ['speed'];
49
54
 
50
55
  /** Base radius per option: a primitive radius step (a reference) or 0. */
51
56
  export const RADIUS = { none: 0, sm: 'sm', md: 'md', lg: 'lg', xl: 'xl', '2xl': '2xl' };
@@ -238,6 +243,7 @@ export const DEFAULT_RECIPE = Object.freeze({
238
243
  measure: '70',
239
244
  button: 'solid',
240
245
  field: 'outline',
246
+ speed: 'normal',
241
247
  });
242
248
 
243
249
  const HEX = /^#[0-9a-f]{6}$/;
@@ -248,6 +254,9 @@ export const defaultTypeset = (r) => r.font.mono === DEFAULT_RECIPE.font.mono &&
248
254
  /** Does the recipe keep the default styles (solid buttons, outline fields: every ht1 and ht2 code)? */
249
255
  export const defaultStyles = (r) => STYLE_KEYS.every((k) => r[k] === DEFAULT_RECIPE[k]);
250
256
 
257
+ /** Does the recipe keep the default motion (Speed normal: every code before motion)? */
258
+ export const defaultMotion = (r) => MOTION_KEYS.every((k) => r[k] === DEFAULT_RECIPE[k]);
259
+
251
260
  /** Fill in defaults, normalise, and throw on anything invalid. Returns a new, plain recipe. */
252
261
  export function normalizeRecipe(input = {}) {
253
262
  const r = { ...DEFAULT_RECIPE, ...input, font: { ...DEFAULT_RECIPE.font, ...input.font } };
@@ -282,6 +291,7 @@ export function normalizeRecipe(input = {}) {
282
291
  measure: r.measure,
283
292
  button: r.button,
284
293
  field: r.field,
294
+ speed: r.speed,
285
295
  };
286
296
  if (input.preset) out.preset = String(input.preset);
287
297
  return out;
@@ -7,6 +7,7 @@
7
7
  import { hexToHslTriplet, hexToOklch } from '../color.mjs';
8
8
  import { componentVars } from './components.mjs';
9
9
  import { extraList, extraTextStyles } from './extras.mjs';
10
+ import { bezierCss, springCss } from './motion.mjs';
10
11
  import { resolveTextStyles, shadowCss, textEdits } from './recipe.mjs';
11
12
 
12
13
  export const rem = (px) => (px >= 9999 ? '9999px' : `${px / 16}rem`);
@@ -93,6 +94,22 @@ export function extraVars(list, format, font) {
93
94
  return { light, dark };
94
95
  }
95
96
 
97
+ /**
98
+ * Motion as CSS variables, the same in both modes: --duration-fast|base|slow (ms), --ease-standard|emphasized|exit
99
+ * (cubic-bezier), and each spring as --spring-<name> (a linear() easing) with --spring-<name>-duration.
100
+ */
101
+ export function motionVars(motion) {
102
+ const vars = {};
103
+ for (const [name, ms] of Object.entries(motion.durations)) vars[`--duration-${name}`] = `${ms}ms`;
104
+ for (const [name, curve] of Object.entries(motion.easings)) vars[`--ease-${name}`] = bezierCss(curve);
105
+ for (const [name, spring] of Object.entries(motion.springs)) {
106
+ const css = springCss(spring);
107
+ vars[`--spring-${name}`] = css.easing;
108
+ vars[`--spring-${name}-duration`] = `${css.duration}ms`;
109
+ }
110
+ return vars;
111
+ }
112
+
96
113
  /** { light: { '--primary': '…', '--radius': '0.625rem' }, dark: { … } } (a system's extras too) */
97
114
  export function themeVars(theme, format) {
98
115
  const convert = format === 'hsl' ? hexToHslTriplet : hexToOklch;
@@ -106,6 +123,7 @@ export function themeVars(theme, format) {
106
123
  vars['--density'] = String(theme.density.scale);
107
124
  for (const size of ['sm', 'md', 'lg', 'x']) vars[`--control-${size}`] = `${theme.density[size]}px`;
108
125
  Object.assign(vars, typeVars(theme.type), textStyleVars(themeTextStyles(theme), format));
126
+ if (theme.motion) Object.assign(vars, motionVars(theme.motion));
109
127
  }
110
128
  Object.assign(vars, styleVars(theme, format)[m]);
111
129
  if (theme.components) Object.assign(vars, componentVars(theme.components, format, convert)[m]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halftone-ds/tokens",
3
- "version": "1.4.0",
3
+ "version": "1.5.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",
@@ -104,7 +104,10 @@ export default function designMd(ctx, options) {
104
104
  const hex = Object.fromEntries(ctx.colors.map((c) => [c.name, c.light]));
105
105
  const darkHex = Object.fromEntries(ctx.colors.map((c) => [c.name, c.dark]));
106
106
  const radius = Object.fromEntries(group(ctx.prim, ['radius']).map((t) => [t.key, t.value]));
107
- const duration = Object.fromEntries(group(ctx.prim, ['duration']).map((t) => [t.key, t.value]));
107
+ const duration = ctx.motion.durations;
108
+ const springLine = Object.entries(ctx.motion.springs)
109
+ .map(([n, s]) => `${n} (stiffness ${s.stiffness}, damping ${s.damping}, mass ${s.mass})`)
110
+ .join(' and ');
108
111
 
109
112
  // A system's own tokens: listed, never in the front matter's shared vocabulary.
110
113
  const extras = describeExtras(ctx.extras ?? { color: [], text: [], radius: [], shadow: [], border: [] }, { platform: options.platform ?? 'mobile' });
@@ -220,8 +223,10 @@ ${radius['2xl']}px; chips, avatars and dots are fully round.
220
223
  Only components listed in the registry in \`DESIGN_SYSTEM.md\` exist. ${STYLE_TEXT.button[ctx.styles.button]} ${STYLE_TEXT.field[ctx.styles.field]}
221
224
  Button, Chip, Badge and Input draw the theme's component tokens, the same in both kits: ${describeComponents(ctx.components).join('; ')}.
222
225
  Never restyle them by hand. Phones raise any tap target under 44px to 44.
223
- Motion: ${duration.fast}ms for micro-feedback, ${duration.base}ms for most transitions, ${duration.slow}ms for sheets, and
224
- nothing moves when the OS asks for reduced motion.
226
+ Motion: ${duration.fast}ms for micro-feedback, ${duration.base}ms for most transitions, ${duration.slow}ms for sheets; the
227
+ standard easing (cubic-bezier(${ctx.motion.easings.standard.join(', ')})) for most movement, emphasized for entering,
228
+ exit for leaving; springs ${springLine} for motion that should feel physical. Nothing moves when the OS asks for
229
+ reduced motion.
225
230
 
226
231
  ## Do's and Don'ts
227
232
 
package/targets/figma.mjs CHANGED
@@ -25,6 +25,9 @@ export default function figma(ctx, options) {
25
25
  'font-size': num(['font', 'size'], (k) => `text-${k}`),
26
26
  border: { width: { value: ctx.shape.borderWidth, code: 'border' } },
27
27
  icon: { stroke: { value: ctx.shape.stroke, code: 'strokeWidth' } },
28
+ // Durations only: Figma variables hold numbers, and easings and springs have no variable type (set them on
29
+ // prototype transitions by hand: they are in DESIGN.md).
30
+ duration: Object.fromEntries(Object.entries(ctx.motion.durations).map(([n, ms]) => [n, { value: ms, code: `duration-${n}` }])),
28
31
  };
29
32
  const fonts = themeFonts(ctx);
30
33
  const strings = {
package/targets/llms.mjs CHANGED
@@ -42,7 +42,7 @@ ${rows}
42
42
  - Fonts: headings ${fonts.heading?.family ?? 'system'}, body ${fonts.body?.family ?? 'system'}, mono ${fonts.mono?.family ?? 'system'} (applied by Text; \`font-heading\` makes any Text a heading, \`font-mono\` code and figures)
43
43
  - Typeset: body ${ctx.type.size}px, leading ${ctx.type.leading}; every \`text-*\` size below scales by ${ctx.type.scale}${theme.applied ? `\n- Theme: \`${theme.code}\` (\`npx halftone-tokens theme show\`)` : ''}
44
44
  - Font sizes (\`text-*\`): ${steps(['font', 'size'])}
45
- - Durations: ${steps(['duration'], 'ms')}
45
+ - Motion: durations ${Object.entries(ctx.motion.durations).map(([n, ms]) => `${n} ${ms}ms`).join(' · ')} (\`duration-fast\`…); easings ${Object.entries(ctx.motion.easings).map(([n, c]) => `${n} cubic-bezier(${c.join(', ')})`).join(' · ')} (\`ease-standard\`…); springs ${Object.entries(ctx.motion.springs).map(([n, s]) => `${n} stiffness ${s.stiffness}, damping ${s.damping}, mass ${s.mass}`).join(' · ')} (\`MOTION.spring.snappy\` in lib/theme.ts${options.platform === 'web' ? ', `spring-snappy` on the web' : ''}). Nothing moves under reduced motion
46
46
  ${extras.length ? `\n### Extras (this brand's own)\n\nNo kit component uses these; screens may, as classes (never their hex):\n\n${extras.join('\n')}\n` : ''}`;
47
47
  return [{ path: options.out, contents }];
48
48
  }
@@ -138,7 +138,10 @@ ${cssBlock('.dark:root', ctx.semDark, { styleShape: ctx.shape, extras: ctx.extra
138
138
  letterSpacing[`type-${name}`] = `var(--type-${name}-tracking)`;
139
139
  fontWeight[`type-${name}`] = `var(--type-${name}-weight)`;
140
140
  }
141
- const extend = { colors, borderRadius, borderWidth, boxShadow, height, minHeight: height, width: height, spacing, fontSize, lineHeight, letterSpacing, fontWeight, maxWidth };
141
+ // Motion: duration-fast|base|slow and ease-standard|emphasized|exit (springs are in lib/theme.ts MOTION).
142
+ const transitionDuration = Object.fromEntries(Object.entries(ctx.motion.durations).map(([n, ms]) => [n, `${ms}ms`]));
143
+ const transitionTimingFunction = Object.fromEntries(Object.entries(ctx.motion.easings).map(([n, c]) => [n, `cubic-bezier(${c.join(', ')})`]));
144
+ const extend = { colors, borderRadius, borderWidth, boxShadow, height, minHeight: height, width: height, spacing, fontSize, lineHeight, letterSpacing, fontWeight, maxWidth, transitionDuration, transitionTimingFunction };
142
145
  const files = [{ path: options.css, contents: css }];
143
146
  if (options.tailwind) files.push({ path: options.tailwind, contents: `// ${ctx.header}\nmodule.exports = ${JSON.stringify(extend, null, 2)};\n` });
144
147
  if (options.preset) {