@designtools/tokens 0.9.0 → 0.11.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.
@@ -47,12 +47,12 @@ function resolveShades(requested) {
47
47
  const seen = new Set(requested);
48
48
  return VALID_SHADES.filter((s) => seen.has(s));
49
49
  }
50
- function snapShade(shade, active) {
51
- if (active.includes(shade)) return shade;
50
+ function snapShade(shade2, active) {
51
+ if (active.includes(shade2)) return shade2;
52
52
  if (active.length === 0) {
53
53
  throw new Error("cannot snap a shade against an empty shade set");
54
54
  }
55
- const target = VALID_SHADES.indexOf(shade);
55
+ const target = VALID_SHADES.indexOf(shade2);
56
56
  let best = active[0];
57
57
  let bestDistance = Infinity;
58
58
  for (const candidate of active) {
@@ -185,6 +185,42 @@ var LIGHTNESS_FACTORS = {
185
185
  achromatic: [0.98, 0.95, 0.9, 0.8, 0.66, 0.38, 0, -0.26, -0.44, -0.62, -0.8, -0.92]
186
186
  }
187
187
  };
188
+ function maxChroma(lightness, hue, gamut = "srgb") {
189
+ const capped = clampChroma({ mode: "oklch", l: lightness, c: 0.4, h: hue }, "oklch", GAMUT_SPACE[gamut]);
190
+ return capped.c ?? 0;
191
+ }
192
+ function hueDriftDegrees(drift, hue, achromatic) {
193
+ if (achromatic || drift === void 0 || drift === "none") return 0;
194
+ if (typeof drift === "number") return drift;
195
+ if (hue >= 60 && hue <= 125) return -Math.min(25, 0.3 * (hue - 40));
196
+ if (hue >= 180 && hue < 275) return Math.min(25, 0.3 * (275 - hue));
197
+ return 0;
198
+ }
199
+ function refitThroughPins(lightness, anchor, pins) {
200
+ const n = lightness.length;
201
+ const held = new Map([[0, lightness[0]], [n - 1, lightness[n - 1]], [anchor, lightness[anchor]], ...pins]);
202
+ const at = [...held.keys()].sort((a, b) => a - b);
203
+ const out = [...lightness];
204
+ for (let k = 0; k < at.length - 1; k++) {
205
+ const a = at[k];
206
+ const b = at[k + 1];
207
+ const da = held.get(a) - lightness[a];
208
+ const db = held.get(b) - lightness[b];
209
+ for (let i = a; i <= b; i++) {
210
+ const t = (i - a) / (b - a);
211
+ out[i] = lightness[i] + da * (1 - t) + db * t;
212
+ }
213
+ }
214
+ for (let i = 1; i < n; i++) {
215
+ if (out[i] > out[i - 1] + 1e-9) {
216
+ throw new Error(
217
+ `an exact colour puts steps ${VALID_SHADES[i - 1]} and ${VALID_SHADES[i]} out of order (${(out[i - 1] * 100).toFixed(1)}% then ${(out[i] * 100).toFixed(1)}% lightness): it has to be darker than the steps above it and lighter than those below`
218
+ );
219
+ }
220
+ }
221
+ return out;
222
+ }
223
+ var MIN_DARK_STEP = 0.02;
188
224
  function printOklch(l, c, h) {
189
225
  return `oklch(${l} ${c.toFixed(4)} ${h})`;
190
226
  }
@@ -211,8 +247,9 @@ function buildScale(baseColor, strategy, options) {
211
247
  const seedShade = options?.seedShade ?? DEFAULT_SEED_SHADE;
212
248
  const emitted = resolveShades(options?.shades);
213
249
  const gamut = options?.gamut ?? "srgb";
214
- const maxLightness = Math.max(0.98, baseLightness);
215
- const minLightness = Math.min(0.15, baseLightness);
250
+ const below = VALID_SHADES.length - 1 - VALID_SHADES.indexOf(seedShade);
251
+ const maxLightness = Math.max(options?.lightEnd ?? 0.98, baseLightness);
252
+ const minLightness = Math.min(options?.darkEnd !== void 0 ? Math.min(options.darkEnd, baseLightness - MIN_DARK_STEP * below) : 0.15, baseLightness);
216
253
  const headroomUp = maxLightness - baseLightness;
217
254
  const headroomDown = baseLightness - minLightness;
218
255
  const factors = reanchorFactors(
@@ -220,21 +257,56 @@ function buildScale(baseColor, strategy, options) {
220
257
  seedShade
221
258
  );
222
259
  const computeChroma = strategy === "perceptual" ? computeScaleChromaPerceptual : computeScaleChroma;
260
+ const n = VALID_SHADES.length;
261
+ const anchor = VALID_SHADES.indexOf(seedShade);
262
+ const pins = /* @__PURE__ */ new Map();
263
+ for (const [step, colour] of Object.entries(options?.pins ?? {})) {
264
+ if (!colour) continue;
265
+ const i = VALID_SHADES.indexOf(Number(step));
266
+ if (i === -1) throw new Error(`${step} is not a step (${VALID_SHADES.join(", ")})`);
267
+ if (i === anchor) throw new Error(`${step} is where the ramp's own colour lands: change that colour instead`);
268
+ if (!isInGamut(colour, gamut)) throw new Error(`the exact colour on ${step}, ${colour}, can't be shown on ${gamut === "p3" ? "a P3" : "an sRGB"} screen`);
269
+ pins.set(i, parseToOklch(colour));
270
+ }
271
+ let lightness = VALID_SHADES.map((_, i) => {
272
+ if (i === anchor) return baseLightness;
273
+ const factor = factors[i];
274
+ const target = factor >= 0 ? baseLightness + headroomUp * factor : baseLightness + headroomDown * factor;
275
+ return Math.max(minLightness, Math.min(maxLightness, target));
276
+ });
277
+ if (pins.size) lightness = refitThroughPins(lightness, anchor, new Map([...pins].map(([i, c]) => [i, c.l])));
278
+ const drift = hueDriftDegrees(options?.hueDrift, baseHue, isAchromatic);
279
+ const hueAt = (i) => drift && i > anchor ? ((baseHue + drift * (i - anchor) / (n - 1 - anchor)) % 360 + 360) % 360 : baseHue;
280
+ const profile = options?.chroma?.profile ?? "follow";
281
+ const strength = options?.chroma?.strength ?? 1;
282
+ const peak = VALID_SHADES.indexOf(options?.chroma?.peakAt ?? seedShade);
283
+ const bell = (i) => Math.exp(-(((i - peak) / 2.5) ** 2));
284
+ const share = profile === "relative" ? baseChroma / Math.max(1e-6, maxChroma(baseLightness, baseHue, gamut)) : 0;
285
+ const chromaAt = (i) => {
286
+ if (isAchromatic) return baseChroma;
287
+ let c;
288
+ if (profile === "constant") c = baseChroma;
289
+ else if (profile === "relative") c = maxChroma(lightness[i], hueAt(i), gamut) * share;
290
+ else if (profile === "peak") c = baseChroma * bell(i) / bell(anchor);
291
+ else c = computeChroma((chromaShadeFor(i, seedShade) - 25) / 925, baseChroma);
292
+ if (strength !== 1) c *= 1 + (strength - 1) * Math.min(1, Math.abs(i - anchor) / 2);
293
+ if (options?.tintFloor !== void 0 && i < anchor) c = Math.max(c, baseChroma * options.tintFloor);
294
+ return c;
295
+ };
223
296
  const scale = {};
224
- for (let i = 0; i < VALID_SHADES.length; i++) {
225
- const shade = VALID_SHADES[i];
226
- if (!emitted.includes(shade)) continue;
227
- if (shade === seedShade) {
228
- scale[shade] = formatOklchInGamut(baseLightness, baseChroma, baseHue, gamut);
297
+ for (let i = 0; i < n; i++) {
298
+ const shade2 = VALID_SHADES[i];
299
+ if (!emitted.includes(shade2)) continue;
300
+ if (i === anchor) {
301
+ scale[shade2] = formatOklchInGamut(baseLightness, baseChroma, baseHue, gamut);
229
302
  continue;
230
303
  }
231
- const factor = factors[i];
232
- const target = factor >= 0 ? baseLightness + headroomUp * factor : baseLightness + headroomDown * factor;
233
- const lightness = Math.max(minLightness, Math.min(maxLightness, target));
234
- const chromaShade = chromaShadeFor(i, seedShade);
235
- const normalizedPosition = (chromaShade - 25) / 925;
236
- const chroma = isAchromatic ? baseChroma : computeChroma(normalizedPosition, baseChroma);
237
- scale[shade] = formatOklchInGamut(lightness, chroma, baseHue, gamut);
304
+ const pin = pins.get(i);
305
+ if (pin) {
306
+ scale[shade2] = formatOklchInGamut(pin.l, pin.c ?? 0, pin.h ?? 0, gamut);
307
+ continue;
308
+ }
309
+ scale[shade2] = formatOklchInGamut(lightness[i], chromaAt(i), hueAt(i), gamut);
238
310
  }
239
311
  return scale;
240
312
  }
@@ -422,13 +494,40 @@ function deriveWarningColor(primaryColor) {
422
494
  };
423
495
  return oklchToHex(warning);
424
496
  }
497
+ function byFamily(map, name) {
498
+ if (!map) return void 0;
499
+ const alias = aliasOf(name);
500
+ return map[name] ?? (alias ? map[alias] : void 0);
501
+ }
502
+ function shapeFor(name, options) {
503
+ const system = name === "neutral" ? {} : { lightEnd: options?.lightEnd, darkEnd: options?.darkEnd, tintFloor: options?.tintFloor, chroma: options?.chroma, hueDrift: options?.hueDrift };
504
+ const own = byFamily(options?.families, name);
505
+ if (!own) return system;
506
+ const chroma = own.chroma || system.chroma ? { ...system.chroma, ...own.chroma } : void 0;
507
+ return {
508
+ ...system,
509
+ ...own.lightnessRange?.light !== void 0 ? { lightEnd: own.lightnessRange.light } : {},
510
+ ...own.lightnessRange?.dark !== void 0 ? { darkEnd: own.lightnessRange.dark } : {},
511
+ ...own.tintFloor !== void 0 ? { tintFloor: own.tintFloor } : {},
512
+ ...chroma ? { chroma } : {},
513
+ ...own.hueDrift !== void 0 ? { hueDrift: own.hueDrift } : {}
514
+ };
515
+ }
425
516
  function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", options) {
426
517
  const gen = lightnessStrategy === "perceptual" ? generateColorScaleAPCA : generateColorScale;
427
- const genScale = (name, color) => gen(color, {
428
- shades: options?.shades,
429
- gamut: options?.gamut,
430
- seedShade: familySeedShade(name, options?.seedShade, options?.seedShades)
431
- });
518
+ const genScale = (name, color) => {
519
+ try {
520
+ return gen(color, {
521
+ shades: options?.shades,
522
+ gamut: options?.gamut,
523
+ seedShade: familySeedShade(name, options?.seedShade, options?.seedShades),
524
+ ...shapeFor(name, options),
525
+ pins: byFamily(options?.familyPins, name)
526
+ });
527
+ } catch (error) {
528
+ throw new Error(`${name}: ${error.message}`);
529
+ }
530
+ };
432
531
  const palette = {};
433
532
  palette.black = "oklch(0 0 0)";
434
533
  palette.white = "oklch(1 0 0)";
@@ -454,14 +553,15 @@ function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", opti
454
553
  else if (overrodeAlias && !overrodeSemantic) palette[semantic] = palette[alias];
455
554
  }
456
555
  }
556
+ if (options?.aliases === false) for (const [, alias] of ALIAS_PAIRS) delete palette[alias];
457
557
  return palette;
458
558
  }
459
- function getShade(palette, colorName, shade) {
559
+ function getShade(palette, colorName, shade2) {
460
560
  const scale = palette[colorName];
461
561
  if (!scale) {
462
562
  throw new Error(`Color "${colorName}" not found in palette`);
463
563
  }
464
- return scale[shade];
564
+ return scale[shade2];
465
565
  }
466
566
 
467
567
  // src/bridge.ts
@@ -484,7 +584,7 @@ function bridgeShade(offset, seedShade, active) {
484
584
  function extendedBridgeShades(mode, seedShade, active, overrides) {
485
585
  const offsets = BRIDGE_OFFSETS[mode].extended;
486
586
  const at = (offset) => bridgeShade(offset, seedShade, active);
487
- const snap = (shade) => snapShade(shade, active);
587
+ const snap = (shade2) => snapShade(shade2, active);
488
588
  const offsetSubdued = at(offsets.subdued);
489
589
  const subdued = mode === "light" ? snap(Math.min(offsetSubdued, 100)) : snap(Math.max(offsetSubdued, 800));
490
590
  return {
@@ -539,20 +639,20 @@ var TINT_HUE_SHARE = 0.8;
539
639
  var APCA_WHITE_MAX_Y = { "aa-large": 0.4564, aa: 0.314, aaa: 0.1946 };
540
640
  var APCA_BLACK_MIN_Y = { "aa-large": 0.2831, aa: 0.4233, aaa: 0.5906 };
541
641
  var WCAG_FLOOR = { "aa-large": 3, aa: 4.5, aaa: 7 };
542
- function settleFill(scale, shade, target, active, views) {
642
+ function settleFill(scale, shade2, target, active, views) {
543
643
  const lum = (s) => views.map((v) => getContrastRatio(v.scale[s], "#000000", v.gamut) * 0.05 - 0.05);
544
644
  const whiteMax = Math.min(1.05 / WCAG_FLOOR[target] - 0.05, APCA_WHITE_MAX_Y[target]);
545
645
  const blackMin = Math.max(WCAG_FLOOR[target] * 0.05 - 0.05, APCA_BLACK_MIN_Y[target]);
546
646
  const ok = (s) => lum(s).every((y2) => y2 <= whiteMax) || lum(s).every((y2) => y2 >= blackMin);
547
- if (ok(shade)) return shade;
548
- const y = Math.max(...lum(shade));
647
+ if (ok(shade2)) return shade2;
648
+ const y = Math.max(...lum(shade2));
549
649
  const darkerFirst = y - whiteMax <= 2 * (blackMin - y);
550
- const at = active.indexOf(shade);
650
+ const at = active.indexOf(shade2);
551
651
  const darker = [at + 1, at + 2], lighter = [at - 1, at - 2];
552
652
  for (const i of darkerFirst ? [...darker, ...lighter] : [...lighter, ...darker]) {
553
653
  if (i >= 0 && i < active.length && scale[active[i]] && ok(active[i])) return active[i];
554
654
  }
555
- return shade;
655
+ return shade2;
556
656
  }
557
657
  var HOVER_SHIFT = 0.09;
558
658
  var ACTIVE_SHIFT = 0.15;
@@ -587,13 +687,13 @@ function findBestForeground(views, white, black, algorithm, contrastTarget, colo
587
687
  ].sort((a, b) => Number(b.wcag >= wcagMin) - Number(a.wcag >= wcagMin) || b.contrast - a.contrast);
588
688
  const extreme = { value: ends[0].value, ref: ends[0].ref };
589
689
  const best = ends[0].contrast;
590
- const steps = (which, refName) => activeShades.map((shade) => ({
591
- value: views[0][which][shade],
592
- ref: { type: "shade", colorName: refName, shade },
593
- contrast: getContrast((view) => view[which][shade]),
594
- wcag: wcagMin ? getWcag((view) => view[which][shade]) : Infinity,
690
+ const steps = (which, refName) => activeShades.map((shade2) => ({
691
+ value: views[0][which][shade2],
692
+ ref: { type: "shade", colorName: refName, shade: shade2 },
693
+ contrast: getContrast((view) => view[which][shade2]),
694
+ wcag: wcagMin ? getWcag((view) => view[which][shade2]) : Infinity,
595
695
  // the least chroma any view shows, so the sRGB and P3 tiers judge the hue alike and pick the same step
596
- chroma: Math.min(...views.map((view) => chromaOf(view[which][shade]))),
696
+ chroma: Math.min(...views.map((view) => chromaOf(view[which][shade2]))),
597
697
  own: which === "scale"
598
698
  }));
599
699
  const own = steps("scale", colorName);
@@ -636,7 +736,7 @@ function createExtendedSemanticColor(scale, neutral, white, black, mode, contras
636
736
  const warm = mode === "light" && seedColour.c >= 0.05 && (seedColour.h ?? 0) >= 40 && (seedColour.h ?? 0) <= 115;
637
737
  const subduedShade = warm && !overrides?.subdued ? snapShade(200, activeShades) : offsetSubdued;
638
738
  const seedStep = bridgeShade(0, seedShade, activeShades);
639
- const blackLabel = (shade) => getContrastRatio(scale[shade], black) > getContrastRatio(scale[shade], white);
739
+ const blackLabel = (shade2) => getContrastRatio(scale[shade2], black) > getContrastRatio(scale[shade2], white);
640
740
  const bridgeDefault = mode === "dark" && !overrides?.DEFAULT && offsetDefault !== seedStep && blackLabel(seedStep) ? seedStep : offsetDefault;
641
741
  const fillViews = [{ scale, gamut: gamuts.own }, ...gamuts.other ? [{ scale: gamuts.other.scale, gamut: gamuts.other.gamut }] : []];
642
742
  const defaultShade = colorName === "primary" || overrides?.DEFAULT ? bridgeDefault : settleFill(scale, bridgeDefault, contrastTarget, activeShades, fillViews);
@@ -756,7 +856,7 @@ function textOn(bg, neutral, white, black, active) {
756
856
  }
757
857
  function generateSurfaceTokens(palette, mode, overrides, shades, colors, backgrounds) {
758
858
  const activeShades = shadeKeys(shades);
759
- const snap = (shade) => snapShade(shade, activeShades);
859
+ const snap = (shade2) => snapShade(shade2, activeShades);
760
860
  const neutral = palette.neutral;
761
861
  if (!neutral) {
762
862
  throw new Error("Neutral palette not found");
@@ -807,7 +907,7 @@ function generateSurfaceTokens(palette, mode, overrides, shades, colors, backgro
807
907
  }
808
908
  function generateUtilityTokens(palette, mode, overrides, shades, seedShade, grounds) {
809
909
  const activeShades = shadeKeys(shades);
810
- const snap = (shade) => snapShade(shade, activeShades);
910
+ const snap = (shade2) => snapShade(shade2, activeShades);
811
911
  const neutral = palette.neutral;
812
912
  const primary = palette.primary;
813
913
  if (!neutral || !primary) {
@@ -925,11 +1025,11 @@ function checkRampChroma(palette) {
925
1025
  if (typeof scale === "string" || !scale) continue;
926
1026
  let peak = 0;
927
1027
  let atShade = 500;
928
- for (const [shade, color] of Object.entries(scale)) {
1028
+ for (const [shade2, color] of Object.entries(scale)) {
929
1029
  const { c } = parseToOklch(color);
930
1030
  if (c > peak) {
931
1031
  peak = c;
932
- atShade = Number(shade);
1032
+ atShade = Number(shade2);
933
1033
  }
934
1034
  }
935
1035
  results[name] = {
@@ -970,6 +1070,320 @@ function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa", gam
970
1070
  return { score, passed, total };
971
1071
  }
972
1072
 
1073
+ // src/grounds.ts
1074
+ var STATUS_GROUNDS = ["success", "warning", "destructive"];
1075
+ var GROUND_BASE_TOKENS = ["canvas", "canvas-foreground", "muted", "muted-foreground", "border", "input", "ring"];
1076
+ var GROUND_COLOR_PARTS = ["", "-foreground", "-subdued", "-subdued-foreground", "-hover", "-active"];
1077
+ var FILL_FLOOR = 3;
1078
+ var PANEL_FLOOR = 1.1;
1079
+ var TEXT_FLOOR = { "aa-large": 3, aa: 4.5, aaa: 7 };
1080
+ function groundTokenNames(colors) {
1081
+ return [...GROUND_BASE_TOKENS, ...colors.flatMap((c) => GROUND_COLOR_PARTS.map((p) => `${c}${p}`))];
1082
+ }
1083
+ function semanticColors(semantic) {
1084
+ const core = ["primary", "neutral", "success", "destructive", "warning"];
1085
+ return [...core, ...Object.keys(semantic).filter((n) => !core.includes(n) && n !== "muted")];
1086
+ }
1087
+ function reservedGroundNames(colors) {
1088
+ return [
1089
+ "canvas",
1090
+ "surface",
1091
+ "overlay",
1092
+ "foreground",
1093
+ "muted",
1094
+ "border",
1095
+ "input",
1096
+ "ring",
1097
+ "shadow",
1098
+ ...colors.flatMap((c) => [c, `${c}-subdued`])
1099
+ ];
1100
+ }
1101
+ function assertDistinctGroundNames(grounds, colors) {
1102
+ const seen = /* @__PURE__ */ new Map();
1103
+ for (const ground of grounds) {
1104
+ for (const token of groundTokenNames(colors)) {
1105
+ const name = `--on-${ground}-${token}`;
1106
+ const other = seen.get(name);
1107
+ if (other && other !== ground) {
1108
+ throw new Error(`Grounds "${other}" and "${ground}" would both emit ${name}; rename one of the backgrounds`);
1109
+ }
1110
+ seen.set(name, ground);
1111
+ }
1112
+ }
1113
+ }
1114
+ var valueOf = (ref, palette) => {
1115
+ switch (ref.type) {
1116
+ case "white":
1117
+ return palette.white;
1118
+ case "black":
1119
+ return palette.black;
1120
+ case "value":
1121
+ return ref.value;
1122
+ case "shade":
1123
+ return palette[ref.colorName][ref.shade];
1124
+ }
1125
+ };
1126
+ var shade = (colorName, step) => ({ type: "shade", colorName, shade: step });
1127
+ var sameRef = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1128
+ function fromSurfaceRef(ref) {
1129
+ switch (ref.type) {
1130
+ case "white":
1131
+ return { type: "white" };
1132
+ case "black":
1133
+ return { type: "black" };
1134
+ case "shade":
1135
+ return shade("neutral", ref.shade);
1136
+ case "value":
1137
+ return { type: "value", value: ref.value };
1138
+ }
1139
+ }
1140
+ function baseRefs(base, colors, ground, active) {
1141
+ const { semantic, surface, utility } = base;
1142
+ const refs = {};
1143
+ const sr = surface._refs;
1144
+ refs.canvas = fromSurfaceRef(ground === "canvas" ? sr.canvas : sr.surface);
1145
+ refs["canvas-foreground"] = fromSurfaceRef(ground === "canvas" ? sr["canvas-foreground"] : sr["surface-foreground"]);
1146
+ const muted = semantic.muted._shades;
1147
+ refs.muted = shade("neutral", snapShade(muted.DEFAULT, active));
1148
+ refs["muted-foreground"] = shade("neutral", snapShade(muted.foreground, active));
1149
+ const steps = utility._steps;
1150
+ refs.border = shade("neutral", steps.border);
1151
+ refs.input = shade("neutral", steps.input);
1152
+ refs.ring = shade("primary", steps.ring);
1153
+ for (const name of colors) {
1154
+ const c = semantic[name];
1155
+ refs[name] = shade(name, c._shades.DEFAULT);
1156
+ refs[`${name}-foreground`] = c._refs.foreground;
1157
+ refs[`${name}-subdued`] = shade(name, c._shades.subdued);
1158
+ refs[`${name}-subdued-foreground`] = c._refs["subdued-foreground"];
1159
+ refs[`${name}-hover`] = { type: "value", value: c.hover };
1160
+ refs[`${name}-active`] = { type: "value", value: c.active };
1161
+ }
1162
+ return refs;
1163
+ }
1164
+ var FAMILY_CHROMA = 0.05;
1165
+ function familyOf(bg, palette, colors, active) {
1166
+ const o = parseToOklch(bg);
1167
+ if ((o.c ?? 0) < FAMILY_CHROMA) return "neutral";
1168
+ let best = "neutral";
1169
+ let distance = 30;
1170
+ for (const name of colors) {
1171
+ if (name === "neutral") continue;
1172
+ const scale = palette[name];
1173
+ const ref = parseToOklch(scale[snapShade(500, active)]);
1174
+ if ((ref.c ?? 0) < 0.03) continue;
1175
+ const d = Math.abs((((ref.h ?? 0) - (o.h ?? 0)) % 360 + 540) % 360 - 180);
1176
+ if (d < distance) {
1177
+ distance = d;
1178
+ best = name;
1179
+ }
1180
+ }
1181
+ return best;
1182
+ }
1183
+ function searchGround(spec, base, baseCanvas, colors, views, mode, options, active) {
1184
+ const target = options?.contrastTarget ?? "aa";
1185
+ const algorithm = options?.contrastAlgorithm ?? "wcag";
1186
+ const textFloor = TEXT_FLOOR[target];
1187
+ const mutedFloor = target === "aaa" ? 7 : 4.5;
1188
+ const srgb = views[0].palette;
1189
+ const notes = [];
1190
+ const cr = (a, b) => Math.min(...views.map((v) => getContrastRatio(valueOf(a, v.palette), valueOf(b, v.palette), v.gamut)));
1191
+ const ground = spec.canvas;
1192
+ const groundL = parseToOklch(valueOf(ground, srgb)).l;
1193
+ const light = cr(ground, { type: "black" }) > cr(ground, { type: "white" });
1194
+ const farSide = (ref) => {
1195
+ const l = parseToOklch(valueOf(ref, srgb)).l;
1196
+ return light ? l < groundL : l > groundL;
1197
+ };
1198
+ const steps = (colorName) => active.filter((s) => srgb[colorName]?.[s] !== void 0).map((s) => shade(colorName, s));
1199
+ const tinted = spec.family !== "neutral";
1200
+ const own = steps(spec.family).filter(farSide);
1201
+ const pool = own.length >= 3 || tinted && own.length ? own : [...own, ...steps("neutral").filter(farSide)];
1202
+ const textPool = steps(spec.family);
1203
+ const closest = (list, to, aim2) => [...list].sort((a, b) => Math.abs(cr(a, to) - aim2) - Math.abs(cr(b, to) - aim2))[0];
1204
+ const panelCandidates = (list, vis) => {
1205
+ const drawn = list.filter((r) => cr(r, ground) >= PANEL_FLOOR);
1206
+ const byVis = (a, b) => Math.abs(cr(a, ground) - vis) - Math.abs(cr(b, ground) - vis);
1207
+ return [...drawn.filter(farSide).sort(byVis), ...drawn.filter((r) => !farSide(r)).sort(byVis)];
1208
+ };
1209
+ const inHue = (r) => !tinted || r.type === "shade" && r.colorName === spec.family;
1210
+ const keepsPlace = (r) => inHue(r) && farSide(r) && cr(r, ground) >= PANEL_FLOOR;
1211
+ const nearest = (colorName, from, on, floor) => {
1212
+ const list = steps(colorName).filter((r) => cr(r, on) >= floor);
1213
+ const at = active.indexOf(from);
1214
+ const position = (r) => active.indexOf(r.shade);
1215
+ return list.sort((a, b) => Math.abs(position(a) - at) - Math.abs(position(b) - at))[0];
1216
+ };
1217
+ const bestEnd = (on) => cr({ type: "white" }, on) >= cr({ type: "black" }, on) ? { type: "white" } : { type: "black" };
1218
+ const refs = {};
1219
+ refs.canvas = ground;
1220
+ refs["canvas-foreground"] = spec.foreground;
1221
+ const fgContrast = cr(spec.foreground, ground);
1222
+ const mutedVis = Math.max(cr(base.muted, baseCanvas), PANEL_FLOOR);
1223
+ const mutedPanels = [
1224
+ ...keepsPlace(base.muted) ? [base.muted] : [],
1225
+ ...panelCandidates(spec.family === "neutral" ? steps("neutral") : steps(spec.family), mutedVis)
1226
+ ];
1227
+ const aim = Math.max(mutedFloor, Math.min(7, fgContrast * 0.65));
1228
+ const quietOn = (panel) => {
1229
+ const reads = (r) => cr(r, ground) >= mutedFloor && (!panel || cr(r, panel) >= mutedFloor) && cr(r, ground) < fgContrast;
1230
+ if (inHue(base["muted-foreground"]) && reads(base["muted-foreground"]) && keepsPlace(base.muted)) return base["muted-foreground"];
1231
+ return closest(textPool.filter((r) => reads(r) && cr(r, ground) < fgContrast * 0.92), ground, aim);
1232
+ };
1233
+ const settled = mutedPanels.map((panel) => ({ panel, text: quietOn(panel) })).find((m) => m.text);
1234
+ refs.muted = settled?.panel ?? mutedPanels[0] ?? base.muted;
1235
+ const quiet = settled?.text ?? quietOn(void 0);
1236
+ if (quiet) {
1237
+ refs["muted-foreground"] = quiet;
1238
+ if (!settled) notes.push(`muted-foreground: reads on the ground but not on a muted panel at ${mutedFloor}:1`);
1239
+ } else {
1240
+ refs["muted-foreground"] = spec.foreground;
1241
+ notes.push(`muted-foreground: no step quieter than the body text reads at ${mutedFloor}:1, so it is the body colour`);
1242
+ }
1243
+ const borderVis = cr(base.border, baseCanvas);
1244
+ const borderReads = (r) => cr(r, ground) >= Math.min(1.15, borderVis);
1245
+ refs.border = keepsPlace(base.border) && cr(base.border, ground) >= borderVis * 0.9 && cr(base.border, ground) <= borderVis * 2 ? base.border : closest([...pool, ...steps(spec.family)].filter(borderReads), ground, borderVis) ?? base.border;
1246
+ refs.input = inHue(base.input) && cr(base.input, ground) >= FILL_FLOOR ? base.input : [...pool].filter((r) => cr(r, ground) >= FILL_FLOOR).sort((a, b) => cr(a, ground) - cr(b, ground))[0] ?? bestEnd(ground);
1247
+ const ringFamily = tinted ? spec.family : "primary";
1248
+ const ringFrom = tinted ? base[spec.family].shade : base.ring.shade;
1249
+ refs.ring = inHue(base.ring) && cr(base.ring, ground) >= FILL_FLOOR ? base.ring : nearest(ringFamily, ringFrom, ground, FILL_FLOOR) ?? bestEnd(ground);
1250
+ for (const name of colors) {
1251
+ const src = tinted && (name === "primary" || name === "neutral") ? spec.family : name;
1252
+ const fillRef = base[src];
1253
+ const fillShade = fillRef.shade;
1254
+ const scaleIn = (v) => v.palette[src];
1255
+ const neutralIn = (v) => v.palette.neutral;
1256
+ const labelOn = (bg, role2, pageGrounds = []) => {
1257
+ const found = findBestForeground(
1258
+ views.map((v) => ({ background: valueOf(bg, v.palette), scale: scaleIn(v), neutral: neutralIn(v), gamut: v.gamut })),
1259
+ srgb.white,
1260
+ srgb.black,
1261
+ algorithm,
1262
+ target,
1263
+ src,
1264
+ active,
1265
+ role2,
1266
+ options?.foreground ?? "balanced",
1267
+ mode,
1268
+ options?.wcagFloor ?? true,
1269
+ pageGrounds
1270
+ );
1271
+ return found.ref;
1272
+ };
1273
+ const setStates = (fill, label) => {
1274
+ const f = valueOf(fill, srgb), l = valueOf(label, srgb);
1275
+ refs[`${name}-hover`] = { type: "value", value: stateOf(f, l, HOVER_SHIFT, views[0].gamut) };
1276
+ refs[`${name}-active`] = { type: "value", value: stateOf(f, l, ACTIVE_SHIFT, views[0].gamut) };
1277
+ };
1278
+ if (tinted && name === "neutral") {
1279
+ const tonal = panelCandidates(steps(src), 1.6).map((fill2) => ({ fill: fill2, label: labelOn(fill2, "tint") })).find((t) => cr(t.label, t.fill) >= textFloor);
1280
+ const fill = tonal?.fill ?? steps(src).filter(farSide)[0] ?? bestEnd(ground);
1281
+ const label = tonal?.label ?? labelOn(fill, "fill");
1282
+ refs[name] = fill;
1283
+ refs[`${name}-foreground`] = label;
1284
+ setStates(fill, label);
1285
+ } else if (inHue(fillRef) && cr(fillRef, ground) >= FILL_FLOOR) {
1286
+ refs[name] = fillRef;
1287
+ refs[`${name}-foreground`] = base[`${src}-foreground`];
1288
+ refs[`${name}-hover`] = base[`${src}-hover`];
1289
+ refs[`${name}-active`] = base[`${src}-active`];
1290
+ } else {
1291
+ const turnsOver = spec.kind === "background" && spec.family === src && src !== "neutral";
1292
+ const ramp = steps(src);
1293
+ const fill = turnsOver ? light ? ramp[ramp.length - 1] : ramp[0] : nearest(src, fillShade, ground, FILL_FLOOR) ?? bestEnd(ground);
1294
+ const label = turnsOver ? labelOn(fill, "tint") : labelOn(fill, "fill");
1295
+ refs[name] = fill;
1296
+ refs[`${name}-foreground`] = label;
1297
+ setStates(fill, label);
1298
+ if (cr(fill, ground) < FILL_FLOOR) notes.push(`${name}: no step stands out from the ground at ${FILL_FLOOR}:1`);
1299
+ }
1300
+ const tint = base[`${src}-subdued`];
1301
+ const tintLabel = base[`${src}-subdued-foreground`];
1302
+ const readsOnBoth = (label, on) => cr(label, on) >= textFloor && cr(label, ground) >= textFloor;
1303
+ const role = tintLabel.type === "shade" && tintLabel.colorName === src ? "tint" : "fill";
1304
+ const groundValue = [valueOf(ground, srgb)];
1305
+ const tintVis = Math.max(cr(tint, baseCanvas), PANEL_FLOOR);
1306
+ let pair = keepsPlace(tint) && readsOnBoth(tintLabel, tint) ? { tint, label: tintLabel } : void 0;
1307
+ const tints = panelCandidates(steps(src), tintVis);
1308
+ for (const candidate of tints) {
1309
+ if (pair) break;
1310
+ if (readsOnBoth(tintLabel, candidate)) {
1311
+ pair = { tint: candidate, label: tintLabel };
1312
+ break;
1313
+ }
1314
+ const label = labelOn(candidate, role, groundValue);
1315
+ if (readsOnBoth(label, candidate)) pair = { tint: candidate, label };
1316
+ }
1317
+ if (!pair) {
1318
+ const fallback = tints[0] ?? tint;
1319
+ pair = { tint: fallback, label: labelOn(fallback, role, groundValue) };
1320
+ notes.push(`${name}-subdued-foreground: no label reads on both a tint and the ground at ${textFloor}:1`);
1321
+ }
1322
+ refs[`${name}-subdued`] = pair.tint;
1323
+ refs[`${name}-subdued-foreground`] = pair.label;
1324
+ }
1325
+ const tokens = Object.fromEntries(Object.entries(refs).map(([k, r]) => [k, valueOf(r, srgb)]));
1326
+ return { kind: spec.kind, tokens, _refs: refs, changed: [], notes };
1327
+ }
1328
+ function generateGroundTokens(tiers, mode, views, options) {
1329
+ const base = { semantic: tiers.semantic[mode], surface: tiers.surface[mode], utility: tiers.utility[mode] };
1330
+ const active = resolveShades(options?.shades);
1331
+ const srgb = views[0].palette;
1332
+ const colors = semanticColors(base.semantic);
1333
+ const out = {};
1334
+ const canvasRefs = baseRefs(base, colors, "canvas", active);
1335
+ const surfaceRefs = baseRefs(base, colors, "surface", active);
1336
+ const baseOf = (refs) => ({
1337
+ kind: "base",
1338
+ tokens: Object.fromEntries(Object.entries(refs).map(([k, r]) => [k, valueOf(r, srgb)])),
1339
+ _refs: refs,
1340
+ changed: [],
1341
+ notes: []
1342
+ });
1343
+ out.canvas = baseOf(canvasRefs);
1344
+ out.surface = baseOf(surfaceRefs);
1345
+ const specs = [];
1346
+ for (const name of STATUS_GROUNDS) {
1347
+ specs.push({
1348
+ name: `${name}-subdued`,
1349
+ kind: "status",
1350
+ canvas: canvasRefs[`${name}-subdued`],
1351
+ foreground: canvasRefs[`${name}-subdued-foreground`],
1352
+ family: name
1353
+ });
1354
+ }
1355
+ for (const [name, bg] of Object.entries(base.surface.backgrounds ?? {})) {
1356
+ specs.push({
1357
+ name,
1358
+ kind: "background",
1359
+ canvas: { type: "value", value: bg.DEFAULT },
1360
+ foreground: fromSurfaceRef(bg._refs.foreground),
1361
+ family: familyOf(bg.DEFAULT, srgb, colors, active)
1362
+ });
1363
+ }
1364
+ const order = options?.grounds === "text" ? ["canvas", "canvas-foreground"] : groundTokenNames(colors);
1365
+ if (options?.grounds === "text") {
1366
+ for (const name of ["canvas", "surface"]) {
1367
+ const g = out[name];
1368
+ g.tokens = Object.fromEntries(order.map((k) => [k, g.tokens[k]]));
1369
+ g._refs = Object.fromEntries(order.map((k) => [k, g._refs[k]]));
1370
+ }
1371
+ }
1372
+ for (const spec of specs) {
1373
+ const searched = searchGround(spec, canvasRefs, canvasRefs.canvas, colors, views, mode, options, active);
1374
+ const g = {
1375
+ ...searched,
1376
+ // notes describe tokens a text-only ground does not carry
1377
+ notes: options?.grounds === "text" ? [] : searched.notes,
1378
+ tokens: Object.fromEntries(order.map((k) => [k, searched.tokens[k]])),
1379
+ _refs: Object.fromEntries(order.map((k) => [k, searched._refs[k]]))
1380
+ };
1381
+ g.changed = Object.keys(g._refs).filter((k) => !GROUND_BASE_TOKENS.slice(0, 2).includes(k) && !sameRef(g._refs[k], canvasRefs[k]));
1382
+ out[spec.name] = g;
1383
+ }
1384
+ return out;
1385
+ }
1386
+
973
1387
  // src/generate.ts
974
1388
  var defaultTypography = {
975
1389
  fontSize: {
@@ -1049,7 +1463,15 @@ function generateTokens(brandColors, options) {
1049
1463
  const scaleOptions = {
1050
1464
  seedShade: options?.seedShade,
1051
1465
  seedShades: options?.seedShades,
1052
- shades: options?.shades
1466
+ shades: options?.shades,
1467
+ lightEnd: options?.lightnessRange?.light,
1468
+ darkEnd: options?.lightnessRange?.dark,
1469
+ tintFloor: options?.tintFloor,
1470
+ chroma: options?.chroma,
1471
+ hueDrift: options?.hueDrift,
1472
+ families: options?.families,
1473
+ familyPins: options?.pins,
1474
+ aliases: options?.aliases
1053
1475
  };
1054
1476
  const primitives = generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "srgb" });
1055
1477
  const wide = options?.gamut === "p3" ? generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "p3" }) : void 0;
@@ -1079,8 +1501,20 @@ function generateTokens(brandColors, options) {
1079
1501
  own: "srgb",
1080
1502
  ...wide ? { other: { gamut: "p3", palette: wide } } : {}
1081
1503
  });
1504
+ const withGrounds = options?.grounds !== "none";
1505
+ const colors = semanticColors(tiers.semantic.light);
1506
+ const reserved = reservedGroundNames(colors);
1507
+ for (const name of withGrounds ? Object.keys(options?.backgrounds ?? {}) : []) {
1508
+ if (reserved.includes(name)) {
1509
+ throw new Error(`Background name "${name}" is taken: it is already a token or a ground. Reserved: ${reserved.join(", ")}`);
1510
+ }
1511
+ }
1512
+ const views = [{ palette: primitives, gamut: "srgb" }, ...wide ? [{ palette: wide, gamut: "p3" }] : []];
1513
+ const groundTokens = withGrounds ? { light: generateGroundTokens(tiers, "light", views, options), dark: generateGroundTokens(tiers, "dark", views, options) } : void 0;
1514
+ if (groundTokens) assertDistinctGroundNames(Object.keys(groundTokens.light), colors);
1082
1515
  return {
1083
1516
  ...tiers,
1517
+ ...groundTokens ? { grounds: groundTokens } : {},
1084
1518
  pageContrast: { light: pageContrast(tiers, "light"), dark: pageContrast(tiers, "dark") },
1085
1519
  spacing: {},
1086
1520
  typography: defaultTypography,
@@ -1108,9 +1542,9 @@ function pageContrast(tiers, mode) {
1108
1542
  }
1109
1543
 
1110
1544
  // src/usage.ts
1111
- var TEXT_FLOOR = { "aa-large": 3, aa: 4.5, aaa: 7 };
1545
+ var TEXT_FLOOR2 = { "aa-large": 3, aa: 4.5, aaa: 7 };
1112
1546
  function usageReport(tokens, target = "aa") {
1113
- const floors = { text: TEXT_FLOOR[target], shape: 3 };
1547
+ const floors = { text: TEXT_FLOOR2[target], shape: 3 };
1114
1548
  const verdict = (r) => r >= floors.text ? "text" : r >= floors.shape ? "shape" : "none";
1115
1549
  const mode = (m) => {
1116
1550
  const surface = tokens.surface[m];
@@ -1147,7 +1581,7 @@ function formatColor(color, format) {
1147
1581
  }
1148
1582
  function colorScaleToCssVars(name, scale, colorFormat = "hex", indent = " ") {
1149
1583
  return Object.entries(scale).map(
1150
- ([shade, color]) => `${indent}--color-${name}-${shade}: ${formatColor(color, colorFormat)};`
1584
+ ([shade2, color]) => `${indent}--color-${name}-${shade2}: ${formatColor(color, colorFormat)};`
1151
1585
  );
1152
1586
  }
1153
1587
  function emitPrimitiveVars(tokens, colorFormat, want, indent, inFamily, scoped) {
@@ -1294,12 +1728,52 @@ function emitUtilityVars(mode, indent, active, seedShade, steps) {
1294
1728
  ];
1295
1729
  const lines = [];
1296
1730
  for (const [token, ref] of refs) {
1297
- const [scale, shade] = ref.split(/-(?=\d+$)/);
1298
- const snapped = `${scale}-${snapShade(Number(shade), active)}`;
1731
+ const [scale, shade2] = ref.split(/-(?=\d+$)/);
1732
+ const snapped = `${scale}-${snapShade(Number(shade2), active)}`;
1299
1733
  lines.push(`${indent}--${token}: ${primitiveToVar(snapped)};`);
1300
1734
  }
1301
1735
  return lines;
1302
1736
  }
1737
+ function groundRefToVar(ref, colorFormat) {
1738
+ return ref.type === "value" ? formatColor(ref.value, colorFormat) : refToVar(ref);
1739
+ }
1740
+ function ownGroundTokens(tokens, ground) {
1741
+ const grounds = tokens.grounds;
1742
+ const names = Object.keys(grounds.light[ground]._refs);
1743
+ if (ground === "canvas") return names;
1744
+ const same = (mode, token) => JSON.stringify(grounds[mode][ground]._refs[token]) === JSON.stringify(grounds[mode].canvas._refs[token]);
1745
+ return names.filter((token) => !same("light", token) || !same("dark", token));
1746
+ }
1747
+ function emitGroundVars(tokens, mode, colorFormat, indent) {
1748
+ const lines = [];
1749
+ for (const [ground, set] of Object.entries(tokens.grounds?.[mode] ?? {})) {
1750
+ for (const token of ownGroundTokens(tokens, ground)) {
1751
+ lines.push(`${indent}--on-${ground}-${token}: ${groundRefToVar(set._refs[token], colorFormat)};`);
1752
+ }
1753
+ }
1754
+ return lines;
1755
+ }
1756
+ function emitGroundScopes(tokens, rebind) {
1757
+ const grounds = tokens.grounds?.light;
1758
+ if (!grounds || Object.keys(grounds).length === 0) return [];
1759
+ const lines = [
1760
+ "",
1761
+ '/* Grounds: mark an element data-surface="<ground>" and everything inside it reads',
1762
+ " that ground's tokens. canvas and surface reset to the page's own, for a card inside a band. */"
1763
+ ];
1764
+ for (const [ground, set] of Object.entries(grounds)) {
1765
+ const names = Object.keys(set._refs);
1766
+ const own = new Set(ownGroundTokens(tokens, ground));
1767
+ lines.push(`${GROUND_SELECTOR(ground)} {`);
1768
+ for (const token of names) lines.push(` --${token}: var(--on-${own.has(token) ? ground : "canvas"}-${token});`);
1769
+ if (rebind) for (const token of names) lines.push(` --color-${token}: var(--${token});`);
1770
+ lines.push(" background-color: var(--canvas);");
1771
+ lines.push(" color: var(--canvas-foreground);");
1772
+ lines.push("}");
1773
+ }
1774
+ return lines;
1775
+ }
1776
+ var GROUND_SELECTOR = (ground) => `[data-surface="${ground}"]`;
1303
1777
  function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shades, families, seedShade, seedShades) {
1304
1778
  const lines = [];
1305
1779
  const anchors = { seedShade, seedShades };
@@ -1308,7 +1782,8 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1308
1782
  const scoped = !!families && families.length > 0;
1309
1783
  const inFamily = familyFilter(families);
1310
1784
  const wantPrimitives = want.has("primitives") || want.has("ramp");
1311
- const wantModes = want.has("semantic") || !scoped && (want.has("surface") || want.has("utility"));
1785
+ const wantGrounds = want.has("grounds") && !scoped && !!tokens.grounds;
1786
+ const wantModes = want.has("semantic") || !scoped && (want.has("surface") || want.has("utility")) || wantGrounds;
1312
1787
  const modeBody = (mode, indent, withComments) => {
1313
1788
  const body = [];
1314
1789
  if (want.has("surface") && !scoped) {
@@ -1324,6 +1799,11 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1324
1799
  if (want.has("semantic")) {
1325
1800
  if (withComments) body.push(`${indent}/* Semantic Colors */`);
1326
1801
  body.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1802
+ if (withComments) body.push("");
1803
+ }
1804
+ if (wantGrounds) {
1805
+ if (withComments) body.push(`${indent}/* Grounds: read through data-surface, below */`);
1806
+ body.push(...emitGroundVars(tokens, mode, colorFormat, indent));
1327
1807
  }
1328
1808
  while (body.length > 0 && body[body.length - 1] === "") body.pop();
1329
1809
  return body;
@@ -1354,6 +1834,7 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1354
1834
  lines.push(" }");
1355
1835
  lines.push("}");
1356
1836
  }
1837
+ if (wantGrounds) lines.push(...emitGroundScopes(tokens, false));
1357
1838
  return lines.join("\n");
1358
1839
  }
1359
1840
  var MODE_SELECTORS = {
@@ -1388,7 +1869,8 @@ var TOKEN_SECTIONS = [
1388
1869
  "ramp",
1389
1870
  "semantic",
1390
1871
  "surface",
1391
- "utility"
1872
+ "utility",
1873
+ "grounds"
1392
1874
  ];
1393
1875
  var ALL_SECTIONS = [...TOKEN_SECTIONS];
1394
1876
  function familyFilter(families) {
@@ -1454,7 +1936,7 @@ function emitThemeRebinding(aliases, indent) {
1454
1936
  }
1455
1937
  return lines;
1456
1938
  }
1457
- function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, anchors) {
1939
+ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, anchors, wantGrounds) {
1458
1940
  const lines = [];
1459
1941
  const seedShade = anchors.seedShade;
1460
1942
  if (want.has("surface") && !scoped) {
@@ -1470,9 +1952,14 @@ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases,
1470
1952
  if (want.has("semantic")) {
1471
1953
  lines.push(`${indent}/* Semantic Colors */`);
1472
1954
  lines.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1955
+ lines.push("");
1956
+ }
1957
+ if (wantGrounds) {
1958
+ lines.push(`${indent}/* Grounds: read through data-surface, below */`);
1959
+ lines.push(...emitGroundVars(tokens, mode, colorFormat, indent));
1473
1960
  }
1474
1961
  while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
1475
- lines.push(...emitThemeRebinding(aliases, indent));
1962
+ if (aliases.length > 0) lines.push(...emitThemeRebinding(aliases, indent));
1476
1963
  return lines;
1477
1964
  }
1478
1965
  function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replacePalette = true, sections, shades, families, seedShade, seedShades) {
@@ -1484,7 +1971,8 @@ function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replace
1484
1971
  const inFamily = familyFilter(families);
1485
1972
  const aliases = semanticAliasNames(tokens, sections, families);
1486
1973
  const wantPrimitives = want.has("primitives") || want.has("ramp");
1487
- const wantModes = aliases.length > 0;
1974
+ const wantGrounds = want.has("grounds") && !scoped && !!tokens.grounds;
1975
+ const wantModes = aliases.length > 0 || wantGrounds;
1488
1976
  lines.push("@theme static {");
1489
1977
  if (replacePalette && !scoped) {
1490
1978
  lines.push(" /* Clear Tailwind's stock palette, so a colour class this file does not");
@@ -1510,21 +1998,22 @@ function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replace
1510
1998
  lines.push("");
1511
1999
  lines.push("/* Light Mode */");
1512
2000
  lines.push(`${MODE_SELECTORS.light} {`);
1513
- lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2001
+ lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
1514
2002
  lines.push("}");
1515
2003
  lines.push("");
1516
2004
  lines.push("/* Dark Mode */");
1517
2005
  lines.push(`${MODE_SELECTORS.dark} {`);
1518
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2006
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
1519
2007
  lines.push("}");
1520
2008
  lines.push("");
1521
2009
  lines.push("/* System Preference: Dark Mode */");
1522
2010
  lines.push("@media (prefers-color-scheme: dark) {");
1523
2011
  lines.push(` ${MODE_SELECTORS.systemDark} {`);
1524
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2012
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
1525
2013
  lines.push(" }");
1526
2014
  lines.push("}");
1527
2015
  }
2016
+ if (wantGrounds) lines.push(...emitGroundScopes(tokens, true));
1528
2017
  return lines.join("\n");
1529
2018
  }
1530
2019
  function exportToTailwindV3(tokens, colorFormat = "hex") {
@@ -1540,8 +2029,8 @@ function exportToTailwindV3(tokens, colorFormat = "hex") {
1540
2029
  config.theme.extend.colors[name] = formatColor(scale, colorFormat);
1541
2030
  } else {
1542
2031
  config.theme.extend.colors[name] = {};
1543
- for (const [shade, color] of Object.entries(scale)) {
1544
- config.theme.extend.colors[name][shade] = formatColor(color, colorFormat);
2032
+ for (const [shade2, color] of Object.entries(scale)) {
2033
+ config.theme.extend.colors[name][shade2] = formatColor(color, colorFormat);
1545
2034
  }
1546
2035
  }
1547
2036
  }
@@ -1557,8 +2046,8 @@ function exportToTailwindV3(tokens, colorFormat = "hex") {
1557
2046
  active: `var(--${name}-active)`
1558
2047
  };
1559
2048
  if (primitiveScale && typeof primitiveScale !== "string") {
1560
- for (const [shade, color] of Object.entries(primitiveScale)) {
1561
- colorObj[shade] = formatColor(color, colorFormat);
2049
+ for (const [shade2, color] of Object.entries(primitiveScale)) {
2050
+ colorObj[shade2] = formatColor(color, colorFormat);
1562
2051
  }
1563
2052
  }
1564
2053
  config.theme.extend.colors[name] = colorObj;
@@ -1575,8 +2064,8 @@ function exportToTailwindV3(tokens, colorFormat = "hex") {
1575
2064
  active: `var(--${name}-active)`
1576
2065
  };
1577
2066
  if (primitiveScale && typeof primitiveScale !== "string") {
1578
- for (const [shade, color] of Object.entries(primitiveScale)) {
1579
- colorObj[shade] = formatColor(color, colorFormat);
2067
+ for (const [shade2, color] of Object.entries(primitiveScale)) {
2068
+ colorObj[shade2] = formatColor(color, colorFormat);
1580
2069
  }
1581
2070
  }
1582
2071
  config.theme.extend.colors[name] = colorObj;
@@ -1617,8 +2106,8 @@ function exportToDtcg(tokens) {
1617
2106
  dtcg[name] = dtcgColorValue(scale);
1618
2107
  } else {
1619
2108
  const group = { $type: "color" };
1620
- for (const [shade, color] of Object.entries(scale)) {
1621
- group[shade] = { $value: formatColorAs(color, "hex") };
2109
+ for (const [shade2, color] of Object.entries(scale)) {
2110
+ group[shade2] = { $value: formatColorAs(color, "hex") };
1622
2111
  }
1623
2112
  dtcg[name] = group;
1624
2113
  }
@@ -1680,6 +2169,16 @@ function exportToDtcg(tokens) {
1680
2169
  ring: { $value: formatColorAs(util.ring, "hex") },
1681
2170
  shadow: { $value: formatColorAs(util.shadow, "hex") }
1682
2171
  };
2172
+ const grounds = tokens.grounds?.[mode];
2173
+ if (grounds) {
2174
+ const groundGroup = {};
2175
+ for (const [name, set] of Object.entries(grounds)) {
2176
+ const group = { $type: "color" };
2177
+ for (const [token, value] of Object.entries(set.tokens)) group[token] = { $value: formatColorAs(value, "hex") };
2178
+ groundGroup[name] = group;
2179
+ }
2180
+ semanticGroup.ground = groundGroup;
2181
+ }
1683
2182
  dtcg[mode] = semanticGroup;
1684
2183
  }
1685
2184
  return JSON.stringify(dtcg, null, 2);
@@ -1728,6 +2227,7 @@ function selectTokenSections(tokens, sections, families) {
1728
2227
  }
1729
2228
  if (want.has("surface") && !scoped) out.surface = tokens.surface;
1730
2229
  if (want.has("utility") && !scoped) out.utility = tokens.utility;
2230
+ if (want.has("grounds") && !scoped && tokens.grounds) out.grounds = tokens.grounds;
1731
2231
  if (tokens.p3) {
1732
2232
  const wide = selectTokenSections({ ...tokens, ...tokens.p3, p3: void 0 }, sections, families);
1733
2233
  out.p3 = Object.fromEntries(
@@ -1780,13 +2280,27 @@ function walk(css, onDeclaration) {
1780
2280
  const lines = css.split("\n");
1781
2281
  const stack = [];
1782
2282
  let pending = "";
2283
+ let inComment = false;
1783
2284
  lines.forEach((line, index) => {
1784
2285
  const trimmed = line.trim();
1785
2286
  const declaration = /^(--[a-z0-9-]+)\s*:\s*(.+?);\s*$/i.exec(trimmed);
1786
- if (declaration && stack.length > 0) {
2287
+ if (declaration && stack.length > 0 && !inComment) {
1787
2288
  onDeclaration(line, index, stack.join(" > "), declaration[1], declaration[2]);
1788
2289
  }
1789
- for (const char of trimmed) {
2290
+ for (let i = 0; i < trimmed.length; i++) {
2291
+ const char = trimmed[i];
2292
+ if (inComment) {
2293
+ if (char === "*" && trimmed[i + 1] === "/") {
2294
+ inComment = false;
2295
+ i++;
2296
+ }
2297
+ continue;
2298
+ }
2299
+ if (char === "/" && trimmed[i + 1] === "*") {
2300
+ inComment = true;
2301
+ i++;
2302
+ continue;
2303
+ }
1790
2304
  if (char === "{") {
1791
2305
  stack.push(normaliseSelector(pending));
1792
2306
  pending = "";
@@ -1797,7 +2311,7 @@ function walk(css, onDeclaration) {
1797
2311
  pending += char;
1798
2312
  }
1799
2313
  }
1800
- if (trimmed.endsWith("{") || trimmed.endsWith("}")) pending = "";
2314
+ if (!inComment && (trimmed.endsWith("{") || trimmed.endsWith("}"))) pending = "";
1801
2315
  });
1802
2316
  }
1803
2317
  function readDeclarations(css) {
@@ -1895,6 +2409,31 @@ function diffSlice(target, slice) {
1895
2409
  return { matches: differing.length === 0 && missing.length === 0, differing, missing };
1896
2410
  }
1897
2411
 
2412
+ // src/contract.ts
2413
+ var ALIASES = new Set(ALIAS_PAIRS.map(([, alias]) => alias));
2414
+ var TEXT = 4.5;
2415
+ function stepContract(palette) {
2416
+ const families = Object.entries(palette).filter(([name, scale]) => typeof scale === "object" && name !== "neutral" && !ALIASES.has(name)).map(([name, scale]) => [name, scale]);
2417
+ const out = [];
2418
+ for (const step of VALID_SHADES) {
2419
+ for (const [role, ground] of [
2420
+ ["text on white", "#ffffff"],
2421
+ ["text on black", "#000000"]
2422
+ ]) {
2423
+ const holds = [];
2424
+ const fails = [];
2425
+ for (const [name, scale] of families) {
2426
+ const colour = scale[step];
2427
+ if (!colour) continue;
2428
+ (getContrastRatio(colour, ground) >= TEXT ? holds : fails).push(name);
2429
+ }
2430
+ if (!holds.length || !fails.length) continue;
2431
+ out.push({ step, role, holds, fails, odd: fails.length <= holds.length ? fails : holds });
2432
+ }
2433
+ }
2434
+ return out;
2435
+ }
2436
+
1898
2437
  // src/seed.ts
1899
2438
  var GENERATOR_NAME = "@designtools/tokens";
1900
2439
  function stableStringify(value) {
@@ -1935,6 +2474,22 @@ function withJsonProvenance(json, p) {
1935
2474
  };
1936
2475
  return JSON.stringify(stamped, null, 2);
1937
2476
  }
2477
+ function rangeOf(seed) {
2478
+ const r = seed.lightnessRange;
2479
+ if (!r || r.light === void 0 && r.dark === void 0) return void 0;
2480
+ return { ...r.light !== void 0 ? { light: r.light / 100 } : {}, ...r.dark !== void 0 ? { dark: r.dark / 100 } : {} };
2481
+ }
2482
+ function familiesOf(seed) {
2483
+ const entries = Object.entries(seed.families ?? {}).filter(([, f]) => f && Object.keys(f).length);
2484
+ if (!entries.length) return void 0;
2485
+ return Object.fromEntries(
2486
+ entries.map(([name, f]) => {
2487
+ const range = f.lightnessRange ? rangeOf({ lightnessRange: f.lightnessRange }) : void 0;
2488
+ const { lightnessRange: _, ...rest } = f;
2489
+ return [name, { ...rest, ...range ? { lightnessRange: range } : {} }];
2490
+ })
2491
+ );
2492
+ }
1938
2493
 
1939
2494
  export {
1940
2495
  APCAUnavailableError,
@@ -1983,10 +2538,17 @@ export {
1983
2538
  checkSurfaceContrast,
1984
2539
  checkRampChroma,
1985
2540
  computeAccessibilityScore,
2541
+ STATUS_GROUNDS,
2542
+ GROUND_BASE_TOKENS,
2543
+ GROUND_COLOR_PARTS,
2544
+ groundTokenNames,
2545
+ reservedGroundNames,
2546
+ generateGroundTokens,
1986
2547
  generateTokens,
1987
2548
  usageReport,
1988
2549
  serialiseUsage,
1989
2550
  WIDE_GAMUT_QUERY,
2551
+ GROUND_SELECTOR,
1990
2552
  exportToCss,
1991
2553
  overrideContract,
1992
2554
  TOKEN_SECTIONS,
@@ -2001,11 +2563,14 @@ export {
2001
2563
  readDeclarations,
2002
2564
  mergeSlice,
2003
2565
  diffSlice,
2566
+ stepContract,
2004
2567
  GENERATOR_NAME,
2005
2568
  stableStringify,
2006
2569
  fingerprint,
2007
2570
  seedFingerprint,
2008
2571
  provenanceComment,
2009
2572
  parseProvenance,
2010
- withJsonProvenance
2573
+ withJsonProvenance,
2574
+ rangeOf,
2575
+ familiesOf
2011
2576
  };