@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.
@@ -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
 
@@ -106,16 +121,41 @@ export type ComponentShape = {
106
121
  h: Partial<Record<'sm' | 'md' | 'lg', number>>;
107
122
  /** Horizontal padding (px) by size. */
108
123
  x: Partial<Record<'sm' | 'md' | 'lg', number>>;
109
- /** Font role, size and line height (px), tracking (em); `style` the text style it follows. */
110
- text: { style?: string; font: 'heading' | 'body' | 'mono'; size: number; leading: number; tracking: number };
124
+ /** Font role, size and line height (px), tracking (em), the label's weight and case; `style` the text style it follows. */
125
+ text: { style?: string; font: 'heading' | 'body' | 'mono'; size: number; leading: number; tracking: number; weight: number; case: ComponentCase };
126
+ /** The border width set on the component (px), or null: as the style draws it. */
127
+ border?: number | null;
128
+ /** Chip, Badge and Input: the drawn border and bottom edge (px). Button's are per variant. */
129
+ borderWidth?: number;
130
+ edgeWidth?: number;
131
+ /** The gap between an icon and the label (px) by size; Input has none. */
132
+ gap?: Partial<Record<'sm' | 'md' | 'lg', number>>;
133
+ /** Icon size (px): ICON_DEFAULT until a system sets one. */
134
+ icon?: number;
135
+ /** Button and Input: a Foundations shadow level, or 'none' (defaultShadow until a system sets one). */
136
+ shadow?: ComponentShadow;
137
+ /** Button and Input: the focus ring's width (px) and role (null: derived). */
138
+ ring?: { width: number; role: string | null };
139
+ /** Button: the focused border (the ring's role). */
140
+ focusBorder?: ComponentColor;
141
+ /** Input: the placeholder's colour. */
142
+ placeholder?: ComponentColor;
111
143
  variants: Record<string, ComponentVariant>;
112
144
  };
145
+ export type ComponentCase = 'none' | 'uppercase';
146
+ export type ComponentShadow = 'none' | '1' | '2' | '3';
147
+ export type ComponentProp = 'border' | 'weight' | 'case' | 'icon' | 'shadow' | 'ring' | 'placeholder';
113
148
  export type ComponentShapes = Record<ComponentName, ComponentShape>;
114
149
  export type ComponentDefinition = {
115
150
  prefix: string;
116
151
  label: string;
117
152
  styles: string[];
118
- sizes: Array<'sm' | 'md' | 'lg' | 'x'>;
153
+ /** The size steps it has (heights). */
154
+ steps: Array<'sm' | 'md' | 'lg'>;
155
+ /** The size keys a system may set: the steps, padding and (not Input) the icon gap. */
156
+ sizes: Array<'sm' | 'md' | 'lg' | 'x' | 'gap'>;
157
+ /** The properties beyond style, corner, size and text it has. */
158
+ props: ComponentProp[];
119
159
  variants: Record<string, ComponentSlot[]>;
120
160
  text: string;
121
161
  };
@@ -124,6 +164,14 @@ export const COMPONENTS: Record<ComponentName, ComponentDefinition>;
124
164
  export const CORNERS: Corner[];
125
165
  export const SLOTS: ComponentSlot[];
126
166
  export const SLOT_VAR: Record<ComponentSlot | 'ring', string>;
167
+ export const WEIGHTS: number[];
168
+ export const CASES: ComponentCase[];
169
+ export const SHADOWS: ComponentShadow[];
170
+ /** The icon size (px) each component draws on the web until a system sets one. */
171
+ export const ICON_DEFAULT: Record<'button' | 'chip' | 'badge', number>;
172
+ export const RING_WIDTH: number;
173
+ /** A component's shadow until a system sets one: Button '1'; Input '1' for a boxed field (a border), else 'none'. */
174
+ export function defaultShadow(name: ComponentName, borderWidth?: number): ComponentShadow;
127
175
  /** The touch-target floor (px) the mobile kit applies on phones. */
128
176
  export const TOUCH_TARGET: number;
129
177
  export function defaultCorner(name: ComponentName, options?: { controls?: string; style?: string }): Corner;
@@ -166,9 +214,30 @@ export const OPTIONS: {
166
214
  measure: Measure[];
167
215
  button: ButtonStyle[];
168
216
  field: FieldStyle[];
217
+ speed: Speed[];
169
218
  };
170
219
  export const TYPESET_KEYS: ['size', 'leading', 'flow', 'measure'];
171
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>;
172
241
  export const LEADING: Record<Leading, number>;
173
242
  export const FLOW: Record<Flow, number>;
174
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';
@@ -27,6 +28,7 @@ export { CVD_TYPES, cvdWarnings, describeCvdWarnings, DISTINCT_PAIRS, MIN_DELTA_
27
28
 
28
29
  export { AA, AA_NON_TEXT, componentContrast, contrastPairs, contrastReport } from '../contrast.mjs';
29
30
  export {
31
+ CASES,
30
32
  COMPONENT_NAMES,
31
33
  COMPONENTS,
32
34
  componentColors,
@@ -35,10 +37,15 @@ export {
35
37
  componentVars,
36
38
  CORNERS,
37
39
  defaultCorner,
40
+ defaultShadow,
38
41
  defaultStyle,
39
42
  fittedLeading,
43
+ ICON_DEFAULT,
44
+ RING_WIDTH,
45
+ SHADOWS,
40
46
  SLOT_VAR,
41
47
  SLOTS,
42
48
  TOUCH_TARGET,
49
+ WEIGHTS,
43
50
  } from './components.mjs';
44
51
  export { apcaContrast } from '../apca.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;
@@ -20,6 +20,29 @@ export const darkStep = (anchor) => DARK_STEP[anchor] ?? anchor;
20
20
  const STATUS_STEPS = { danger: [0, -1], success: [1, -1], warning: [1, -2], info: [1, -1] };
21
21
  const status = (ramp, anchor = '600') => ({ light: p(ramp, shift(anchor, STATUS_STEPS[ramp][0])), dark: p(ramp, shift(anchor, STATUS_STEPS[ramp][1])) });
22
22
 
23
+ /**
24
+ * The tints: colours come from the ramps, not from opacity (a colour at partial opacity takes on whatever is
25
+ * behind it, so its contrast changes with the surface). `<tone>-subtle` is a tinted surface (an Alert, an
26
+ * IconCircle, a selected card), `<tone>-border` its edge: a light step on a light page, a dark one on a dark page.
27
+ * Text on a tint is `foreground`; the tone itself is an icon or a dot on it (contrast.mjs checks both).
28
+ */
29
+ const TINT_TONES = { primary: 'brand', success: 'success', warning: 'warning', destructive: 'danger', info: 'info' };
30
+ export const TINT_ROLES = Object.keys(TINT_TONES).flatMap((tone) => [`${tone}-subtle`, `${tone}-border`]);
31
+ const tints = () =>
32
+ Object.fromEntries(
33
+ Object.entries(TINT_TONES).flatMap(([tone, ramp]) => [
34
+ [`${tone}-subtle`, { light: p(ramp, '100'), dark: p(ramp, '950') }],
35
+ [`${tone}-border`, { light: p(ramp, '300'), dark: p(ramp, '900') }],
36
+ ])
37
+ );
38
+
39
+ /**
40
+ * Roles a theme derives from others rather than picking: the tints, `muted-subtle` (a surface a step off the
41
+ * page) and the pressed fills (the next step of the fill's ramp, away from the page). The fixer moves one of these,
42
+ * not the ink on it, when a pairing on it fails (fix.mjs).
43
+ */
44
+ export const isDerived = (name) => /-(subtle|pressed)$/.test(name);
45
+
23
46
  /**
24
47
  * { name: { light: ref, dark: ref } } in the order the kit's tokens.json lists them. `anchors` holds the step
25
48
  * each status seed sits on (`{ danger: '500' }`); a status without one uses its 600, the curated ramps' seed.
@@ -66,6 +89,10 @@ export function semanticColors(anchor = '600', anchors = {}) {
66
89
  'chart-3': { light: p('warning', 500), dark: p('warning', 400) },
67
90
  'chart-4': { light: p('danger', 500), dark: p('danger', 400) },
68
91
  'chart-5': { light: p('info', 500), dark: p('info', 400) },
92
+ 'muted-subtle': { light: n(50), dark: n(900) },
93
+ ...tints(),
94
+ 'primary-pressed': { light: b(shift(anchor, 1)), dark: b(shift(darkStep(anchor), -1)) },
95
+ 'secondary-pressed': { light: n(200), dark: n(700) },
69
96
  };
70
97
  }
71
98
 
@@ -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`);
@@ -54,8 +55,8 @@ export function textStyleVars(styles, format, font = (role) => `var(--kit-font-$
54
55
  /**
55
56
  * The button and field styles' variables (both formats), from a theme's or a token file's { button, field }
56
57
  * (generate.mjs, resolve.mjs). Widths are numbers on the light block; the field's fill opacity is per mode. A
57
- * field's corners and padding are the component layer's (componentVars: --field-radius, --field-radius-b,
58
- * --field-x).
58
+ * field's corners, padding and shadow are the component layer's (componentVars: --field-radius, --field-radius-b,
59
+ * --field-x, --field-shadow; a field is flat until a system gives it a shadow).
59
60
  */
60
61
  export function styleVars({ button, field }, format) {
61
62
  return {
@@ -66,8 +67,6 @@ export function styleVars({ button, field }, format) {
66
67
  '--field-alpha': String(field.alpha.light),
67
68
  '--field-border-w': `${field.border}px`,
68
69
  '--field-edge-w': `${field.edge}px`,
69
- // Web: a boxed field keeps shadcn's shadow-xs; a filled or underline field has none.
70
- ...(format === 'hsl' ? {} : { '--field-shadow': field.border ? 'var(--shadow-1)' : '0 0 #0000' }),
71
70
  },
72
71
  dark: { '--field-alpha': String(field.alpha.dark) },
73
72
  };
@@ -95,6 +94,22 @@ export function extraVars(list, format, font) {
95
94
  return { light, dark };
96
95
  }
97
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
+
98
113
  /** { light: { '--primary': '…', '--radius': '0.625rem' }, dark: { … } } (a system's extras too) */
99
114
  export function themeVars(theme, format) {
100
115
  const convert = format === 'hsl' ? hexToHslTriplet : hexToOklch;
@@ -108,6 +123,7 @@ export function themeVars(theme, format) {
108
123
  vars['--density'] = String(theme.density.scale);
109
124
  for (const size of ['sm', 'md', 'lg', 'x']) vars[`--control-${size}`] = `${theme.density[size]}px`;
110
125
  Object.assign(vars, typeVars(theme.type), textStyleVars(themeTextStyles(theme), format));
126
+ if (theme.motion) Object.assign(vars, motionVars(theme.motion));
111
127
  }
112
128
  Object.assign(vars, styleVars(theme, format)[m]);
113
129
  if (theme.components) Object.assign(vars, componentVars(theme.components, format, convert)[m]);
package/lib/usage.mjs CHANGED
@@ -94,7 +94,7 @@ export function usageIn(code, colours, roles = {}) {
94
94
  if (colour && colours.has(colour[1])) keys.add(`color.${colour[1]}`);
95
95
  if (colour && roles[colour[1]]) for (const role of roles[colour[1]]) keys.add(`color.${role}`);
96
96
  const component = COMPONENT_CLASS.exec(cls);
97
- if (component && (roles[colour?.[1]] || /^(rounded|h|w|size|px|type|text-type|leading-type|tracking-type|border(-b)?)-/.test(cls))) keys.add(`component.${PREFIX[component[1]]}`);
97
+ if (component && (roles[colour?.[1]] || /^(rounded|h|min-h|w|size|px|gap|type|text-type|leading-type|tracking-type|border(-b)?)-/.test(cls))) keys.add(`component.${PREFIX[component[1]]}`);
98
98
  const radius = RADIUS.exec(cls);
99
99
  if (radius) keys.add(`radius.${radius[1]}`);
100
100
  if (SHADOW[cls]) keys.add(`shadow.${SHADOW[cls]}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halftone-ds/tokens",
3
- "version": "1.3.2",
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",
@@ -41,6 +41,7 @@
41
41
  "push-figma.mjs",
42
42
  "lib/",
43
43
  "targets/",
44
+ "templates/",
44
45
  "README.md",
45
46
  "LICENSE"
46
47
  ],
@@ -5,7 +5,7 @@
5
5
  * The detailed rules stay in DESIGN_SYSTEM.md; this file points there instead of repeating them.
6
6
  * options: { out: 'DESIGN.md', name?: string, description?: string, platform?: 'mobile' | 'web' }
7
7
  */
8
- import { describeTintLimits, textOnTintLimits } from '../lib/contrast.mjs';
8
+ import { subtleLine, textOnSubtle } from '../lib/contrast.mjs';
9
9
  import { describeComponents } from '../lib/theme/components.mjs';
10
10
  import { describeExtras } from '../lib/theme/extras.mjs';
11
11
  import { themeFonts } from './fonts.mjs';
@@ -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' });
@@ -176,17 +179,18 @@ hex literal or a Tailwind palette colour in UI code. Keys ending in \`-dark\` ar
176
179
  - **Background (${hex.background}) and Card (${hex.card}):** the page canvas and raised surfaces.
177
180
  - **Muted foreground (${hex['muted-foreground']}):** helper text, captions, placeholders.
178
181
  - **Destructive, Success, Warning, Info:** status only, each with its own \`-foreground\`.
182
+ - **Tints:** \`primary-subtle\`, \`success-subtle\`, \`warning-subtle\`, \`destructive-subtle\`, \`info-subtle\` (a tinted
183
+ surface: an alert, an icon well, a selected card), each with a \`-border\` (\`border-warning-border\`), and
184
+ \`muted-subtle\`, a surface a step off the page. Pressed fills: \`primary-pressed\`, \`secondary-pressed\`.
179
185
  - **Chart 1–5:** data series.
180
186
 
181
187
  ${contrastLine(ctx)}
182
188
 
183
- A tone's text on that tone's own tint (\`text-success\` on \`bg-success/15\`) is a weaker pairing. With
184
- this palette it clears AA only for:
185
-
186
- ${describeTintLimits(textOnTintLimits(ctx.colors))}.
187
-
188
- On a stronger tint, the text stays \`text-foreground\` and the tint, an icon or a dot carries the
189
- colour. \`halftone-tokens check\` flags class strings that break this.
189
+ Colours come from the ramps, not from opacity: a colour at partial opacity (\`bg-primary/15\`) takes on whatever
190
+ is behind it, so its contrast changes with the surface. Tints are the roles above; transparency is for overlays
191
+ only (the scrim behind a sheet, a frosted bar, a focus ring's halo). Text on a tint is \`text-foreground\` or
192
+ \`text-muted-foreground\`; the tone itself goes on the icon or a dot. ${subtleLine(textOnSubtle(ctx.colors))}
193
+ \`halftone-tokens check\` flags class strings that break this.
190
194
  ${extrasSection}
191
195
  ## Typography
192
196
 
@@ -219,8 +223,10 @@ ${radius['2xl']}px; chips, avatars and dots are fully round.
219
223
  Only components listed in the registry in \`DESIGN_SYSTEM.md\` exist. ${STYLE_TEXT.button[ctx.styles.button]} ${STYLE_TEXT.field[ctx.styles.field]}
220
224
  Button, Chip, Badge and Input draw the theme's component tokens, the same in both kits: ${describeComponents(ctx.components).join('; ')}.
221
225
  Never restyle them by hand. Phones raise any tap target under 44px to 44.
222
- Motion: ${duration.fast}ms for micro-feedback, ${duration.base}ms for most transitions, ${duration.slow}ms for sheets, and
223
- 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.
224
230
 
225
231
  ## Do's and Don'ts
226
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/fonts.mjs CHANGED
@@ -4,6 +4,9 @@
4
4
  * the family name expo-font registers for each role and weight (FONT_FAMILY)
5
5
  * options: { platform: 'next', out: 'app/fonts.ts' } next/font/google, exposing --kit-font-heading,
6
6
  * --kit-font-body and --kit-font-mono (app/tokens.css maps them to font-heading / font-sans / font-mono)
7
+ * options: { platform: 'web', out: 'src/fonts.css' } any other web app: a Google Fonts @import and the same
8
+ * --kit-font-* variables. Import it FIRST in the app's stylesheet (before tailwindcss): a CSS @import of
9
+ * a URL only works at the very top, and the build hoists it there from the first imported file.
7
10
  * An empty family (heading, body) or Menlo (mono) is the platform's own font: nothing to load.
8
11
  *
9
12
  * A curated font (lib/theme/fonts.mjs) loads the weights it lists; any other Google Fonts family (a system's
@@ -84,8 +87,32 @@ export const fontVariables = [${roles.map(([role]) => `${role}.variable`).join('
84
87
  `;
85
88
  }
86
89
 
90
+ const FALLBACK = { serif: 'serif', mono: 'monospace' };
91
+
92
+ function web(ctx, fonts) {
93
+ const roles = [];
94
+ if (fonts.body) roles.push(['body', fonts.body]);
95
+ if (fonts.heading && fonts.heading.id !== fonts.body?.id) roles.push(['heading', fonts.heading]);
96
+ if (fonts.mono) roles.push(['mono', fonts.mono]);
97
+ if (!roles.length) return `/* ${ctx.header} */\n/* The theme uses the system fonts: nothing to load (tokens.css falls back to the system stacks). */\n`;
98
+ const families = [...new Map(roles.map(([, f]) => [f.id, f])).values()].map((f) => `family=${f.family.replace(/ /g, '+')}:wght@${f.weights.join(';')}`);
99
+ const stack = (role, f) => `'${f.family}', ${FALLBACK[role === 'mono' ? 'mono' : f.category] ?? 'sans-serif'}`;
100
+ return `/* ${ctx.header} */
101
+ /* Import this file first in the app's stylesheet, before tailwindcss: a URL @import only works at the top. */
102
+ @import url('https://fonts.googleapis.com/css2?${families.join('&')}&display=swap');
103
+
104
+ :root {
105
+ ${roles.map(([role, f]) => ` --kit-font-${role}: ${stack(role, f)};`).join('\n')}
106
+ }
107
+ `;
108
+ }
109
+
110
+ const PLATFORMS = { expo, next, web };
111
+
87
112
  export default function fontsTarget(ctx, options) {
88
113
  const fonts = themeFonts(ctx);
89
- const contents = options.platform === 'next' ? next(ctx, fonts) : expo(ctx, fonts);
114
+ const platform = PLATFORMS[options.platform ?? 'expo'];
115
+ if (!platform) throw new Error(`fonts: unknown platform "${options.platform}" (expo, next or web)`);
116
+ const contents = platform(ctx, fonts);
90
117
  return [{ path: options.out, contents }];
91
118
  }
package/targets/llms.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  * options: { out: 'tokens/generated/llms-tokens.md', platform?: 'mobile' | 'web' }
5
5
  */
6
6
  import { group } from '../lib/resolve.mjs';
7
- import { AA, describeTintLimits, textOnTintLimits } from '../lib/contrast.mjs';
7
+ import { AA, subtleLine, textOnSubtle } from '../lib/contrast.mjs';
8
8
  import { themeStatus } from '../lib/theme/index.mjs';
9
9
  import { themeFonts } from './fonts.mjs';
10
10
  import { describeComponents } from '../lib/theme/components.mjs';
@@ -23,11 +23,11 @@ export default function llms(ctx, options) {
23
23
  ## Tokens
24
24
 
25
25
  Colours are semantic names only, used as Tailwind classes (\`bg-primary\`, \`text-muted-foreground\`,
26
- \`border-border\`, \`bg-success/15\`). Never hex, never Tailwind palette colours. Both themes are
26
+ \`border-border\`, \`bg-success-subtle\`). Never hex, never Tailwind palette colours, never a colour at an
27
+ opacity (\`bg-primary/15\`): tints are the \`-subtle\` roles (with \`-border\`), \`muted-subtle\` and the
28
+ \`-pressed\` fills; only overlays (the \`bg-black/50\` scrim, a frosted bar, focus halos) are see-through. Both themes are
27
29
  required; ${ctx.contrastFailures?.length ? `${ctx.contrastFailures.length} pairing(s) in this palette fall below WCAG AA (${AA}:1): fix them (\`npm run tokens:build\` names them).` : `every fill/foreground pairing clears WCAG AA (${AA}:1); \`npm run tokens:build\` names any that falls short (\`--strict\` fails on it).`}
28
- A tone's own text on its own tint (\`text-success\` on \`bg-success/15\`) clears AA only for these
29
- tints; on a stronger one, put \`text-foreground\` on the tint:
30
- ${describeTintLimits(textOnTintLimits(ctx.colors))}.
30
+ Text on a tint is \`text-foreground\`; the tone goes on the icon or a dot. ${subtleLine(textOnSubtle(ctx.colors))}
31
31
 
32
32
  | Name | Light | Dark |
33
33
  |---|---|---|
@@ -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
  }