@halftone-ds/tokens 1.3.1 → 1.4.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,8 +16,13 @@
16
16
  * Phones raise anything under 44px to a 44px touch target (hitSlop) in the mobile kit; the tokens hold the
17
17
  * drawn sizes.
18
18
  */
19
+ import { blend, contrast, deltaEOK, relativeLuminance } from '../color.mjs';
19
20
  import { OPTIONS, TEXT_DEFAULTS, TEXT_LINE_HEIGHT } from './recipe.mjs';
20
21
 
22
+ /** WCAG AA for a label (contrast.mjs's AA; not imported, contrast.mjs reads this module). */
23
+ const AA_TEXT = 4.5;
24
+ const RAMP_REF = /^\{primitive\.color\.([a-z0-9-]+)\.(\d+)\}$/;
25
+
21
26
  export const COMPONENT_NAMES = ['button', 'chip', 'badge', 'input'];
22
27
  /** A Foundations corner a component can follow (rounded-sm…2xl, full); a number is an override in px. */
23
28
  export const CORNERS = ['sm', 'md', 'lg', 'xl', '2xl', 'full'];
@@ -34,7 +39,9 @@ export const COMPONENTS = {
34
39
  prefix: 'button',
35
40
  label: 'Button',
36
41
  styles: OPTIONS.button,
37
- sizes: ['sm', 'md', 'lg', 'x'],
42
+ steps: ['sm', 'md', 'lg'],
43
+ sizes: ['sm', 'md', 'lg', 'x', 'gap'],
44
+ props: ['border', 'weight', 'case', 'icon', 'shadow', 'ring'],
38
45
  variants: { primary: SLOTS, secondary: SLOTS, outline: SLOTS, ghost: SLOTS, destructive: SLOTS },
39
46
  text: 'p',
40
47
  },
@@ -42,7 +49,9 @@ export const COMPONENTS = {
42
49
  prefix: 'chip',
43
50
  label: 'Chip',
44
51
  styles: ['outline', 'soft', 'solid'],
45
- sizes: ['md', 'x'],
52
+ steps: ['sm', 'md', 'lg'],
53
+ sizes: ['sm', 'md', 'lg', 'x', 'gap'],
54
+ props: ['border', 'weight', 'icon'],
46
55
  variants: { unselected: SLOTS, selected: SLOTS },
47
56
  text: 'small',
48
57
  },
@@ -50,7 +59,9 @@ export const COMPONENTS = {
50
59
  prefix: 'badge',
51
60
  label: 'Badge',
52
61
  styles: ['pill', 'square', 'soft'],
53
- sizes: ['x'],
62
+ steps: ['sm', 'md'],
63
+ sizes: ['sm', 'md', 'x', 'gap'],
64
+ props: ['border', 'weight', 'case', 'icon'],
54
65
  variants: { default: SLOTS, secondary: SLOTS, destructive: SLOTS, outline: SLOTS },
55
66
  text: 'small',
56
67
  },
@@ -58,12 +69,29 @@ export const COMPONENTS = {
58
69
  prefix: 'field',
59
70
  label: 'Input',
60
71
  styles: OPTIONS.field,
72
+ steps: ['sm', 'md', 'lg'],
61
73
  sizes: ['sm', 'md', 'lg', 'x'],
62
- variants: { default: ['fill', 'label', 'border'], focus: ['border'], error: ['border'], disabled: ['fill', 'label', 'border'] },
74
+ props: ['border', 'placeholder', 'shadow', 'ring'],
75
+ variants: { default: ['fill', 'label', 'border'], focus: ['fill', 'label', 'border'], error: ['fill', 'label', 'border'], disabled: ['fill', 'label', 'border'] },
63
76
  text: 'p',
64
77
  },
65
78
  };
66
79
 
80
+ /** The weights a label can take, and its case (as written, or uppercase). */
81
+ export const WEIGHTS = [400, 500, 600, 700];
82
+ export const CASES = ['none', 'uppercase'];
83
+ /** A component's shadow: none, or a Foundations shadow level. */
84
+ export const SHADOWS = ['none', '1', '2', '3'];
85
+ /** The icon size (px) until a system sets one, the same in both kits: Button 16, Chip 14, Badge 12. */
86
+ export const ICON_DEFAULT = { button: 16, chip: 14, badge: 12 };
87
+ /**
88
+ * The shadow until a system sets one, the same in both kits: a Button has Shadow 1 (Ghost none); an Input has none,
89
+ * whatever its field style (content is flat: a field neither presses nor floats).
90
+ */
91
+ export const defaultShadow = (name) => (name === 'button' ? '1' : 'none');
92
+ /** The focus ring's width (px) until a system sets one: the kits' ring-[3px]. */
93
+ export const RING_WIDTH = 3;
94
+
67
95
  /** The slots as the CSS variables name them. `ring` is the focus ring Input's focus and error states derive. */
68
96
  export const SLOT_VAR = { fill: 'bg', label: 'fg', border: 'border', pressed: 'pressed', ring: 'ring' };
69
97
  /** The slots that carry an opacity (a variable of their own, -a). */
@@ -99,15 +127,15 @@ function variantDefaults(name, style, { button, field }) {
99
127
  if (name === 'button') {
100
128
  return {
101
129
  primary: { fill: a('button', button.alpha), label: 'button-foreground', border: 'button-edge' },
102
- secondary: { fill: 'secondary', label: 'secondary-foreground', border: 'none', pressed: a('secondary', 0.8) },
103
- outline: { fill: both('background', a('input', 0.3)), label: 'foreground', border: both('border', 'input'), pressed: both('accent', a('input', 0.5)) },
104
- ghost: { fill: 'none', label: 'foreground', border: 'none', pressed: both('accent', a('accent', 0.5)) },
130
+ secondary: { fill: 'secondary', label: 'secondary-foreground', border: 'none' },
131
+ outline: { fill: both('background', a('input', 0.3)), label: 'foreground', border: both('border', 'input'), pressed: 'accent' },
132
+ ghost: { fill: 'none', label: 'foreground', border: 'none', pressed: 'accent' },
105
133
  destructive: { fill: 'destructive', label: 'destructive-foreground', border: 'none' },
106
134
  };
107
135
  }
108
136
  if (name === 'chip') {
109
137
  const unselected =
110
- style === 'outline' ? { fill: 'background', label: 'foreground', border: 'border', pressed: 'accent' } : { fill: 'secondary', label: 'secondary-foreground', border: 'none', pressed: a('secondary', 0.8) };
138
+ style === 'outline' ? { fill: 'background', label: 'foreground', border: 'border', pressed: 'accent' } : { fill: 'secondary', label: 'secondary-foreground', border: 'none' };
111
139
  // Selected is inverted (foreground on background), whatever the style but solid, which fills it with the brand.
112
140
  const selected = style === 'solid' ? { fill: 'primary', label: 'primary-foreground', border: 'primary' } : { fill: 'foreground', label: 'background', border: 'foreground' };
113
141
  return { unselected, selected };
@@ -157,7 +185,7 @@ function roleOf(spec) {
157
185
  * hex (ref, mode) → '#rrggbb'
158
186
  * overrides a system's `components` (normalised; Button and Input styles already folded into the recipe)
159
187
  */
160
- export function componentLayer({ styles, controls, corner, density, borderWidth, button, field, textStyles, type, hex, overrides = {} }) {
188
+ export function componentLayer({ styles, controls, corner, density, borderWidth, button, field, textStyles, type, hex, ramps = {}, overrides = {} }) {
161
189
  const tokens = {};
162
190
  const shape = {};
163
191
  const color = (spec, edited) => {
@@ -172,7 +200,72 @@ export function componentLayer({ styles, controls, corner, density, borderWidth,
172
200
  alpha: { light: round(light.alpha), dark: round(dark.alpha) },
173
201
  };
174
202
  };
175
- const faded = (c, by) => ({ ...c, role: c.role, edited: false, derived: true, alpha: { light: round(c.alpha.light * by), dark: round(c.alpha.dark * by) } });
203
+ const page = (mode) => hex('{semantic.color.background}', mode);
204
+
205
+ // Colours come from the ramps (apps/docs/design/studio-wireframes.md › The open card): a fill, label, border or
206
+ // pressed colour is a role or a ramp step, never a colour at partial opacity, whose contrast would change with
207
+ // whatever is behind it. Only overlays (the focus rings' halos) are see-through.
208
+ const order = (r) => Object.keys(ramps[r]).sort((x, y) => Number(x) - Number(y));
209
+ /** The ramp and step a colour sits on: its own reference, or the nearest step of any ramp. */
210
+ const placeOf = (ref, value) => {
211
+ const m = RAMP_REF.exec(ref);
212
+ if (m && ramps[m[1]]?.[m[2]]) return [m[1], m[2]];
213
+ let best = null;
214
+ for (const r of Object.keys(ramps)) for (const st of order(r)) {
215
+ const d = deltaEOK(value, ramps[r][st]);
216
+ if (!best || d < best.d) best = { r, st, d };
217
+ }
218
+ return best ? [best.r, best.st] : null;
219
+ };
220
+ const piece = (spec, mode) => (isObject(spec) && 'light' in spec ? spec[mode] : spec);
221
+ /** A default drawn at partial opacity, as the step of its ramp nearest to what it drew over the page. */
222
+ const opaque = (spec) => {
223
+ const per = {};
224
+ for (const mode of ['light', 'dark']) {
225
+ const { ref, alpha } = specIn(spec, mode);
226
+ if (!(alpha > 0 && alpha < 1) || !Object.keys(ramps).length) {
227
+ per[mode] = piece(spec, mode);
228
+ continue;
229
+ }
230
+ const drawn = blend(hex(ref, mode), page(mode), alpha);
231
+ const place = placeOf(ref, hex(ref, mode));
232
+ const st = order(place[0]).reduce((b, x) => (deltaEOK(drawn, ramps[place[0]][x]) < deltaEOK(drawn, ramps[place[0]][b]) ? x : b));
233
+ per[mode] = `${place[0]}.${st}`;
234
+ }
235
+ return both(per.light, per.dark);
236
+ };
237
+ /**
238
+ * Hover and pressed: the next step of the fill's ramp away from the page (darker on a light page, lighter on a dark
239
+ * one) whose label still reads (AA, or the fill's own contrast when that is lower); the other way when none does.
240
+ */
241
+ const toward = (fill, label) => {
242
+ const per = {};
243
+ for (const mode of ['light', 'dark']) {
244
+ if (fill.alpha[mode] <= 0) {
245
+ per[mode] = 'accent';
246
+ continue;
247
+ }
248
+ const place = placeOf(fill.ref[mode], fill[mode]);
249
+ if (!place) {
250
+ per[mode] = fill.role ?? 'accent';
251
+ continue;
252
+ }
253
+ const list = order(place[0]);
254
+ const at = list.indexOf(place[1]);
255
+ const steps = ramps[place[0]];
256
+ const need = Math.min(AA_TEXT, contrast(fill[mode], label[mode]));
257
+ // Steps run light to dark: away from a light page is up the list.
258
+ const away = relativeLuminance(page(mode)) > 0.5 ? 1 : -1;
259
+ const reads = (j) => list[j] !== undefined && steps[list[j]].toLowerCase() !== fill[mode].toLowerCase() && contrast(steps[list[j]], label[mode]) >= need;
260
+ let pick = null;
261
+ for (const dir of [away, -away]) {
262
+ for (let j = at + dir; j >= 0 && j < list.length && pick === null; j += dir) if (reads(j)) pick = list[j];
263
+ if (pick !== null) break;
264
+ }
265
+ per[mode] = `${place[0]}.${pick ?? list[Math.min(list.length - 1, Math.max(0, at + away))]}`;
266
+ }
267
+ return both(per.light, per.dark);
268
+ };
176
269
 
177
270
  for (const name of COMPONENT_NAMES) {
178
271
  const def = COMPONENTS[name];
@@ -192,7 +285,7 @@ export function componentLayer({ styles, controls, corner, density, borderWidth,
192
285
  Object.assign(x, size.x === undefined ? { sm: 16, md: density.x, lg: 24 } : { sm: Math.max(0, size.x - 4), md: size.x, lg: size.x + 4 });
193
286
  }
194
287
  if (name === 'chip') {
195
- h.md = size.md ?? 36;
288
+ Object.assign(h, { sm: size.sm ?? 32, md: size.md ?? 36, lg: size.lg ?? 40 });
196
289
  x.md = size.x ?? 14;
197
290
  }
198
291
  if (name === 'badge') x.md = size.x ?? 8;
@@ -201,21 +294,50 @@ export function componentLayer({ styles, controls, corner, density, borderWidth,
201
294
  x.md = size.x ?? (field.inset ? 16 : 0);
202
295
  }
203
296
 
204
- // Text: the style's font, size and tracking; the line height fits a control (Body → text-base's 24 on 16).
297
+ // Text: the style's font, size and tracking; the line height fits a control (Body → text-base's 24 on 16). The
298
+ // weight is the component's own (medium; an Input's regular) until set, and the case as written.
205
299
  const textName = o.text ?? def.text;
206
300
  const ts = textStyles[textName];
207
- const text = { style: textName, font: ts.font, size: round(ts.size), leading: round(ts.size * fittedLeading(textName) * (type.leadingFactor ?? 1)), tracking: ts.tracking };
301
+ const text = {
302
+ style: textName,
303
+ font: ts.font,
304
+ size: round(ts.size),
305
+ leading: round(ts.size * fittedLeading(textName) * (type.leadingFactor ?? 1)),
306
+ tracking: ts.tracking,
307
+ weight: o.weight ?? (name === 'input' ? 400 : 500),
308
+ case: o.case ?? 'none',
309
+ };
310
+
311
+ // Border width: Chip and Badge draw the theme's border until set; Input its field style's (an outline box, or
312
+ // a filled or underline field's bottom line). Button's is per variant, below.
313
+ const line = o.border;
314
+ const borderWidthOf = name === 'input' ? (line === undefined ? field.border : field.border ? line : 0) : (line ?? borderWidth);
315
+ const edgeWidthOf = name === 'input' ? (line ?? field.edge) : borderWidthOf;
316
+ // A Badge is as tall as its text, padding and border until a height is set (S without the vertical padding); a
317
+ // set height is exact, never shorter than its text and border.
318
+ if (name === 'badge') {
319
+ const least = round(text.leading + 2 * borderWidthOf);
320
+ Object.assign(h, { sm: Math.max(least, size.sm ?? least), md: Math.max(least, size.md ?? round(text.leading + 4 + 2 * borderWidthOf)) });
321
+ }
322
+ // The gap between an icon and the label: Button's small size is tighter until the gap is set.
323
+ const gap = name === 'button' ? (size.gap === undefined ? { sm: 6, md: 8, lg: 8 } : { sm: size.gap, md: size.gap, lg: size.gap }) : name === 'input' ? null : { md: size.gap ?? (name === 'chip' ? 6 : 4) };
208
324
 
209
325
  // Variants.
210
326
  const defaults = variantDefaults(name, style, { button, field });
211
327
  const variants = {};
212
328
  for (const [variant, slots] of Object.entries(def.variants)) {
213
329
  const edits = o.variants?.[variant] ?? {};
214
- const d = defaults[variant];
330
+ // A default drawn at partial opacity is its nearest ramp step (the ramp rule above).
331
+ const d = Object.fromEntries(Object.entries(defaults[variant]).map(([slot, spec]) => [slot, opaque(spec)]));
215
332
  const v = {};
216
- if (name === 'input' && variant === 'disabled') {
217
- // Disabled follows the default state (at 50% opacity) unless set.
218
- for (const slot of slots) v[slot] = edits[slot] ? color(edits[slot], true) : { ...variants.default[slot], edited: false };
333
+ if (name === 'input' && variant !== 'default') {
334
+ // Focus, error and disabled follow the default state unless set (disabled at 50% opacity); focus and error
335
+ // have a border of their own.
336
+ for (const slot of slots) v[slot] = edits[slot] ? color(edits[slot], true) : d[slot] !== undefined ? color(d[slot]) : { ...variants.default[slot], edited: false };
337
+ // Their rings: the focus ring's role when one is set, otherwise the border at 50% (focus) or 20% / 40% in
338
+ // dark (error).
339
+ if (variant === 'focus') v.ring = o.ring?.role ? { ...color(o.ring.role, true), alpha: { light: 0.5, dark: 0.5 } } : { ...v.border, edited: false, derived: true, alpha: { light: 0.5, dark: 0.5 } };
340
+ if (variant === 'error') v.ring = { ...v.border, edited: false, derived: true, alpha: { light: 0.2, dark: 0.4 } };
219
341
  } else {
220
342
  // A border that is the fill by default (a selected chip, a primary button) follows an edited fill.
221
343
  const follows = edits.fill !== undefined && edits.border === undefined && JSON.stringify(roleOf(d.border ?? 'none')) === JSON.stringify(roleOf(d.fill ?? 'none')) && d.border !== 'none';
@@ -230,28 +352,50 @@ export function componentLayer({ styles, controls, corner, density, borderWidth,
230
352
  if (v.border && roleOf(edits.border ?? d.border) === 'none' && v.fill) v.border = { ...v.fill, role: 'none', edited: edits.border !== undefined, alpha: { light: 0, dark: 0 } };
231
353
  if (slots.includes('pressed')) {
232
354
  if (edits.pressed !== undefined) v.pressed = { ...color(edits.pressed, true), alpha: { light: 1, dark: 1 } };
233
- // Derived: the kit's own pressed colour until the fill changes, then the fill at 90% (a clear fill: accent).
355
+ // Derived: the kit's own pressed colour (Outline and Ghost: accent) until the fill changes; otherwise the
356
+ // fill's ramp step next to it with more contrast against the label (a clear fill: accent).
234
357
  else if (d.pressed && edits.fill === undefined) v.pressed = { ...color(d.pressed), derived: true };
235
- else v.pressed = v.fill.alpha.light === 0 && v.fill.alpha.dark === 0 ? { ...color('accent'), derived: true } : faded(v.fill, 0.9);
236
- }
237
- // Input's focus and error rings: the border at 50% (focus) or 20% / 40% in dark (error).
238
- if (name === 'input' && (variant === 'focus' || variant === 'error')) {
239
- const ring = variant === 'focus' ? { light: 0.5, dark: 0.5 } : { light: 0.2, dark: 0.4 };
240
- v.ring = { ...v.border, edited: false, derived: true, alpha: ring };
358
+ else v.pressed = { ...color(toward(v.fill, v.label)), derived: true };
241
359
  }
242
360
  }
243
- // Button borders: a width per variant (0 without a border), and the primary's bottom edge (raised).
361
+ // Button borders: a width per variant (0 without a border), and the primary's bottom edge (raised). A border
362
+ // width set on the component is every drawn border's; a raised edge stays at least as thick.
244
363
  if (name === 'button') {
245
364
  const none = v.border.role === 'none';
246
365
  const width = variant === 'primary' ? button.border : variant === 'outline' ? borderWidth : 0;
247
366
  const edge = variant === 'primary' ? button.edge : width;
248
- v.borderWidth = none ? 0 : width || (edits.border !== undefined ? borderWidth : 0);
249
- v.edgeWidth = none ? 0 : Math.max(edge, v.borderWidth);
367
+ if (line !== undefined) {
368
+ v.borderWidth = none ? 0 : line;
369
+ v.edgeWidth = none ? 0 : variant === 'primary' && button.edge > button.border ? Math.max(button.edge, line) : line;
370
+ } else {
371
+ v.borderWidth = none ? 0 : width || (edits.border !== undefined ? borderWidth : 0);
372
+ v.edgeWidth = none ? 0 : Math.max(edge, v.borderWidth);
373
+ }
374
+ // The focus ring: the ring role at 50% (Destructive: its own colour at 20%, 40% in dark) until a role is set.
375
+ v.ring = o.ring?.role
376
+ ? { ...color(o.ring.role, true), alpha: { light: 0.5, dark: 0.5 } }
377
+ : variant === 'destructive'
378
+ ? { ...color('destructive'), derived: true, alpha: { light: 0.2, dark: 0.4 } }
379
+ : { ...color('ring'), derived: true, alpha: { light: 0.5, dark: 0.5 } };
250
380
  }
251
381
  variants[variant] = v;
252
382
  }
253
383
 
254
384
  const out = { style, corner: typeof o.radius === 'number' ? null : cornerName, radius, h, x, text, variants };
385
+ // What every variant shares beyond the basics: the border set on the component (null: as the style draws it),
386
+ // the gap, the icon size, the shadow, the focus ring, and Input's
387
+ // placeholder.
388
+ out.border = line ?? null;
389
+ if (name !== 'button') Object.assign(out, { borderWidth: borderWidthOf, edgeWidth: edgeWidthOf });
390
+ if (gap) out.gap = gap;
391
+ if (def.props.includes('icon')) out.icon = o.icon ?? ICON_DEFAULT[name];
392
+ if (def.props.includes('shadow')) out.shadow = o.shadow ?? defaultShadow(name);
393
+ if (def.props.includes('ring')) {
394
+ out.ring = { width: o.ring?.width ?? RING_WIDTH, role: o.ring?.role ?? null };
395
+ // Button: the focused border is the ring's role, opaque.
396
+ if (name === 'button') out.focusBorder = { ...color(o.ring?.role ?? 'ring', !!o.ring?.role), alpha: { light: 1, dark: 1 } };
397
+ }
398
+ if (name === 'input') out.placeholder = { ...color(o.placeholder ?? 'muted-foreground', !!o.placeholder), alpha: { light: 1, dark: 1 } };
255
399
  if (name === 'input') {
256
400
  out.radiusBottom = round(radius * field.roundBottom, 4);
257
401
  out.radius = round(radius * field.round, 4);
@@ -271,19 +415,28 @@ function componentTokens(name, c, { button, field }) {
271
415
  if (name === 'input') t['radius-bottom'] = c.radiusBottom;
272
416
  if (Object.keys(c.h).length) t.height = { ...c.h };
273
417
  t.x = { ...c.x };
274
- t.text = { size: c.text.size, leading: c.text.leading, tracking: c.text.tracking, font: `{primitive.font.family.${c.text.font}}` };
418
+ if (c.gap) t.gap = { ...c.gap };
419
+ t.text = { size: c.text.size, leading: c.text.leading, tracking: c.text.tracking, font: `{primitive.font.family.${c.text.font}}`, weight: c.text.weight };
420
+ if (c.text.case === 'uppercase') t.text.uppercase = 1;
275
421
  // The style numbers the button and field tokens used to hold (semantic.button.*, semantic.field.*).
276
422
  if (name === 'button') Object.assign(t, { alpha: button.alpha, 'border-width': button.border, 'edge-width': button.edge });
423
+ if (name === 'chip' || name === 'badge') t['border-width'] = c.borderWidth;
277
424
  if (name === 'input') {
278
425
  Object.assign(t, {
279
426
  alpha: moded(field.alpha.light, field.alpha.dark),
280
- 'border-width': field.border,
281
- 'edge-width': field.edge,
427
+ 'border-width': c.borderWidth,
428
+ 'edge-width': c.edgeWidth,
282
429
  round: field.round,
283
430
  'round-bottom': field.roundBottom,
284
431
  inset: field.inset,
285
432
  });
286
433
  }
434
+ // The icon size and the shadow level (0 = none).
435
+ if (c.icon !== undefined) t.icon = c.icon;
436
+ if (c.shadow) t.shadow = c.shadow === 'none' ? 0 : Number(c.shadow);
437
+ if (c.ring) t['ring-width'] = c.ring.width;
438
+ if (c.focusBorder) t['focus-border'] = { light: c.focusBorder.ref.light, dark: c.focusBorder.ref.dark };
439
+ if (c.placeholder) t.placeholder = { light: c.placeholder.ref.light, dark: c.placeholder.ref.dark };
287
440
  for (const [variant, v] of Object.entries(c.variants)) {
288
441
  const group = {};
289
442
  for (const slot of ['fill', 'label', 'border', 'pressed', 'ring']) {
@@ -300,9 +453,10 @@ function componentTokens(name, c, { button, field }) {
300
453
  /**
301
454
  * The shape back from a token file's semantic.component group, as componentLayer returns it: `light` / `dark` are
302
455
  * the flat resolved maps ('semantic.component.button.radius' → value), `raw` the unresolved group (for the font role
303
- * and the roles the colours reference). Null when the file has no component tokens (a file from before them).
456
+ * and the roles the colours reference). Null when the file has no component tokens (a file from before them). A file
457
+ * from before a property gets its default (`borderWidth`: the theme's border, for Chip and Badge).
304
458
  */
305
- export function readComponents(light, dark, raw) {
459
+ export function readComponents(light, dark, raw, { borderWidth = 1 } = {}) {
306
460
  if (!raw || !Object.keys(raw).length) return null;
307
461
  const shape = {};
308
462
  const at = (map, path) => map[`semantic.component.${path}`];
@@ -311,6 +465,19 @@ export function readComponents(light, dark, raw) {
311
465
  for (const key of path.split('.')) node = node?.[key];
312
466
  return node?.$value;
313
467
  };
468
+ /** A colour token back as { role, light, dark, alpha }; undefined when the file doesn't have it. */
469
+ const readColor = (path) => {
470
+ const lightHex = at(light, path);
471
+ if (lightHex === undefined) return undefined;
472
+ const refs = rawValue(path);
473
+ const role = /\{semantic\.color\.([a-z0-9-]+)\}/.exec(String(isObject(refs) ? refs.light : refs))?.[1] ?? null;
474
+ return {
475
+ role,
476
+ light: String(lightHex).toLowerCase(),
477
+ dark: String(at(dark, path)).toLowerCase(),
478
+ alpha: { light: at(light, `${path}-alpha`) ?? 1, dark: at(dark, `${path}-alpha`) ?? 1 },
479
+ };
480
+ };
314
481
  for (const name of COMPONENT_NAMES) {
315
482
  if (!raw[name]) return null;
316
483
  const def = COMPONENTS[name];
@@ -321,81 +488,129 @@ export function readComponents(light, dark, raw) {
321
488
  radius: num('radius', 0),
322
489
  h: sizes('height'),
323
490
  x: sizes('x'),
324
- text: { font, size: num('text.size', 16), leading: num('text.leading', 24), tracking: num('text.tracking', 0) },
491
+ text: {
492
+ font,
493
+ size: num('text.size', 16),
494
+ leading: num('text.leading', 24),
495
+ tracking: num('text.tracking', 0),
496
+ weight: num('text.weight', name === 'input' ? 400 : 500),
497
+ case: num('text.uppercase', 0) ? 'uppercase' : 'none',
498
+ },
325
499
  variants: {},
326
500
  };
327
501
  if (name === 'input') out.radiusBottom = num('radius-bottom', out.radius);
502
+ if (name === 'input') Object.assign(out, { borderWidth: num('border-width', 1), edgeWidth: num('edge-width', 1) });
503
+ if (name === 'chip' || name === 'badge') out.borderWidth = out.edgeWidth = num('border-width', borderWidth);
504
+ if (name === 'chip') out.h = { sm: out.h.sm ?? 32, md: out.h.md, lg: out.h.lg ?? 40 };
505
+ if (name === 'badge') out.h = { sm: out.h.sm ?? round(out.text.leading + 2 * out.borderWidth), md: out.h.md ?? round(out.text.leading + 4 + 2 * out.borderWidth) };
506
+ if (name !== 'input') {
507
+ const gap = sizes('gap');
508
+ out.gap = name === 'button' ? { sm: 6, md: 8, lg: 8, ...gap } : { md: name === 'chip' ? 6 : 4, ...gap };
509
+ }
510
+ if (def.props.includes('icon')) out.icon = num('icon', ICON_DEFAULT[name]);
511
+ if (def.props.includes('shadow')) {
512
+ const level = num('shadow', null);
513
+ out.shadow = level === null ? defaultShadow(name) : level === 0 ? 'none' : String(level);
514
+ }
515
+ if (def.props.includes('ring')) out.ring = { width: num('ring-width', RING_WIDTH), role: null };
516
+ if (name === 'button') out.focusBorder = readColor('button.focus-border');
517
+ if (name === 'input') out.placeholder = readColor('input.placeholder');
328
518
  for (const variant of Object.keys(def.variants)) {
329
519
  const v = {};
330
520
  for (const slot of ['fill', 'label', 'border', 'pressed', 'ring']) {
331
- const lightHex = at(light, `${name}.${variant}.${slot}`);
332
- if (lightHex === undefined) continue;
333
- const refs = rawValue(`${name}.${variant}.${slot}`);
334
- const role = /\{semantic\.color\.([a-z0-9-]+)\}/.exec(String(isObject(refs) ? refs.light : refs))?.[1] ?? null;
335
- v[slot] = {
336
- role,
337
- light: String(lightHex).toLowerCase(),
338
- dark: String(at(dark, `${name}.${variant}.${slot}`)).toLowerCase(),
339
- alpha: { light: at(light, `${name}.${variant}.${slot}-alpha`) ?? 1, dark: at(dark, `${name}.${variant}.${slot}-alpha`) ?? 1 },
340
- };
521
+ const color = readColor(`${name}.${variant}.${slot}`);
522
+ if (color) v[slot] = color;
341
523
  }
524
+ // Input's focus and error states from before they had a fill and text: the default state's.
525
+ if (name === 'input' && variant !== 'default') for (const slot of ['fill', 'label']) v[slot] ??= out.variants.default[slot];
342
526
  if (at(light, `${name}.${variant}.border-width`) !== undefined) {
343
527
  v.borderWidth = at(light, `${name}.${variant}.border-width`);
344
528
  v.edgeWidth = at(light, `${name}.${variant}.edge-width`) ?? v.borderWidth;
345
529
  }
346
530
  out.variants[variant] = v;
347
531
  }
532
+ for (const key of ['focusBorder', 'placeholder']) if (out[key] === undefined) delete out[key];
348
533
  shape[name] = out;
349
534
  }
350
535
  return shape;
351
536
  }
352
537
 
538
+ /** Colours a component holds beyond its variants: Button's focused border, Input's placeholder. */
539
+ const OWN_COLORS = { button: { focusBorder: 'focus-border' }, input: { placeholder: 'placeholder' } };
540
+
353
541
  /** Every component variable name a shape produces, light block (what an embedded kit may accept). */
354
542
  export function componentVarNames() {
355
543
  const names = [];
356
544
  for (const name of COMPONENT_NAMES) {
357
545
  const def = COMPONENTS[name];
358
546
  const p = def.prefix;
359
- names.push(`--${p}-radius`, `--${p}-text-size`, `--${p}-text-leading`, `--${p}-text-tracking`, `--${p}-text-font`);
360
- if (name === 'input') names.push('--field-radius-b');
361
- for (const s of def.sizes.filter((s) => s !== 'x')) names.push(`--${p}-h-${s}`);
547
+ names.push(`--${p}-radius`, `--${p}-text-size`, `--${p}-text-leading`, `--${p}-text-tracking`, `--${p}-text-font`, `--${p}-text-weight`);
548
+ if (def.props.includes('case')) names.push(`--${p}-text-case`);
549
+ if (name === 'input') names.push('--field-radius-b', '--field-shadow');
550
+ for (const s of def.steps) names.push(`--${p}-h-${s}`);
362
551
  names.push(`--${p}-x`);
363
- if (name === 'button') names.push('--button-x-sm', '--button-x-lg');
552
+ if (name === 'button') names.push('--button-x-sm', '--button-x-lg', '--button-gap-sm');
553
+ if (name !== 'input') names.push(`--${p}-gap`);
554
+ if (name === 'chip' || name === 'badge') names.push(`--${p}-border-w`);
555
+ if (def.props.includes('icon')) names.push(`--${p}-icon`);
556
+ if (def.props.includes('ring')) names.push(`--${p}-ring-w`);
557
+ for (const key of Object.values(OWN_COLORS[name] ?? {})) names.push(`--${p}-${key}`);
364
558
  for (const [variant, slots] of Object.entries(def.variants)) {
365
- const all = [...slots, ...(name === 'input' && (variant === 'focus' || variant === 'error') ? ['ring'] : [])];
559
+ const all = [...slots, ...(name === 'button' || variant === 'focus' || variant === 'error' ? ['ring'] : [])];
366
560
  for (const slot of all) {
367
561
  names.push(`--${p}-${variant}-${SLOT_VAR[slot]}`);
368
562
  if (ALPHA_SLOTS.has(slot)) names.push(`--${p}-${variant}-${SLOT_VAR[slot]}-a`);
369
563
  }
370
- if (name === 'button') names.push(`--button-${variant}-border-w`, `--button-${variant}-edge-w`);
564
+ if (name === 'button') names.push(`--button-${variant}-border-w`, `--button-${variant}-edge-w`, `--button-${variant}-shadow`);
371
565
  }
372
566
  }
373
567
  return names;
374
568
  }
375
569
 
570
+ const NO_SHADOW = '0 0 #0000';
571
+
376
572
  /**
377
573
  * A shape as CSS variables, { light, dark }, in a kit's format (vars.mjs):
378
- * 'hsl' mobile: colours as triplets, lengths in px or rem (4 places); no font variable (the kit picks it in JS)
379
- * 'oklch' web: oklch colours; `font(role)` writes the text's font family
574
+ * 'hsl' mobile: colours as triplets, lengths in px or rem (4 places); no font variable (the kit picks it in JS),
575
+ * and no shadow (the kit draws TOKENS.components' level with TOKENS.shadows)
576
+ * 'oklch' web: oklch colours; `font(role)` writes the text's font family; shadows are var(--shadow-N)
380
577
  * Colours carry their opacity apart (--button-primary-bg and --button-primary-bg-a), as --button and --button-alpha do.
381
578
  */
382
579
  export function componentVars(shape, format, convert, font = (role) => `var(--kit-font-${role})`) {
383
580
  const light = {};
384
581
  const dark = {};
385
582
  const rem = (px) => (px >= 9999 ? '9999px' : `${round(px / 16)}rem`);
583
+ const shadow = (level) => (!level || level === 'none' ? NO_SHADOW : `var(--shadow-${level})`);
386
584
  for (const name of COMPONENT_NAMES) {
387
585
  const c = shape[name];
388
586
  if (!c) continue;
389
- const p = COMPONENTS[name].prefix;
587
+ const def = COMPONENTS[name];
588
+ const p = def.prefix;
390
589
  light[`--${p}-radius`] = rem(c.radius);
391
590
  if (name === 'input') light['--field-radius-b'] = rem(c.radiusBottom);
392
591
  for (const [s, px] of Object.entries(c.h)) light[`--${p}-h-${s}`] = `${px}px`;
393
592
  light[`--${p}-x`] = `${c.x.md}px`;
394
593
  if (name === 'button') Object.assign(light, { '--button-x-sm': `${c.x.sm}px`, '--button-x-lg': `${c.x.lg}px` });
594
+ if (c.gap) {
595
+ light[`--${p}-gap`] = `${c.gap.md}px`;
596
+ if (name === 'button') light['--button-gap-sm'] = `${c.gap.sm}px`;
597
+ }
598
+ if ((name === 'chip' || name === 'badge') && c.borderWidth !== undefined) light[`--${p}-border-w`] = `${c.borderWidth}px`;
395
599
  light[`--${p}-text-size`] = rem(c.text.size);
396
600
  light[`--${p}-text-leading`] = rem(c.text.leading);
397
601
  light[`--${p}-text-tracking`] = `${c.text.tracking}em`;
602
+ light[`--${p}-text-weight`] = String(c.text.weight ?? (name === 'input' ? 400 : 500));
603
+ if (def.props.includes('case')) light[`--${p}-text-case`] = c.text.case ?? 'none';
398
604
  if (format !== 'hsl') light[`--${p}-text-font`] = font(c.text.font);
605
+ if (def.props.includes('icon')) light[`--${p}-icon`] = `${c.icon ?? ICON_DEFAULT[name]}px`;
606
+ if (c.ring) light[`--${p}-ring-w`] = `${c.ring.width}px`;
607
+ for (const [key, cssName] of Object.entries(OWN_COLORS[name] ?? {})) {
608
+ if (!c[key]) continue;
609
+ light[`--${p}-${cssName}`] = convert(c[key].light);
610
+ dark[`--${p}-${cssName}`] = convert(c[key].dark);
611
+ }
612
+ // Web shadows, as Foundations shadows (defaultShadow until set). Ghost never has one.
613
+ if (format !== 'hsl' && name === 'input') light['--field-shadow'] = shadow(c.shadow ?? defaultShadow(name));
399
614
  for (const [variant, v] of Object.entries(c.variants)) {
400
615
  for (const [slot, col] of Object.entries(v)) {
401
616
  if (!SLOT_VAR[slot] || !col) continue;
@@ -408,6 +623,7 @@ export function componentVars(shape, format, convert, font = (role) => `var(--ki
408
623
  }
409
624
  }
410
625
  if (v.borderWidth !== undefined) Object.assign(light, { [`--button-${variant}-border-w`]: `${v.borderWidth}px`, [`--button-${variant}-edge-w`]: `${v.edgeWidth}px` });
626
+ if (format !== 'hsl' && name === 'button') light[`--button-${variant}-shadow`] = variant === 'ghost' ? NO_SHADOW : shadow(c.shadow ?? defaultShadow(name));
411
627
  }
412
628
  }
413
629
  return { light, dark };
@@ -420,6 +636,7 @@ export function componentColors(shape, css) {
420
636
  const c = shape[name];
421
637
  if (!c) continue;
422
638
  const p = COMPONENTS[name].prefix;
639
+ for (const [key, cssName] of Object.entries(OWN_COLORS[name] ?? {})) if (c[key]) out[`${p}-${cssName}`] = css(`${p}-${cssName}`, false);
423
640
  for (const [variant, v] of Object.entries(c.variants)) {
424
641
  for (const slot of Object.keys(v)) {
425
642
  if (!SLOT_VAR[slot]) continue;
@@ -447,6 +664,13 @@ export function componentPairs(shape, mode, background, blend) {
447
664
  const bg = alpha >= 1 ? v.fill[mode] : alpha <= 0 ? background : blend(v.fill[mode], background, alpha);
448
665
  out.push({ component: name, variant, label: `${COMPONENTS[name].label} ${variant}: label on fill`, fg: v.label[mode], bg, fgRole: v.label.role, bgRole: alpha <= 0 ? 'background' : v.fill.role });
449
666
  }
667
+ // Input's placeholder, on the default state's fill.
668
+ if (c.placeholder) {
669
+ const fill = c.variants.default.fill;
670
+ const alpha = fill.alpha[mode];
671
+ const bg = alpha >= 1 ? fill[mode] : alpha <= 0 ? background : blend(fill[mode], background, alpha);
672
+ out.push({ component: name, variant: 'placeholder', label: 'Input placeholder on fill', fg: c.placeholder[mode], bg, fgRole: c.placeholder.role, bgRole: alpha <= 0 ? 'background' : fill.role });
673
+ }
450
674
  }
451
675
  return out;
452
676
  }
package/lib/theme/fix.mjs CHANGED
@@ -7,6 +7,8 @@
7
7
  * 2. a tone as ink or an icon on its tint (`text-primary on muted`): move the tone away from the page
8
8
  * (darker in light mode, lighter in dark), then re-check its label
9
9
  * 3. body or muted text on a surface: move the text away from the surface
10
+ * 4. anything on a derived role (a tint, `muted-subtle`, a pressed fill): move that role away from the ink on it,
11
+ * never the ink, which every other surface shares
10
12
  *
11
13
  * It checks the STRICT set (tones on muted/accent too). A moved token becomes a literal hex for that
12
14
  * mode, and every move is reported as { token, mode, from, to } so the picker can show it.
@@ -22,7 +24,7 @@
22
24
  import { contrast, hexToOklchParts } from '../color.mjs';
23
25
  import { contrastPairs } from '../contrast.mjs';
24
26
  import { toGamutHex } from './ramp.mjs';
25
- import { BRAND_LINKED, FOREGROUND_CHOICES } from './semantic.mjs';
27
+ import { BRAND_LINKED, FOREGROUND_CHOICES, isDerived } from './semantic.mjs';
26
28
 
27
29
  const MAX_PASSES = 24;
28
30
  const STEP = 0.004;
@@ -102,14 +104,35 @@ export function fixContrast(semantic, lookup, { locked, pinned } = {}) {
102
104
  continue;
103
105
  }
104
106
 
105
- // 2 and 3: move the ink until every pairing it takes part in as ink passes.
107
+ // 4. A derived role moves away from its ink until every pairing on it passes.
108
+ if (isDerived(f.bgName)) {
109
+ const bg = f.bgName;
110
+ if (isFixed(bg)) {
111
+ accept(f);
112
+ continue;
113
+ }
114
+ const onIt = (candidate) =>
115
+ failing(contrastPairs({ ...hex, [bg]: candidate }, mode, { strict: true })).filter((p) => p.bgName === bg && !accepted.has(p.label)).length === 0;
116
+ // A light ink (it reads on black) needs a darker role; a dark ink a lighter one.
117
+ const dir = contrast(hex[f.fgName], '#000000') > contrast(hex[f.fgName], '#ffffff') ? -1 : 1;
118
+ const moved = nudge(hex[bg], dir, onIt);
119
+ if (!moved) {
120
+ cannot(f);
121
+ continue;
122
+ }
123
+ set(bg, moved);
124
+ pass++;
125
+ continue;
126
+ }
127
+
128
+ // 2 and 3: move the ink until every pairing it takes part in as ink passes (4 moves the derived roles).
106
129
  const ink = f.fgName;
107
130
  if (isFixed(ink)) {
108
131
  accept(f);
109
132
  continue;
110
133
  }
111
134
  const asInk = (candidate) =>
112
- failing(contrastPairs({ ...hex, [ink]: candidate }, mode, { strict: true, fg: ink })).filter((p) => !accepted.has(p.label)).length === 0;
135
+ failing(contrastPairs({ ...hex, [ink]: candidate }, mode, { strict: true, fg: ink })).filter((p) => !accepted.has(p.label) && !isDerived(p.bgName)).length === 0;
113
136
  const moved = nudge(hex[ink], away, asInk);
114
137
  if (!moved) {
115
138
  cannot(f);
@@ -150,6 +150,14 @@ export function generateTheme(input, base, { fix = true, colors: system } = {})
150
150
  return withComponents(theme, base);
151
151
  }
152
152
 
153
+ /** Every ramp (a group of numbered steps) as { ramp: { step: hex } }; `value(path)` resolves a primitive. */
154
+ export const rampsOf = (colors, value) =>
155
+ Object.fromEntries(
156
+ Object.entries(colors)
157
+ .filter(([, steps]) => steps && typeof steps === 'object' && Object.keys(steps).some((k) => /^\d+$/.test(k)))
158
+ .map(([name, steps]) => [name, Object.fromEntries(Object.keys(steps).filter((k) => /^\d+$/.test(k)).map((k) => [k, value(`primitive.color.${name}.${k}`)]))])
159
+ );
160
+
153
161
  /**
154
162
  * The theme with its component layer (lib/theme/components.mjs): semantic.component (the tokens) and `components`
155
163
  * (resolved). Built from the theme's own corners, density, border, styles, text styles and colours, so
@@ -178,7 +186,9 @@ export function withComponents(theme, base, overrides = {}) {
178
186
  if (value === undefined) throw new Error(`generateTheme: ${ref} is not in the base tokens`);
179
187
  return value;
180
188
  },
189
+ ramps: rampsOf(primitive.color, (path) => prim[path]),
181
190
  overrides,
182
191
  });
183
- return { ...theme, semantic: { ...theme.semantic, component: tokens }, components: shape };
192
+ // An Input border width set on the system is the field's (--field-border-w, --field-edge-w).
193
+ return { ...theme, field: { ...theme.field, border: shape.input.borderWidth, edge: shape.input.edgeWidth }, semantic: { ...theme.semantic, component: tokens }, components: shape };
184
194
  }