@designtools/tokens 0.11.1 → 0.13.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.
@@ -64,9 +64,9 @@ function snapShade(shade2, active) {
64
64
  }
65
65
  return best;
66
66
  }
67
- function sampleCurve(curve, t) {
67
+ function sampleCurve(curve, t2) {
68
68
  if (curve.length === 1) return curve[0];
69
- const pos = t * (curve.length - 1);
69
+ const pos = t2 * (curve.length - 1);
70
70
  const i = Math.min(Math.floor(pos), curve.length - 2);
71
71
  return curve[i] + (curve[i + 1] - curve[i]) * (pos - i);
72
72
  }
@@ -150,26 +150,26 @@ function oklchToHex(color) {
150
150
  }
151
151
  function computeScaleChroma(scaleValue, baseChroma) {
152
152
  if (scaleValue < 0.03) {
153
- const t2 = scaleValue / 0.03;
154
- return baseChroma * (0.08 + 0.15 * Math.pow(t2, 1.5));
153
+ const t3 = scaleValue / 0.03;
154
+ return baseChroma * (0.08 + 0.15 * Math.pow(t3, 1.5));
155
155
  }
156
156
  if (scaleValue < 0.12) {
157
- const t2 = (scaleValue - 0.03) / 0.09;
158
- return baseChroma * (0.23 + 0.32 * Math.pow(t2, 1.3));
157
+ const t3 = (scaleValue - 0.03) / 0.09;
158
+ return baseChroma * (0.23 + 0.32 * Math.pow(t3, 1.3));
159
159
  }
160
160
  if (scaleValue < 0.28) {
161
- const t2 = (scaleValue - 0.12) / 0.16;
162
- return baseChroma * (0.55 + 0.3 * Math.pow(t2, 1.1));
161
+ const t3 = (scaleValue - 0.12) / 0.16;
162
+ return baseChroma * (0.55 + 0.3 * Math.pow(t3, 1.1));
163
163
  }
164
164
  if (scaleValue < 0.45) {
165
- const t2 = (scaleValue - 0.28) / 0.17;
166
- return baseChroma * (0.85 + 0.15 * t2);
165
+ const t3 = (scaleValue - 0.28) / 0.17;
166
+ return baseChroma * (0.85 + 0.15 * t3);
167
167
  }
168
168
  if (scaleValue < 0.85) {
169
169
  return baseChroma;
170
170
  }
171
- const t = (scaleValue - 0.85) / 0.15;
172
- return baseChroma * (1 - 0.06 * t);
171
+ const t2 = (scaleValue - 0.85) / 0.15;
172
+ return baseChroma * (1 - 0.06 * t2);
173
173
  }
174
174
  var LIGHTNESS_FACTORS = {
175
175
  // Radix-style easing: smooth gradients at the light end, larger jumps at the
@@ -207,8 +207,8 @@ function refitThroughPins(lightness, anchor, pins) {
207
207
  const da = held.get(a) - lightness[a];
208
208
  const db = held.get(b) - lightness[b];
209
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;
210
+ const t2 = (i - a) / (b - a);
211
+ out[i] = lightness[i] + da * (1 - t2) + db * t2;
212
212
  }
213
213
  }
214
214
  for (let i = 1; i < n; i++) {
@@ -386,26 +386,26 @@ function classifyAPCALevel(lcValue) {
386
386
  }
387
387
  function computeScaleChromaPerceptual(scaleValue, baseChroma) {
388
388
  if (scaleValue < 0.03) {
389
- const t2 = scaleValue / 0.03;
390
- return baseChroma * (0.3 + 0.1 * t2);
389
+ const t3 = scaleValue / 0.03;
390
+ return baseChroma * (0.3 + 0.1 * t3);
391
391
  }
392
392
  if (scaleValue < 0.12) {
393
- const t2 = (scaleValue - 0.03) / 0.09;
394
- return baseChroma * (0.4 + 0.25 * t2);
393
+ const t3 = (scaleValue - 0.03) / 0.09;
394
+ return baseChroma * (0.4 + 0.25 * t3);
395
395
  }
396
396
  if (scaleValue < 0.3) {
397
- const t2 = (scaleValue - 0.12) / 0.18;
398
- return baseChroma * (0.65 + 0.25 * t2);
397
+ const t3 = (scaleValue - 0.12) / 0.18;
398
+ return baseChroma * (0.65 + 0.25 * t3);
399
399
  }
400
400
  if (scaleValue < 0.45) {
401
- const t2 = (scaleValue - 0.3) / 0.15;
402
- return baseChroma * (0.9 + 0.1 * t2);
401
+ const t3 = (scaleValue - 0.3) / 0.15;
402
+ return baseChroma * (0.9 + 0.1 * t3);
403
403
  }
404
404
  if (scaleValue < 0.85) {
405
405
  return baseChroma;
406
406
  }
407
- const t = (scaleValue - 0.85) / 0.15;
408
- return baseChroma * (1 - 0.08 * t);
407
+ const t2 = (scaleValue - 0.85) / 0.15;
408
+ return baseChroma * (1 - 0.08 * t2);
409
409
  }
410
410
  function formatColorShort(color, format) {
411
411
  const full = formatColorAs(color, format);
@@ -553,7 +553,7 @@ function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", opti
553
553
  else if (overrodeAlias && !overrodeSemantic) palette[semantic] = palette[alias];
554
554
  }
555
555
  }
556
- if (options?.aliases === false) for (const [, alias] of ALIAS_PAIRS) delete palette[alias];
556
+ if (options?.aliases !== true) for (const [, alias] of ALIAS_PAIRS) delete palette[alias];
557
557
  return palette;
558
558
  }
559
559
  function getShade(palette, colorName, shade2) {
@@ -790,27 +790,14 @@ function generateSemanticTokens(palette, mode, options, gamuts = { own: "srgb" }
790
790
  });
791
791
  const canvas = pageGrounds[0];
792
792
  const whitePage = mode === "light" && !!canvas && parseToOklch(canvas).l > parseToOklch(neutral[snapShade(25, activeShades)]).l + 5e-3;
793
- const mutedBg = snapShade(mode === "light" ? whitePage ? 50 : 100 : 800, activeShades);
794
- const mutedFg = accessibleStep(
795
- neutral,
796
- mode === "light" ? 500 : 200,
797
- mode,
798
- [neutral[mutedBg]],
799
- contrastTarget === "aaa" ? 7 : 4.5,
800
- activeShades
801
- );
802
- const muted = {
803
- DEFAULT: neutral[mutedBg],
804
- foreground: neutral[mutedFg],
805
- _shades: { DEFAULT: mutedBg, foreground: mutedFg }
806
- };
793
+ const quietPanel = snapShade(mode === "light" ? whitePage ? 50 : 100 : 800, activeShades);
794
+ const neutralOverrides = { subdued: quietPanel, ...shadeOverrides.neutral?.[mode] };
807
795
  const tokens = {
808
796
  primary: createExtendedSemanticColor(primary, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.primary?.[mode], "primary", activeShades, anchor("primary"), gamutsFor("primary"), options?.foreground, options?.wcagFloor, pageGrounds),
809
- neutral: createExtendedSemanticColor(neutral, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.neutral?.[mode], "neutral", activeShades, anchor("neutral"), gamutsFor("neutral"), options?.foreground, options?.wcagFloor, pageGrounds),
797
+ neutral: createExtendedSemanticColor(neutral, neutral, white, black, mode, contrastAlgorithm, contrastTarget, neutralOverrides, "neutral", activeShades, anchor("neutral"), gamutsFor("neutral"), options?.foreground, options?.wcagFloor, pageGrounds),
810
798
  success: createExtendedSemanticColor(success, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.success?.[mode], "success", activeShades, anchor("success"), gamutsFor("success"), options?.foreground, options?.wcagFloor, pageGrounds),
811
799
  destructive: createExtendedSemanticColor(destructive, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.destructive?.[mode], "destructive", activeShades, anchor("destructive"), gamutsFor("destructive"), options?.foreground, options?.wcagFloor, pageGrounds),
812
- warning: createExtendedSemanticColor(warning, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.warning?.[mode], "warning", activeShades, anchor("warning"), gamutsFor("warning"), options?.foreground, options?.wcagFloor, pageGrounds),
813
- muted
800
+ warning: createExtendedSemanticColor(warning, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.warning?.[mode], "warning", activeShades, anchor("warning"), gamutsFor("warning"), options?.foreground, options?.wcagFloor, pageGrounds)
814
801
  };
815
802
  const coreColors = [
816
803
  "black",
@@ -847,6 +834,27 @@ function generateSemanticTokens(palette, mode, options, gamuts = { own: "srgb" }
847
834
  }
848
835
  return tokens;
849
836
  }
837
+ function surfaceStep(name, raw, palette) {
838
+ const m = /^([a-z][a-z0-9-]*)@(\d+)$/.exec(raw.trim());
839
+ if (!m) throw new Error(`Page surface "${name}": expected <ramp>@<step> (got "${raw}")`);
840
+ const shadeNumber = Number(m[2]);
841
+ const scale = palette[m[1]];
842
+ if (!scale || typeof scale === "string") throw new Error(`Page surface "${name}" names no ramp: ${m[1]}`);
843
+ if (!(shadeNumber in scale)) throw new Error(`Page surface "${name}" names no step: ${m[2]}`);
844
+ return { colorName: m[1], shade: shadeNumber };
845
+ }
846
+ function mirrorOf(raw) {
847
+ const m = /^(.*)@(\d+)$/.exec(raw.trim());
848
+ if (!m) return raw;
849
+ const steps = [25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
850
+ const i = steps.indexOf(Number(m[2]));
851
+ return i === -1 ? raw : `${m[1]}@${steps[steps.length - 1 - i]}`;
852
+ }
853
+ function secondaryOn(bg, neutral, floor, active) {
854
+ const dark = parseToOklch(bg).l < 0.6;
855
+ const step = accessibleStep(neutral, snapShade(dark ? 200 : 500, active), dark ? "dark" : "light", [bg], floor, active);
856
+ return { value: neutral[step], ref: { type: "shade", shade: step } };
857
+ }
850
858
  function textOn(bg, neutral, white, black, active) {
851
859
  const light = getContrastRatio(bg, black) > getContrastRatio(bg, white);
852
860
  if (!light) return { value: white, ref: { type: "white" } };
@@ -854,7 +862,7 @@ function textOn(bg, neutral, white, black, active) {
854
862
  if (getContrastRatio(bg, neutral[step]) >= 4.5) return { value: neutral[step], ref: { type: "shade", shade: step } };
855
863
  return { value: black, ref: { type: "black" } };
856
864
  }
857
- function generateSurfaceTokens(palette, mode, overrides, shades, colors, backgrounds) {
865
+ function generateSurfaceTokens(palette, mode, overrides, shades, colors, pageSurfaces, textFloor = 4.5) {
858
866
  const activeShades = shadeKeys(shades);
859
867
  const snap = (shade2) => snapShade(shade2, activeShades);
860
868
  const neutral = palette.neutral;
@@ -864,7 +872,7 @@ function generateSurfaceTokens(palette, mode, overrides, shades, colors, backgro
864
872
  const black = palette.black;
865
873
  const white = palette.white;
866
874
  const defaults = mode === "light" ? { canvas: snap(25), "canvas-foreground": snap(800), surface: "white", "surface-foreground": snap(800), overlay: "white", "overlay-foreground": snap(800) } : { canvas: snap(950), "canvas-foreground": "white", surface: "black", "surface-foreground": "white", overlay: "black", "overlay-foreground": "white" };
867
- function resolve(key) {
875
+ function resolve2(key) {
868
876
  const raw = overrides?.[key] ?? defaults[key];
869
877
  if (raw === "white") return { value: white, ref: { type: "white" } };
870
878
  if (raw === "black") return { value: black, ref: { type: "black" } };
@@ -873,36 +881,54 @@ function generateSurfaceTokens(palette, mode, overrides, shades, colors, backgro
873
881
  }
874
882
  const ground = (key) => {
875
883
  const given = colors?.[key];
876
- if (!given) return { bg: resolve(key), fg: resolve(`${key}-foreground`) };
884
+ if (!given) return { bg: resolve2(key), fg: resolve2(`${key}-foreground`) };
877
885
  const bg = { value: given, ref: { type: "value", value: given } };
878
- return { bg, fg: overrides?.[`${key}-foreground`] ? resolve(`${key}-foreground`) : textOn(given, neutral, white, black, activeShades) };
886
+ return { bg, fg: overrides?.[`${key}-foreground`] ? resolve2(`${key}-foreground`) : textOn(given, neutral, white, black, activeShades) };
879
887
  };
880
888
  const { bg: canvas, fg: canvasFg } = ground("canvas");
881
889
  const { bg: surface, fg: surfaceFg } = ground("surface");
882
890
  const { bg: overlay, fg: overlayFg } = ground("overlay");
883
- const named = {};
884
- for (const name of Object.keys(backgrounds ?? {}).sort()) {
885
- const def = backgrounds[name];
886
- const value = mode === "dark" ? def.dark ?? def.light : def.light;
891
+ const secondary = (key, bg) => {
892
+ const set = overrides?.[`${key}-foreground-secondary`];
893
+ if (set !== void 0) return { value: neutral[snap(set)], ref: { type: "shade", shade: snap(set) } };
894
+ return secondaryOn(bg, neutral, textFloor, activeShades);
895
+ };
896
+ const canvasQuiet = secondary("canvas", canvas.value);
897
+ const surfaceQuiet = secondary("surface", surface.value);
898
+ const overlayQuiet = secondary("overlay", overlay.value);
899
+ const extra = {};
900
+ for (const name of Object.keys(pageSurfaces ?? {}).sort()) {
901
+ const def = pageSurfaces[name];
902
+ const raw = mode === "dark" ? def.dark ?? mirrorOf(def.light) : def.light;
903
+ const at = raw.includes("@") ? surfaceStep(name, raw, palette) : void 0;
904
+ const value = at ? palette[at.colorName][at.shade] : raw;
905
+ const ref = at ? { type: "shade", shade: at.shade, colorName: at.colorName } : { type: "value", value: raw };
887
906
  const fg = textOn(value, neutral, white, black, activeShades);
888
- named[name] = { DEFAULT: value, foreground: fg.value, _refs: { DEFAULT: { type: "value", value }, foreground: fg.ref } };
907
+ const quiet = secondaryOn(value, neutral, textFloor, activeShades);
908
+ extra[name] = { DEFAULT: value, foreground: fg.value, "foreground-secondary": quiet.value, _refs: { DEFAULT: ref, foreground: fg.ref, "foreground-secondary": quiet.ref } };
889
909
  }
890
910
  return {
891
911
  canvas: canvas.value,
892
912
  "canvas-foreground": canvasFg.value,
913
+ "canvas-foreground-secondary": canvasQuiet.value,
893
914
  surface: surface.value,
894
915
  "surface-foreground": surfaceFg.value,
916
+ "surface-foreground-secondary": surfaceQuiet.value,
895
917
  overlay: overlay.value,
896
918
  "overlay-foreground": overlayFg.value,
919
+ "overlay-foreground-secondary": overlayQuiet.value,
897
920
  _refs: {
898
921
  canvas: canvas.ref,
899
922
  "canvas-foreground": canvasFg.ref,
923
+ "canvas-foreground-secondary": canvasQuiet.ref,
900
924
  surface: surface.ref,
901
925
  "surface-foreground": surfaceFg.ref,
926
+ "surface-foreground-secondary": surfaceQuiet.ref,
902
927
  overlay: overlay.ref,
903
- "overlay-foreground": overlayFg.ref
928
+ "overlay-foreground": overlayFg.ref,
929
+ "overlay-foreground-secondary": overlayQuiet.ref
904
930
  },
905
- ...Object.keys(named).length ? { backgrounds: named } : {}
931
+ ...Object.keys(extra).length ? { pageSurfaces: extra } : {}
906
932
  };
907
933
  }
908
934
  function generateUtilityTokens(palette, mode, overrides, shades, seedShade, grounds) {
@@ -935,9 +961,6 @@ function generateUtilityTokens(palette, mode, overrides, shades, seedShade, grou
935
961
  function checkSemanticContrast(tokens, gamut = "srgb") {
936
962
  const results = {};
937
963
  for (const [name, color] of Object.entries(tokens)) {
938
- if (name === "muted") {
939
- continue;
940
- }
941
964
  const extendedColor = color;
942
965
  const ratio = getContrastRatio(
943
966
  extendedColor.DEFAULT,
@@ -960,24 +983,11 @@ function checkSemanticContrast(tokens, gamut = "srgb") {
960
983
  passesAAA: subduedRatio >= 7
961
984
  };
962
985
  }
963
- const mutedRatio = getContrastRatio(
964
- tokens.muted.DEFAULT,
965
- tokens.muted.foreground,
966
- gamut
967
- );
968
- results["muted"] = {
969
- ratio: Math.round(mutedRatio * 100) / 100,
970
- passesAA: meetsWCAG_AA(mutedRatio),
971
- passesAAA: mutedRatio >= 7
972
- };
973
986
  return results;
974
987
  }
975
988
  function checkSemanticContrastAPCA(tokens, gamut = "srgb") {
976
989
  const results = {};
977
990
  for (const [name, color] of Object.entries(tokens)) {
978
- if (name === "muted") {
979
- continue;
980
- }
981
991
  const ext = color;
982
992
  const defaultLc = getAPCAContrast(ext.foreground, ext.DEFAULT, gamut);
983
993
  results[`${name}/default`] = {
@@ -990,11 +1000,6 @@ function checkSemanticContrastAPCA(tokens, gamut = "srgb") {
990
1000
  level: classifyAPCALevel(subduedLc)
991
1001
  };
992
1002
  }
993
- const mutedLc = getAPCAContrast(tokens.muted.foreground, tokens.muted.DEFAULT, gamut);
994
- results["muted"] = {
995
- lcValue: Math.round(mutedLc * 10) / 10,
996
- level: classifyAPCALevel(mutedLc)
997
- };
998
1003
  return results;
999
1004
  }
1000
1005
  var NON_TEXT_CONTRAST_MIN = 3;
@@ -1014,6 +1019,9 @@ function checkSurfaceContrast(surface, utility, gamut = "srgb") {
1014
1019
  "canvas/foreground": pair(surface.canvas, surface["canvas-foreground"]),
1015
1020
  "surface/foreground": pair(surface.surface, surface["surface-foreground"]),
1016
1021
  "overlay/foreground": pair(surface.overlay, surface["overlay-foreground"]),
1022
+ "canvas/foreground-secondary": pair(surface.canvas, surface["canvas-foreground-secondary"]),
1023
+ "surface/foreground-secondary": pair(surface.surface, surface["surface-foreground-secondary"]),
1024
+ "overlay/foreground-secondary": pair(surface.overlay, surface["overlay-foreground-secondary"]),
1017
1025
  "ring/canvas": pair(surface.canvas, utility.ring, true),
1018
1026
  "border/canvas": pair(surface.canvas, utility.border, true, true)
1019
1027
  };
@@ -1042,7 +1050,7 @@ function checkRampChroma(palette) {
1042
1050
  }
1043
1051
  function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa", gamut = "srgb") {
1044
1052
  const { floor } = getContrastThresholds(algorithm, contrastTarget);
1045
- const skipKeys = /* @__PURE__ */ new Set(["muted"]);
1053
+ const skipKeys = /* @__PURE__ */ new Set();
1046
1054
  let passed = 0;
1047
1055
  let total = 0;
1048
1056
  if (algorithm === "wcag") {
@@ -1071,46 +1079,44 @@ function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa", gam
1071
1079
  }
1072
1080
 
1073
1081
  // src/grounds.ts
1074
- var STATUS_GROUNDS = ["success", "warning", "destructive"];
1075
- var GROUND_BASE_TOKENS = ["canvas", "canvas-foreground", "muted", "muted-foreground", "border", "input", "ring"];
1082
+ var GROUND_BASE_TOKENS = [
1083
+ "canvas",
1084
+ "canvas-foreground",
1085
+ "canvas-foreground-secondary",
1086
+ "border",
1087
+ "input",
1088
+ "ring",
1089
+ "surface",
1090
+ "surface-foreground",
1091
+ "surface-foreground-secondary"
1092
+ ];
1076
1093
  var GROUND_COLOR_PARTS = ["", "-foreground", "-subdued", "-subdued-foreground", "-hover", "-active"];
1077
1094
  var FILL_FLOOR = 3;
1078
1095
  var PANEL_FLOOR = 1.1;
1079
1096
  var TEXT_FLOOR = { "aa-large": 3, aa: 4.5, aaa: 7 };
1097
+ var BODY_AIM = 7;
1080
1098
  function groundTokenNames(colors) {
1081
1099
  return [...GROUND_BASE_TOKENS, ...colors.flatMap((c) => GROUND_COLOR_PARTS.map((p) => `${c}${p}`))];
1082
1100
  }
1083
1101
  function semanticColors(semantic) {
1084
1102
  const core = ["primary", "neutral", "success", "destructive", "warning"];
1085
- return [...core, ...Object.keys(semantic).filter((n) => !core.includes(n) && n !== "muted")];
1103
+ return [...core, ...Object.keys(semantic).filter((n) => !core.includes(n))];
1086
1104
  }
1087
- function reservedGroundNames(colors) {
1105
+ function reservedSurfaceNames(colors) {
1088
1106
  return [
1089
1107
  "canvas",
1090
1108
  "surface",
1091
1109
  "overlay",
1092
1110
  "foreground",
1093
- "muted",
1094
1111
  "border",
1095
1112
  "input",
1096
1113
  "ring",
1097
1114
  "shadow",
1115
+ "white",
1116
+ "black",
1098
1117
  ...colors.flatMap((c) => [c, `${c}-subdued`])
1099
1118
  ];
1100
1119
  }
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
1120
  var valueOf = (ref, palette) => {
1115
1121
  switch (ref.type) {
1116
1122
  case "white":
@@ -1132,24 +1138,25 @@ function fromSurfaceRef(ref) {
1132
1138
  case "black":
1133
1139
  return { type: "black" };
1134
1140
  case "shade":
1135
- return shade("neutral", ref.shade);
1141
+ return shade(ref.colorName ?? "neutral", ref.shade);
1136
1142
  case "value":
1137
1143
  return { type: "value", value: ref.value };
1138
1144
  }
1139
1145
  }
1140
- function baseRefs(base, colors, ground, active) {
1146
+ function baseRefs(base, colors, active) {
1141
1147
  const { semantic, surface, utility } = base;
1142
1148
  const refs = {};
1143
1149
  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));
1150
+ refs.canvas = fromSurfaceRef(sr.canvas);
1151
+ refs["canvas-foreground"] = fromSurfaceRef(sr["canvas-foreground"]);
1152
+ refs["canvas-foreground-secondary"] = fromSurfaceRef(sr["canvas-foreground-secondary"]);
1149
1153
  const steps = utility._steps;
1150
1154
  refs.border = shade("neutral", steps.border);
1151
1155
  refs.input = shade("neutral", steps.input);
1152
1156
  refs.ring = shade("primary", steps.ring);
1157
+ refs.surface = fromSurfaceRef(sr.surface);
1158
+ refs["surface-foreground"] = fromSurfaceRef(sr["surface-foreground"]);
1159
+ refs["surface-foreground-secondary"] = fromSurfaceRef(sr["surface-foreground-secondary"]);
1153
1160
  for (const name of colors) {
1154
1161
  const c = semantic[name];
1155
1162
  refs[name] = shade(name, c._shades.DEFAULT);
@@ -1161,30 +1168,65 @@ function baseRefs(base, colors, ground, active) {
1161
1168
  }
1162
1169
  return refs;
1163
1170
  }
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);
1171
+ function suggestStep(color, options) {
1172
+ const o = parseToOklch(color);
1173
+ const reference = generateColorScale(oklchToHex({ mode: "oklch", l: 0.6, c: Math.max(o.c ?? 0, 0.01), h: o.h ?? 0 }), {
1174
+ lightEnd: options?.lightnessRange?.light,
1175
+ darkEnd: options?.lightnessRange?.dark
1176
+ });
1177
+ let best = 500;
1178
+ let distance = Infinity;
1179
+ for (const step of VALID_SHADES) {
1180
+ const d = Math.abs(parseToOklch(reference[step]).l - o.l);
1176
1181
  if (d < distance) {
1177
1182
  distance = d;
1178
- best = name;
1183
+ best = step;
1179
1184
  }
1180
1185
  }
1181
1186
  return best;
1182
1187
  }
1188
+ function rampRefs(ramp, step, light, palette, active) {
1189
+ const fill = shade(ramp, snapShade(step, active));
1190
+ const fillValue = valueOf(fill, palette);
1191
+ const label = getContrastRatio(fillValue, palette.white) >= getContrastRatio(fillValue, palette.black) ? { type: "white" } : { type: "black" };
1192
+ return {
1193
+ [ramp]: fill,
1194
+ [`${ramp}-foreground`]: label,
1195
+ [`${ramp}-hover`]: { type: "value", value: fillValue },
1196
+ [`${ramp}-active`]: { type: "value", value: fillValue },
1197
+ [`${ramp}-subdued`]: shade(ramp, snapShade(light ? 100 : 900, active)),
1198
+ [`${ramp}-subdued-foreground`]: shade(ramp, snapShade(light ? 700 : 300, active))
1199
+ };
1200
+ }
1201
+ function fillRef(fill, palette) {
1202
+ if (fill === "white") return { type: "white" };
1203
+ if (fill === "black") return { type: "black" };
1204
+ const m = /^([a-z][a-z0-9-]*)-(\d+)$/.exec(fill);
1205
+ if (!m) throw new Error(`"${fill}" is not page, own, white, black or a step (<ramp>-<step>)`);
1206
+ const step = Number(m[2]);
1207
+ const scale = palette[m[1]];
1208
+ if (!scale || typeof scale === "string") throw new Error(`"${fill}" names no ramp: ${m[1]}`);
1209
+ if (!VALID_SHADES.includes(step)) throw new Error(`"${fill}" names no step: ${m[2]}`);
1210
+ return shade(m[1], step);
1211
+ }
1212
+ function statesFor(fill, label, palette, active) {
1213
+ if (fill.type === "white") return [shade("neutral", snapShade(50, active)), shade("neutral", snapShade(100, active))];
1214
+ if (fill.type === "black") return [shade("neutral", snapShade(900, active)), shade("neutral", snapShade(800, active))];
1215
+ if (fill.type !== "shade") return [fill, fill];
1216
+ const scale = palette[fill.colorName];
1217
+ const steps = active.filter((s) => scale[s] !== void 0);
1218
+ const at = steps.indexOf(fill.shade);
1219
+ const towards = parseToOklch(valueOf(label, palette)).l > parseToOklch(scale[fill.shade]).l ? -1 : 1;
1220
+ const pick = (n) => {
1221
+ const i = at + towards * n;
1222
+ return shade(fill.colorName, steps[i >= 0 && i < steps.length ? i : Math.max(0, Math.min(steps.length - 1, at - towards * n))]);
1223
+ };
1224
+ return [pick(1), pick(2)];
1225
+ }
1183
1226
  function searchGround(spec, base, baseCanvas, colors, views, mode, options, active) {
1184
1227
  const target = options?.contrastTarget ?? "aa";
1185
1228
  const algorithm = options?.contrastAlgorithm ?? "wcag";
1186
1229
  const textFloor = TEXT_FLOOR[target];
1187
- const mutedFloor = target === "aaa" ? 7 : 4.5;
1188
1230
  const srgb = views[0].palette;
1189
1231
  const notes = [];
1190
1232
  const cr = (a, b) => Math.min(...views.map((v) => getContrastRatio(valueOf(a, v.palette), valueOf(b, v.palette), v.gamut)));
@@ -1199,8 +1241,7 @@ function searchGround(spec, base, baseCanvas, colors, views, mode, options, acti
1199
1241
  const tinted = spec.family !== "neutral";
1200
1242
  const own = steps(spec.family).filter(farSide);
1201
1243
  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];
1244
+ const closest = (list, to, aim) => [...list].sort((a, b) => Math.abs(cr(a, to) - aim) - Math.abs(cr(b, to) - aim))[0];
1204
1245
  const panelCandidates = (list, vis) => {
1205
1246
  const drawn = list.filter((r) => cr(r, ground) >= PANEL_FLOOR);
1206
1247
  const byVis = (a, b) => Math.abs(cr(a, ground) - vis) - Math.abs(cr(b, ground) - vis);
@@ -1218,49 +1259,28 @@ function searchGround(spec, base, baseCanvas, colors, views, mode, options, acti
1218
1259
  const refs = {};
1219
1260
  refs.canvas = ground;
1220
1261
  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
1262
  const borderVis = cr(base.border, baseCanvas);
1244
1263
  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;
1264
+ const ownRamp = tinted;
1265
+ const farBorder = ownRamp ? closest(steps(spec.family).filter((r) => farSide(r) && borderReads(r) && cr(r, ground) <= borderVis * 2), ground, borderVis) : void 0;
1266
+ refs.border = keepsPlace(base.border) && cr(base.border, ground) >= borderVis * 0.9 && cr(base.border, ground) <= borderVis * 2 ? base.border : farBorder ?? closest([...pool, ...steps(spec.family)].filter(borderReads), ground, borderVis) ?? base.border;
1246
1267
  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
1268
  const ringFamily = tinted ? spec.family : "primary";
1248
1269
  const ringFrom = tinted ? base[spec.family].shade : base.ring.shade;
1249
1270
  refs.ring = inHue(base.ring) && cr(base.ring, ground) >= FILL_FLOOR ? base.ring : nearest(ringFamily, ringFrom, ground, FILL_FLOOR) ?? bestEnd(ground);
1250
1271
  for (const name of colors) {
1251
1272
  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];
1273
+ const pageFill = base[src];
1274
+ const fillShade = pageFill.shade;
1255
1275
  const neutralIn = (v) => v.palette.neutral;
1256
- const labelOn = (bg, role2, pageGrounds = []) => {
1276
+ const labelOn = (bg, role2, pageGrounds = [], from = src) => {
1257
1277
  const found = findBestForeground(
1258
- views.map((v) => ({ background: valueOf(bg, v.palette), scale: scaleIn(v), neutral: neutralIn(v), gamut: v.gamut })),
1278
+ views.map((v) => ({ background: valueOf(bg, v.palette), scale: v.palette[from], neutral: neutralIn(v), gamut: v.gamut })),
1259
1279
  srgb.white,
1260
1280
  srgb.black,
1261
1281
  algorithm,
1262
1282
  target,
1263
- src,
1283
+ from,
1264
1284
  active,
1265
1285
  role2,
1266
1286
  options?.foreground ?? "balanced",
@@ -1275,20 +1295,45 @@ function searchGround(spec, base, baseCanvas, colors, views, mode, options, acti
1275
1295
  refs[`${name}-hover`] = { type: "value", value: stateOf(f, l, HOVER_SHIFT, views[0].gamut) };
1276
1296
  refs[`${name}-active`] = { type: "value", value: stateOf(f, l, ACTIVE_SHIFT, views[0].gamut) };
1277
1297
  };
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);
1298
+ const action = name === "primary" ? spec.action : void 0;
1299
+ if (action === "page") {
1300
+ refs[name] = base[name];
1301
+ refs[`${name}-foreground`] = base[`${name}-foreground`];
1302
+ refs[`${name}-hover`] = base[`${name}-hover`];
1303
+ refs[`${name}-active`] = base[`${name}-active`];
1304
+ if (cr(base[name], ground) < FILL_FLOOR) notes.push(`${name}: the page's, ${cr(base[name], ground).toFixed(2)}:1 against the ground (action page), carried by its label`);
1305
+ } else if (action === "own") {
1306
+ const own2 = base[spec.ramp];
1307
+ const ramp = steps(spec.ramp);
1308
+ const fill = cr(own2, ground) >= FILL_FLOOR ? own2 : light ? ramp[ramp.length - 1] : ramp[0];
1309
+ const label = sameRef(fill, own2) ? base[`${spec.ramp}-foreground`] : labelOn(fill, "tint", [], spec.ramp);
1310
+ refs[name] = fill;
1311
+ refs[`${name}-foreground`] = label;
1312
+ setStates(fill, label);
1313
+ if (cr(fill, ground) < FILL_FLOOR) notes.push(`${name}: no step of ${spec.ramp} stands out from the ground at ${FILL_FLOOR}:1 (action own)`);
1314
+ } else if (action) {
1315
+ const [fillName, labelName] = action.split("/");
1316
+ const fill = fillRef(fillName, srgb);
1317
+ const label = labelName ? fillRef(labelName, srgb) : labelOn(fill, "fill");
1318
+ refs[name] = fill;
1319
+ refs[`${name}-foreground`] = label;
1320
+ setStates(fill, label);
1321
+ if (cr(fill, ground) < FILL_FLOOR) notes.push(`${name}: ${fillName} is ${cr(fill, ground).toFixed(2)}:1 against the ground, under ${FILL_FLOOR}:1`);
1322
+ if (cr(label, fill) < textFloor) notes.push(`${name}-foreground: ${labelName ?? "the label"} is ${cr(label, fill).toFixed(2)}:1 on ${fillName}, under ${textFloor}:1`);
1323
+ } else if (tinted && name === "neutral") {
1324
+ const tonal = panelCandidates(steps(src), 1.6).map((fill2) => ({ fill: fill2, label: labelOn(fill2, "tint") })).find((t2) => cr(t2.label, t2.fill) >= textFloor);
1280
1325
  const fill = tonal?.fill ?? steps(src).filter(farSide)[0] ?? bestEnd(ground);
1281
1326
  const label = tonal?.label ?? labelOn(fill, "fill");
1282
1327
  refs[name] = fill;
1283
1328
  refs[`${name}-foreground`] = label;
1284
1329
  setStates(fill, label);
1285
- } else if (inHue(fillRef) && cr(fillRef, ground) >= FILL_FLOOR) {
1286
- refs[name] = fillRef;
1330
+ } else if (inHue(pageFill) && cr(pageFill, ground) >= FILL_FLOOR) {
1331
+ refs[name] = pageFill;
1287
1332
  refs[`${name}-foreground`] = base[`${src}-foreground`];
1288
1333
  refs[`${name}-hover`] = base[`${src}-hover`];
1289
1334
  refs[`${name}-active`] = base[`${src}-active`];
1290
1335
  } else {
1291
- const turnsOver = spec.kind === "background" && spec.family === src && src !== "neutral";
1336
+ const turnsOver = spec.family === src && src !== "neutral";
1292
1337
  const ramp = steps(src);
1293
1338
  const fill = turnsOver ? light ? ramp[ramp.length - 1] : ramp[0] : nearest(src, fillShade, ground, FILL_FLOOR) ?? bestEnd(ground);
1294
1339
  const label = turnsOver ? labelOn(fill, "tint") : labelOn(fill, "fill");
@@ -1322,64 +1367,141 @@ function searchGround(spec, base, baseCanvas, colors, views, mode, options, acti
1322
1367
  refs[`${name}-subdued`] = pair.tint;
1323
1368
  refs[`${name}-subdued-foreground`] = pair.label;
1324
1369
  }
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 };
1370
+ return { refs, notes };
1327
1371
  }
1328
- function generateGroundTokens(tiers, mode, views, options) {
1329
- const base = { semantic: tiers.semantic[mode], surface: tiers.surface[mode], utility: tiers.utility[mode] };
1372
+ function buildGround(name, given, tiers, views, options) {
1330
1373
  const active = resolveShades(options?.shades);
1331
1374
  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
- });
1375
+ const target = options?.contrastTarget ?? "aa";
1376
+ const textFloor = TEXT_FLOOR[target];
1377
+ const secondaryFloor = target === "aaa" ? 7 : 4.5;
1378
+ const scale = srgb[given.ramp];
1379
+ if (!scale || typeof scale === "string") throw new Error(`Ground "${name}" names no ramp: ${given.ramp} (add it with --color)`);
1380
+ if (!VALID_SHADES.includes(given.step)) throw new Error(`Ground "${name}" names no step: ${given.step}`);
1381
+ const step = snapShade(given.step, active);
1382
+ const ground = shade(given.ramp, step);
1383
+ const cr = (a, b) => Math.min(...views.map((v) => getContrastRatio(valueOf(a, v.palette), valueOf(b, v.palette), v.gamut)));
1384
+ const light = cr(ground, { type: "black" }) > cr(ground, { type: "white" });
1385
+ const polarity = light ? "light" : "dark";
1386
+ const tint = given.tint ?? options?.groundTint ?? "own";
1387
+ const text = given.text ?? options?.groundText ?? "page";
1388
+ const action = given.action ?? options?.groundAction;
1389
+ const notes = [];
1390
+ const bestEnd = (on) => cr({ type: "white" }, on) >= cr({ type: "black" }, on) ? { type: "white" } : { type: "black" };
1391
+ const tier = { semantic: tiers.semantic[polarity], surface: tiers.surface[polarity], utility: tiers.utility[polarity] };
1392
+ const colors = semanticColors(tier.semantic);
1393
+ const page = baseRefs(tier, colors, active);
1394
+ const base = colors.includes(given.ramp) ? page : { ...page, ...rampRefs(given.ramp, step, light, srgb, active) };
1395
+ const rampSteps = active.filter((s) => scale[s] !== void 0).map((s) => shade(given.ramp, s));
1396
+ let body;
1397
+ if (text === "page") {
1398
+ body = cr(page["canvas-foreground"], ground) >= textFloor ? page["canvas-foreground"] : bestEnd(ground);
1399
+ } else if (text === "own") {
1400
+ const reads = rampSteps.filter((r) => cr(r, ground) >= BODY_AIM);
1401
+ body = reads.sort((a, b) => cr(a, ground) - cr(b, ground))[0] ?? rampSteps.filter((r) => cr(r, ground) >= textFloor).sort((a, b) => cr(b, ground) - cr(a, ground))[0] ?? bestEnd(ground);
1402
+ } else {
1403
+ body = fillRef(text, srgb);
1404
+ }
1405
+ if (cr(body, ground) < textFloor) notes.push(`canvas-foreground: ${cr(body, ground).toFixed(2)}:1, under ${textFloor}:1`);
1406
+ const searched = searchGround(
1407
+ { name, canvas: ground, foreground: body, family: tint === "page" ? "neutral" : given.ramp, textFamily: text === "own" ? given.ramp : "neutral", ramp: given.ramp, ...action ? { action } : {} },
1408
+ base,
1409
+ page.canvas,
1410
+ colors,
1411
+ views,
1412
+ polarity,
1413
+ options,
1414
+ active
1415
+ );
1416
+ const refs = searched.refs;
1417
+ notes.push(...searched.notes);
1418
+ if (tint === "page") {
1419
+ for (const token of ["neutral-subdued", "neutral-subdued-foreground", "border", "input", "ring"]) refs[token] = page[token];
1420
+ } else if (tint !== "own") {
1421
+ const one = fillRef(tint, srgb);
1422
+ refs.border = one;
1423
+ refs.input = one;
1424
+ refs.ring = one;
1425
+ }
1426
+ if (tint !== "own") {
1427
+ for (const token of ["input", "ring"]) {
1428
+ if (cr(refs[token], ground) < FILL_FLOOR) notes.push(`${token}: ${cr(refs[token], ground).toFixed(2)}:1, under ${FILL_FLOOR}:1`);
1429
+ }
1354
1430
  }
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
- });
1431
+ const pageCardVis = Math.max(cr(page.surface, page.canvas), PANEL_FLOOR);
1432
+ if (tint !== "page") {
1433
+ const groundL = parseToOklch(valueOf(ground, srgb)).l;
1434
+ const lighter = (r) => parseToOklch(valueOf(r, srgb)).l > groundL;
1435
+ const cards = rampSteps.filter((r) => cr(r, ground) >= PANEL_FLOOR);
1436
+ const byVis = (a, b) => Math.abs(cr(a, ground) - pageCardVis) - Math.abs(cr(b, ground) - pageCardVis);
1437
+ refs.surface = [...cards.filter(lighter).sort(byVis), ...cards.filter((r) => !lighter(r)).sort(byVis)][0] ?? page.surface;
1438
+ } else {
1439
+ refs.surface = page.surface;
1363
1440
  }
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]]));
1441
+ refs.canvas = ground;
1442
+ refs["canvas-foreground"] = body;
1443
+ refs["surface-foreground"] = cr(body, refs.surface) >= textFloor ? body : bestEnd(refs.surface);
1444
+ const textPool = text === "own" ? rampSteps : active.map((s) => shade("neutral", s));
1445
+ const secondary = (key, on) => {
1446
+ const token = `${key}-foreground-secondary`;
1447
+ const bodyOn = refs[`${key}-foreground`];
1448
+ if (text !== "page" && text !== "own") {
1449
+ refs[token] = bodyOn;
1450
+ notes.push(`${token}: one colour (${text}) for all text, so secondary text is no quieter than body text`);
1451
+ return;
1370
1452
  }
1453
+ const bodyContrast = cr(bodyOn, on);
1454
+ const reads = (r) => cr(r, on) >= secondaryFloor && cr(r, on) < bodyContrast;
1455
+ const aim = Math.max(secondaryFloor, Math.min(7, bodyContrast * 0.65));
1456
+ const kept = text === "page" && reads(page[token]) ? page[token] : void 0;
1457
+ const found = kept ?? textPool.filter(reads).sort((a, b) => Math.abs(cr(a, on) - aim) - Math.abs(cr(b, on) - aim))[0];
1458
+ if (found) refs[token] = found;
1459
+ else {
1460
+ refs[token] = bodyOn;
1461
+ notes.push(`${token}: nothing quieter than the body text reads at ${secondaryFloor}:1, so it is the body colour`);
1462
+ }
1463
+ };
1464
+ secondary("canvas", ground);
1465
+ secondary("surface", refs.surface);
1466
+ for (const c of colors) {
1467
+ if (sameRef(refs[c], page[c]) && sameRef(refs[`${c}-foreground`], page[`${c}-foreground`])) {
1468
+ refs[`${c}-hover`] = page[`${c}-hover`];
1469
+ refs[`${c}-active`] = page[`${c}-active`];
1470
+ continue;
1471
+ }
1472
+ [refs[`${c}-hover`], refs[`${c}-active`]] = statesFor(refs[c], refs[`${c}-foreground`], srgb, active);
1371
1473
  }
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;
1474
+ const order = groundTokenNames(colors);
1475
+ const _refs = Object.fromEntries(order.map((k) => [k, refs[k] ?? page[k]]));
1476
+ return {
1477
+ ramp: given.ramp,
1478
+ step,
1479
+ polarity,
1480
+ tint,
1481
+ text,
1482
+ ...action ? { action } : {},
1483
+ tokens: Object.fromEntries(order.map((k) => [k, valueOf(_refs[k], srgb)])),
1484
+ _refs,
1485
+ // the ground itself always; the rest where they differ from the page of the ground's polarity
1486
+ own: order.filter((k) => k === "canvas" || !sameRef(_refs[k], page[k])),
1487
+ notes
1488
+ };
1489
+ }
1490
+ function assertGroundsShape(options) {
1491
+ if (typeof options?.grounds === "string") {
1492
+ throw new Error(`grounds: "${options.grounds}" is 0.11's setting. From 0.12 grounds are declared one by one, { pine: { ramp: "pine", step: 800 } }; "text" is groundTint: "page"`);
1493
+ }
1494
+ if (options && "backgrounds" in options) {
1495
+ throw new Error("backgrounds is gone from 0.12: a section that changes with the mode is a page surface (pageSurfaces); one painted the same in both is a ground on a ramp (grounds)");
1496
+ }
1497
+ }
1498
+ function generateGroundTokens(tiers, views, options) {
1499
+ const out = {};
1500
+ assertGroundsShape(options);
1501
+ for (const name of Object.keys(options?.grounds ?? {}).sort()) {
1502
+ if (name === "canvas") throw new Error(`A ground can't be called "canvas": data-surface="canvas" resets to the page`);
1503
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error(`Ground name must be lower-case kebab-case (got "${name}")`);
1504
+ out[name] = buildGround(name, options.grounds[name], tiers, views, options);
1383
1505
  }
1384
1506
  return out;
1385
1507
  }
@@ -1471,16 +1593,16 @@ function generateTokens(brandColors, options) {
1471
1593
  hueDrift: options?.hueDrift,
1472
1594
  families: options?.families,
1473
1595
  familyPins: options?.pins,
1474
- aliases: options?.aliases
1596
+ // green, red and yellow beside success, destructive and warning only when asked (from 0.12)
1597
+ aliases: options?.aliases ?? false
1475
1598
  };
1476
1599
  const primitives = generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "srgb" });
1477
1600
  const wide = options?.gamut === "p3" ? generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "p3" }) : void 0;
1478
1601
  const grounds = (palette, mode) => {
1479
- const surface = generateSurfaceTokens(palette, mode, options?.surfaceShadeOverrides?.[mode], options?.shades, options?.surfaceColors?.[mode], options?.backgrounds);
1602
+ const surface = generateSurfaceTokens(palette, mode, options?.surfaceShadeOverrides?.[mode], options?.shades, options?.surfaceColors?.[mode], options?.pageSurfaces, textFloorOf(options));
1480
1603
  const light = (c) => getContrastRatio(c, "#000000") > getContrastRatio(c, "#ffffff");
1481
- const pageIsLight = light(surface.canvas);
1482
- const named = Object.values(surface.backgrounds ?? {}).map((b) => b.DEFAULT).filter((c) => light(c) === pageIsLight);
1483
- return [surface.canvas, surface.surface, surface.overlay, ...named];
1604
+ const same = Object.values(surface.pageSurfaces ?? {}).map((b) => b.DEFAULT).filter((c) => light(c) === light(surface.canvas));
1605
+ return [surface.canvas, surface.surface, surface.overlay, ...same];
1484
1606
  };
1485
1607
  const colourTiers = (palette, gamuts) => ({
1486
1608
  primitives: palette,
@@ -1489,8 +1611,8 @@ function generateTokens(brandColors, options) {
1489
1611
  dark: generateSemanticTokens(palette, "dark", options, gamuts, grounds(palette, "dark"))
1490
1612
  },
1491
1613
  surface: {
1492
- light: generateSurfaceTokens(palette, "light", options?.surfaceShadeOverrides?.light, options?.shades, options?.surfaceColors?.light, options?.backgrounds),
1493
- dark: generateSurfaceTokens(palette, "dark", options?.surfaceShadeOverrides?.dark, options?.shades, options?.surfaceColors?.dark, options?.backgrounds)
1614
+ light: generateSurfaceTokens(palette, "light", options?.surfaceShadeOverrides?.light, options?.shades, options?.surfaceColors?.light, options?.pageSurfaces, textFloorOf(options)),
1615
+ dark: generateSurfaceTokens(palette, "dark", options?.surfaceShadeOverrides?.dark, options?.shades, options?.surfaceColors?.dark, options?.pageSurfaces, textFloorOf(options))
1494
1616
  },
1495
1617
  utility: {
1496
1618
  light: generateUtilityTokens(palette, "light", options?.utilityShadeOverrides?.light, options?.shades, options?.seedShade, grounds(palette, "light")),
@@ -1501,21 +1623,20 @@ function generateTokens(brandColors, options) {
1501
1623
  own: "srgb",
1502
1624
  ...wide ? { other: { gamut: "p3", palette: wide } } : {}
1503
1625
  });
1504
- const withGrounds = options?.grounds !== "none";
1505
1626
  const colors = semanticColors(tiers.semantic.light);
1506
- const reserved = reservedGroundNames(colors);
1507
- for (const name of withGrounds ? Object.keys(options?.backgrounds ?? {}) : []) {
1627
+ const reserved = reservedSurfaceNames(colors);
1628
+ for (const name of Object.keys(options?.pageSurfaces ?? {})) {
1508
1629
  if (reserved.includes(name)) {
1509
- throw new Error(`Background name "${name}" is taken: it is already a token or a ground. Reserved: ${reserved.join(", ")}`);
1630
+ throw new Error(`Page surface name "${name}" is taken: it is already a token. Reserved: ${reserved.join(", ")}`);
1510
1631
  }
1511
1632
  }
1512
1633
  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);
1634
+ assertGroundsShape(options);
1635
+ const groundTokens = Object.keys(options?.grounds ?? {}).length ? generateGroundTokens(tiers, views, options) : void 0;
1515
1636
  return {
1516
1637
  ...tiers,
1517
1638
  ...groundTokens ? { grounds: groundTokens } : {},
1518
- pageContrast: { light: pageContrast(tiers, "light"), dark: pageContrast(tiers, "dark") },
1639
+ pageContrast: { light: pageContrast(tiers, "light", groundTokens), dark: pageContrast(tiers, "dark", groundTokens) },
1519
1640
  spacing: {},
1520
1641
  typography: defaultTypography,
1521
1642
  radii: defaultRadii,
@@ -1523,14 +1644,17 @@ function generateTokens(brandColors, options) {
1523
1644
  ...wide ? { p3: colourTiers(wide, { own: "p3", other: { gamut: "srgb", palette: primitives } }) } : {}
1524
1645
  };
1525
1646
  }
1526
- function pageContrast(tiers, mode) {
1647
+ function textFloorOf(options) {
1648
+ return options?.contrastTarget === "aaa" ? 7 : 4.5;
1649
+ }
1650
+ function pageContrast(tiers, mode, groundTokens) {
1527
1651
  const surface = tiers.surface[mode];
1528
1652
  const grounds = { canvas: surface.canvas, surface: surface.surface, overlay: surface.overlay };
1529
- for (const [name, bg] of Object.entries(surface.backgrounds ?? {})) grounds[`surface-${name}`] = bg.DEFAULT;
1653
+ for (const [name, bg] of Object.entries(surface.pageSurfaces ?? {})) grounds[name] = bg.DEFAULT;
1654
+ for (const [name, g] of Object.entries(groundTokens ?? {})) grounds[`ground-${name}`] = g.tokens.canvas;
1530
1655
  const colours = {};
1531
- for (const [name, colour] of Object.entries(tiers.semantic[mode])) {
1532
- colours[name === "muted" ? "muted-foreground" : name] = name === "muted" ? colour.foreground : colour.DEFAULT;
1533
- }
1656
+ for (const [name, colour] of Object.entries(tiers.semantic[mode])) colours[name] = colour.DEFAULT;
1657
+ for (const key of ["canvas", "surface", "overlay"]) colours[`${key}-foreground-secondary`] = surface[`${key}-foreground-secondary`];
1534
1658
  const out = {};
1535
1659
  for (const name of Object.keys(colours).sort()) {
1536
1660
  out[name] = {};
@@ -1549,13 +1673,11 @@ function usageReport(tokens, target = "aa") {
1549
1673
  const mode = (m) => {
1550
1674
  const surface = tokens.surface[m];
1551
1675
  const grounds = { canvas: surface.canvas, surface: surface.surface, overlay: surface.overlay };
1552
- for (const [name, bg] of Object.entries(surface.backgrounds ?? {})) grounds[`surface-${name}`] = bg.DEFAULT;
1676
+ for (const [name, page] of Object.entries(surface.pageSurfaces ?? {})) grounds[name] = page.DEFAULT;
1677
+ for (const [name, g] of Object.entries(tokens.grounds ?? {})) grounds[`ground-${name}`] = g.tokens.canvas;
1553
1678
  const colours = {};
1679
+ for (const key of ["canvas", "surface", "overlay"]) colours[`${key}-foreground-secondary`] = surface[`${key}-foreground-secondary`];
1554
1680
  for (const [name, colour] of Object.entries(tokens.semantic[m])) {
1555
- if (name === "muted") {
1556
- colours["muted-foreground"] = colour.foreground;
1557
- continue;
1558
- }
1559
1681
  colours[name] = colour.DEFAULT;
1560
1682
  colours[`${name}-subdued-foreground`] = colour["subdued-foreground"];
1561
1683
  }
@@ -1622,10 +1744,6 @@ function getExtendedMappings(mode, colorName, overrides, active, anchors) {
1622
1744
  const seedShade = familySeedShade(colorName, anchors.seedShade, anchors.seedShades);
1623
1745
  return extendedBridgeShades(mode, seedShade, active, overrides?.[colorName]?.[mode]);
1624
1746
  }
1625
- var MUTED_SHADE_MAPPINGS = {
1626
- light: { DEFAULT: 100, foreground: 500 },
1627
- dark: { DEFAULT: 800, foreground: 200 }
1628
- };
1629
1747
  var UTILITY_SHADE_MAPPINGS = {
1630
1748
  light: {
1631
1749
  border: "neutral-200",
@@ -1658,7 +1776,7 @@ function surfaceRefToVar(ref, colorFormat) {
1658
1776
  case "black":
1659
1777
  return "var(--color-black)";
1660
1778
  case "shade":
1661
- return `var(--color-neutral-${ref.shade})`;
1779
+ return `var(--color-${ref.colorName ?? "neutral"}-${ref.shade})`;
1662
1780
  // a background passed in as a colour is not on any ramp, so it is written as it is
1663
1781
  case "value":
1664
1782
  return formatColor(ref.value, colorFormat);
@@ -1666,7 +1784,17 @@ function surfaceRefToVar(ref, colorFormat) {
1666
1784
  }
1667
1785
  function emitSurfaceVars(surface, colorFormat, indent) {
1668
1786
  const lines = [];
1669
- const keys = ["canvas", "canvas-foreground", "surface", "surface-foreground", "overlay", "overlay-foreground"];
1787
+ const keys = [
1788
+ "canvas",
1789
+ "canvas-foreground",
1790
+ "canvas-foreground-secondary",
1791
+ "surface",
1792
+ "surface-foreground",
1793
+ "surface-foreground-secondary",
1794
+ "overlay",
1795
+ "overlay-foreground",
1796
+ "overlay-foreground-secondary"
1797
+ ];
1670
1798
  for (const key of keys) {
1671
1799
  if (surface._refs) {
1672
1800
  lines.push(`${indent}--${key}: ${surfaceRefToVar(surface._refs[key], colorFormat)};`);
@@ -1674,9 +1802,10 @@ function emitSurfaceVars(surface, colorFormat, indent) {
1674
1802
  lines.push(`${indent}--${key}: ${formatColor(surface[key], colorFormat)};`);
1675
1803
  }
1676
1804
  }
1677
- for (const [name, bg] of Object.entries(surface.backgrounds ?? {})) {
1678
- lines.push(`${indent}--surface-${name}: ${surfaceRefToVar(bg._refs.DEFAULT, colorFormat)};`);
1679
- lines.push(`${indent}--surface-${name}-foreground: ${surfaceRefToVar(bg._refs.foreground, colorFormat)};`);
1805
+ for (const [name, page] of Object.entries(surface.pageSurfaces ?? {})) {
1806
+ lines.push(`${indent}--${name}: ${surfaceRefToVar(page._refs.DEFAULT, colorFormat)};`);
1807
+ lines.push(`${indent}--${name}-foreground: ${surfaceRefToVar(page._refs.foreground, colorFormat)};`);
1808
+ lines.push(`${indent}--${name}-foreground-secondary: ${surfaceRefToVar(page._refs["foreground-secondary"], colorFormat)};`);
1680
1809
  }
1681
1810
  return lines;
1682
1811
  }
@@ -1695,7 +1824,7 @@ function emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, act
1695
1824
  lines.push(`${indent}--${name}-active: ${formatColor(color.active, colorFormat)};`);
1696
1825
  }
1697
1826
  for (const [name, color] of Object.entries(tokens.semantic[mode])) {
1698
- if (!extendedSemanticNames.includes(name) && name !== "muted" && inFamily(name)) {
1827
+ if (!extendedSemanticNames.includes(name) && inFamily(name)) {
1699
1828
  const ext = color;
1700
1829
  const mappings = ext._shades ?? getExtendedMappings(mode, name, shadeOverrides, active, anchors);
1701
1830
  lines.push(`${indent}--${name}: var(--color-${name}-${mappings.DEFAULT});`);
@@ -1706,11 +1835,6 @@ function emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, act
1706
1835
  lines.push(`${indent}--${name}-active: ${formatColor(ext.active, colorFormat)};`);
1707
1836
  }
1708
1837
  }
1709
- if (!scoped || inFamily("neutral")) {
1710
- const muted = tokens.semantic[mode].muted._shades ?? MUTED_SHADE_MAPPINGS[mode];
1711
- lines.push(`${indent}--muted: var(--color-neutral-${snapShade(muted.DEFAULT, active)});`);
1712
- lines.push(`${indent}--muted-foreground: var(--color-neutral-${snapShade(muted.foreground, active)});`);
1713
- }
1714
1838
  return lines;
1715
1839
  }
1716
1840
  function emitUtilityVars(mode, indent, active, seedShade, steps) {
@@ -1737,36 +1861,30 @@ function emitUtilityVars(mode, indent, active, seedShade, steps) {
1737
1861
  function groundRefToVar(ref, colorFormat) {
1738
1862
  return ref.type === "value" ? formatColor(ref.value, colorFormat) : refToVar(ref);
1739
1863
  }
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;
1864
+ function modeSelectors(tokens) {
1865
+ const grounds = Object.entries(tokens.grounds ?? {});
1866
+ if (!grounds.length) return { ...MODE_SELECTORS };
1867
+ const of = (polarity) => grounds.filter(([, g]) => g.polarity === polarity).map(([name]) => GROUND_SELECTOR(name));
1868
+ const reset = GROUND_SELECTOR("canvas");
1869
+ const own = `${reset}:not([data-theme="light"]):not(.light)`;
1870
+ return {
1871
+ light: [MODE_SELECTORS.light, reset, ...of("light")].join(", "),
1872
+ dark: [MODE_SELECTORS.dark, ...MODE_SELECTORS.dark.split(", ").map((s) => `${s} ${own}`), ...of("dark")].join(", "),
1873
+ systemDark: [MODE_SELECTORS.systemDark, `${MODE_SELECTORS.systemDark} ${own}`].join(", ")
1874
+ };
1755
1875
  }
1756
- function emitGroundScopes(tokens, rebind) {
1757
- const grounds = tokens.grounds?.light;
1758
- if (!grounds || Object.keys(grounds).length === 0) return [];
1876
+ function emitGroundScopes(tokens, rebind, colorFormat) {
1877
+ const grounds = Object.entries(tokens.grounds ?? {});
1878
+ if (!grounds.length) return [];
1759
1879
  const lines = [
1760
1880
  "",
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. */"
1881
+ '/* Grounds: mark an element data-surface="<ground>" and everything inside it reads tokens',
1882
+ ' that work on it. data-surface="canvas" resets to the page, for a card inside a band. */'
1763
1883
  ];
1764
- for (const [ground, set] of Object.entries(grounds)) {
1765
- const names = Object.keys(set._refs);
1766
- const own = new Set(ownGroundTokens(tokens, ground));
1884
+ for (const [ground, set] of grounds) {
1767
1885
  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});`);
1886
+ for (const token of set.own) lines.push(` --${token}: ${groundRefToVar(set._refs[token], colorFormat)};`);
1887
+ if (rebind) for (const token of set.own) lines.push(` --color-${token}: var(--${token});`);
1770
1888
  lines.push(" background-color: var(--canvas);");
1771
1889
  lines.push(" color: var(--canvas-foreground);");
1772
1890
  lines.push("}");
@@ -1801,10 +1919,6 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1801
1919
  body.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1802
1920
  if (withComments) body.push("");
1803
1921
  }
1804
- if (wantGrounds) {
1805
- if (withComments) body.push(`${indent}/* Grounds: read through data-surface, below */`);
1806
- body.push(...emitGroundVars(tokens, mode, colorFormat, indent));
1807
- }
1808
1922
  while (body.length > 0 && body[body.length - 1] === "") body.pop();
1809
1923
  return body;
1810
1924
  };
@@ -1816,25 +1930,26 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1816
1930
  lines.push(...emitWideGamutBlock(tokens, inFamily));
1817
1931
  }
1818
1932
  if (wantModes) {
1933
+ const selectors = wantGrounds ? modeSelectors(tokens) : MODE_SELECTORS;
1819
1934
  if (wantPrimitives) lines.push("");
1820
1935
  lines.push("/* Light Mode */");
1821
- lines.push(`${MODE_SELECTORS.light} {`);
1936
+ lines.push(`${selectors.light} {`);
1822
1937
  lines.push(...modeBody("light", " ", true));
1823
1938
  lines.push("}");
1824
1939
  lines.push("");
1825
1940
  lines.push("/* Dark Mode */");
1826
- lines.push(`${MODE_SELECTORS.dark} {`);
1941
+ lines.push(`${selectors.dark} {`);
1827
1942
  lines.push(...modeBody("dark", " ", true));
1828
1943
  lines.push("}");
1829
1944
  lines.push("");
1830
1945
  lines.push("/* System Preference: Dark Mode */");
1831
1946
  lines.push("@media (prefers-color-scheme: dark) {");
1832
- lines.push(` ${MODE_SELECTORS.systemDark} {`);
1947
+ lines.push(` ${selectors.systemDark} {`);
1833
1948
  lines.push(...modeBody("dark", " ", false));
1834
1949
  lines.push(" }");
1835
1950
  lines.push("}");
1836
1951
  }
1837
- if (wantGrounds) lines.push(...emitGroundScopes(tokens, false));
1952
+ if (wantGrounds) lines.push(...emitGroundScopes(tokens, false, colorFormat));
1838
1953
  return lines.join("\n");
1839
1954
  }
1840
1955
  var MODE_SELECTORS = {
@@ -1905,21 +2020,23 @@ function semanticAliasNames(tokens, sections, families) {
1905
2020
  if (want.has("semantic")) {
1906
2021
  for (const name of extended) if (inFamily(name)) pushExtended(name);
1907
2022
  for (const name of Object.keys(tokens.semantic.light)) {
1908
- if (!extended.includes(name) && name !== "muted" && inFamily(name)) pushExtended(name);
2023
+ if (!extended.includes(name) && inFamily(name)) pushExtended(name);
1909
2024
  }
1910
- if (!scoped || inFamily("neutral")) names.push("muted", "muted-foreground");
1911
2025
  }
1912
2026
  if (want.has("surface") && !scoped) {
1913
2027
  names.push(
1914
2028
  "canvas",
1915
2029
  "canvas-foreground",
2030
+ "canvas-foreground-secondary",
1916
2031
  "surface",
1917
2032
  "surface-foreground",
2033
+ "surface-foreground-secondary",
1918
2034
  "overlay",
1919
- "overlay-foreground"
2035
+ "overlay-foreground",
2036
+ "overlay-foreground-secondary"
1920
2037
  );
1921
- for (const name of Object.keys(tokens.surface.light.backgrounds ?? {})) {
1922
- names.push(`surface-${name}`, `surface-${name}-foreground`);
2038
+ for (const name of Object.keys(tokens.surface.light.pageSurfaces ?? {})) {
2039
+ names.push(name, `${name}-foreground`, `${name}-foreground-secondary`);
1923
2040
  }
1924
2041
  }
1925
2042
  if (want.has("utility") && !scoped) {
@@ -1936,7 +2053,7 @@ function emitThemeRebinding(aliases, indent) {
1936
2053
  }
1937
2054
  return lines;
1938
2055
  }
1939
- function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, anchors, wantGrounds) {
2056
+ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, anchors) {
1940
2057
  const lines = [];
1941
2058
  const seedShade = anchors.seedShade;
1942
2059
  if (want.has("surface") && !scoped) {
@@ -1954,10 +2071,6 @@ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases,
1954
2071
  lines.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1955
2072
  lines.push("");
1956
2073
  }
1957
- if (wantGrounds) {
1958
- lines.push(`${indent}/* Grounds: read through data-surface, below */`);
1959
- lines.push(...emitGroundVars(tokens, mode, colorFormat, indent));
1960
- }
1961
2074
  while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
1962
2075
  if (aliases.length > 0) lines.push(...emitThemeRebinding(aliases, indent));
1963
2076
  return lines;
@@ -1995,25 +2108,26 @@ function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replace
1995
2108
  lines.push("}");
1996
2109
  if (wantPrimitives) lines.push(...emitWideGamutBlock(tokens, inFamily));
1997
2110
  if (wantModes) {
2111
+ const selectors = wantGrounds ? modeSelectors(tokens) : MODE_SELECTORS;
1998
2112
  lines.push("");
1999
2113
  lines.push("/* Light Mode */");
2000
- lines.push(`${MODE_SELECTORS.light} {`);
2001
- lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
2114
+ lines.push(`${selectors.light} {`);
2115
+ lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2002
2116
  lines.push("}");
2003
2117
  lines.push("");
2004
2118
  lines.push("/* Dark Mode */");
2005
- lines.push(`${MODE_SELECTORS.dark} {`);
2006
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
2119
+ lines.push(`${selectors.dark} {`);
2120
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2007
2121
  lines.push("}");
2008
2122
  lines.push("");
2009
2123
  lines.push("/* System Preference: Dark Mode */");
2010
2124
  lines.push("@media (prefers-color-scheme: dark) {");
2011
- lines.push(` ${MODE_SELECTORS.systemDark} {`);
2012
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors, wantGrounds));
2125
+ lines.push(` ${selectors.systemDark} {`);
2126
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
2013
2127
  lines.push(" }");
2014
2128
  lines.push("}");
2015
2129
  }
2016
- if (wantGrounds) lines.push(...emitGroundScopes(tokens, true));
2130
+ if (wantGrounds) lines.push(...emitGroundScopes(tokens, true, colorFormat));
2017
2131
  return lines.join("\n");
2018
2132
  }
2019
2133
  function exportToTailwindV3(tokens, colorFormat = "hex") {
@@ -2053,7 +2167,7 @@ function exportToTailwindV3(tokens, colorFormat = "hex") {
2053
2167
  config.theme.extend.colors[name] = colorObj;
2054
2168
  }
2055
2169
  for (const name of Object.keys(tokens.semantic.light)) {
2056
- if (!extendedSemanticColors.includes(name) && name !== "muted") {
2170
+ if (!extendedSemanticColors.includes(name)) {
2057
2171
  const primitiveScale = tokens.primitives[name];
2058
2172
  const colorObj = {
2059
2173
  DEFAULT: `var(--${name})`,
@@ -2071,22 +2185,13 @@ function exportToTailwindV3(tokens, colorFormat = "hex") {
2071
2185
  config.theme.extend.colors[name] = colorObj;
2072
2186
  }
2073
2187
  }
2074
- config.theme.extend.colors["muted"] = {
2075
- DEFAULT: "var(--muted)",
2076
- foreground: "var(--muted-foreground)"
2077
- };
2078
- config.theme.extend.colors["canvas"] = {
2079
- DEFAULT: "var(--canvas)",
2080
- foreground: "var(--canvas-foreground)"
2081
- };
2082
- config.theme.extend.colors["surface"] = {
2083
- DEFAULT: "var(--surface)",
2084
- foreground: "var(--surface-foreground)"
2085
- };
2086
- config.theme.extend.colors["overlay"] = {
2087
- DEFAULT: "var(--overlay)",
2088
- foreground: "var(--overlay-foreground)"
2089
- };
2188
+ for (const key of ["canvas", "surface", "overlay"]) {
2189
+ config.theme.extend.colors[key] = {
2190
+ DEFAULT: `var(--${key})`,
2191
+ foreground: `var(--${key}-foreground)`,
2192
+ "foreground-secondary": `var(--${key}-foreground-secondary)`
2193
+ };
2194
+ }
2090
2195
  config.theme.extend.colors["border"] = "var(--border)";
2091
2196
  config.theme.extend.colors["input"] = "var(--input)";
2092
2197
  config.theme.extend.colors["ring"] = "var(--ring)";
@@ -2130,7 +2235,7 @@ function exportToDtcg(tokens) {
2130
2235
  };
2131
2236
  }
2132
2237
  for (const [colorName, color] of Object.entries(tokens.semantic[mode])) {
2133
- if (!extendedNames.includes(colorName) && colorName !== "muted") {
2238
+ if (!extendedNames.includes(colorName)) {
2134
2239
  const ext = color;
2135
2240
  semanticGroup[colorName] = {
2136
2241
  $type: "color",
@@ -2145,21 +2250,18 @@ function exportToDtcg(tokens) {
2145
2250
  };
2146
2251
  }
2147
2252
  }
2148
- const muted = tokens.semantic[mode].muted;
2149
- semanticGroup.muted = {
2150
- $type: "color",
2151
- DEFAULT: { $value: formatColorAs(muted.DEFAULT, "hex") },
2152
- foreground: { $value: formatColorAs(muted.foreground, "hex") }
2153
- };
2154
2253
  const surf = tokens.surface[mode];
2155
2254
  semanticGroup.surface = {
2156
2255
  $type: "color",
2157
2256
  canvas: { $value: formatColorAs(surf.canvas, "hex") },
2158
2257
  "canvas-foreground": { $value: formatColorAs(surf["canvas-foreground"], "hex") },
2258
+ "canvas-foreground-secondary": { $value: formatColorAs(surf["canvas-foreground-secondary"], "hex") },
2159
2259
  surface: { $value: formatColorAs(surf.surface, "hex") },
2160
2260
  "surface-foreground": { $value: formatColorAs(surf["surface-foreground"], "hex") },
2261
+ "surface-foreground-secondary": { $value: formatColorAs(surf["surface-foreground-secondary"], "hex") },
2161
2262
  overlay: { $value: formatColorAs(surf.overlay, "hex") },
2162
- "overlay-foreground": { $value: formatColorAs(surf["overlay-foreground"], "hex") }
2263
+ "overlay-foreground": { $value: formatColorAs(surf["overlay-foreground"], "hex") },
2264
+ "overlay-foreground-secondary": { $value: formatColorAs(surf["overlay-foreground-secondary"], "hex") }
2163
2265
  };
2164
2266
  const util = tokens.utility[mode];
2165
2267
  semanticGroup.utility = {
@@ -2169,18 +2271,17 @@ function exportToDtcg(tokens) {
2169
2271
  ring: { $value: formatColorAs(util.ring, "hex") },
2170
2272
  shadow: { $value: formatColorAs(util.shadow, "hex") }
2171
2273
  };
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
- }
2182
2274
  dtcg[mode] = semanticGroup;
2183
2275
  }
2276
+ if (tokens.grounds && Object.keys(tokens.grounds).length) {
2277
+ const groundGroup = {};
2278
+ for (const [name, set] of Object.entries(tokens.grounds)) {
2279
+ const group = { $type: "color" };
2280
+ for (const [token, value] of Object.entries(set.tokens)) group[token] = { $value: formatColorAs(value, "hex") };
2281
+ groundGroup[name] = group;
2282
+ }
2283
+ dtcg.ground = groundGroup;
2284
+ }
2184
2285
  return JSON.stringify(dtcg, null, 2);
2185
2286
  }
2186
2287
  var SECTIONED_FORMATS = ["css", "tailwind-v4"];
@@ -2271,8 +2372,8 @@ function exportTokens(tokens, format, options) {
2271
2372
  }
2272
2373
 
2273
2374
  // src/merge.ts
2274
- function keyOf(block, property) {
2275
- return `${block} ${property}`;
2375
+ function keyOf(block2, property) {
2376
+ return `${block2} ${property}`;
2276
2377
  }
2277
2378
  function normaliseSelector(raw) {
2278
2379
  return raw.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim();
@@ -2319,7 +2420,7 @@ function readDeclarations(css) {
2319
2420
  const out = [];
2320
2421
  walk(
2321
2422
  css,
2322
- (_line, _index, block, property, value) => out.push({ block, property, value })
2423
+ (_line, _index, block2, property, value) => out.push({ block: block2, property, value })
2323
2424
  );
2324
2425
  return out;
2325
2426
  }
@@ -2332,8 +2433,8 @@ function mergeSlice(target, slice) {
2332
2433
  const updated = [];
2333
2434
  const unchanged = [];
2334
2435
  const seen = /* @__PURE__ */ new Set();
2335
- walk(target, (line, index, block, property, value) => {
2336
- const key = keyOf(block, property);
2436
+ walk(target, (line, index, block2, property, value) => {
2437
+ const key = keyOf(block2, property);
2337
2438
  const wanted = incoming.get(key);
2338
2439
  if (!wanted) return;
2339
2440
  seen.add(key);
@@ -2350,10 +2451,10 @@ function mergeSlice(target, slice) {
2350
2451
  if (additions.length > 0) {
2351
2452
  const lastLineOfBlock = /* @__PURE__ */ new Map();
2352
2453
  const indentOfBlock = /* @__PURE__ */ new Map();
2353
- walk(lines.join("\n"), (line, index, block) => {
2354
- lastLineOfBlock.set(block, index);
2355
- if (!indentOfBlock.has(block)) {
2356
- indentOfBlock.set(block, /^\s*/.exec(line)?.[0] ?? " ");
2454
+ walk(lines.join("\n"), (line, index, block2) => {
2455
+ lastLineOfBlock.set(block2, index);
2456
+ if (!indentOfBlock.has(block2)) {
2457
+ indentOfBlock.set(block2, /^\s*/.exec(line)?.[0] ?? " ");
2357
2458
  }
2358
2459
  });
2359
2460
  const byBlock = /* @__PURE__ */ new Map();
@@ -2369,9 +2470,9 @@ function mergeSlice(target, slice) {
2369
2470
  const ordered = [...byBlock.entries()].sort(
2370
2471
  (a, b) => (lastLineOfBlock.get(b[0]) ?? 0) - (lastLineOfBlock.get(a[0]) ?? 0)
2371
2472
  );
2372
- for (const [block, declarations] of ordered) {
2373
- const at = lastLineOfBlock.get(block);
2374
- const indent = indentOfBlock.get(block) ?? " ";
2473
+ for (const [block2, declarations] of ordered) {
2474
+ const at = lastLineOfBlock.get(block2);
2475
+ const indent = indentOfBlock.get(block2) ?? " ";
2375
2476
  lines.splice(
2376
2477
  at + 1,
2377
2478
  0,
@@ -2410,6 +2511,319 @@ function diffSlice(target, slice) {
2410
2511
  return { matches: differing.length === 0 && missing.length === 0, differing, missing };
2411
2512
  }
2412
2513
 
2514
+ // src/scale.ts
2515
+ var t = (name, value, description) => ({ name, value, description });
2516
+ var textStep = (step, size, px, leading, tracking, use) => [
2517
+ t(`--text-${step}`, size, `${px}: ${use}`),
2518
+ t(`--text-${step}--line-height`, `var(--leading-${leading})`),
2519
+ t(`--text-${step}--letter-spacing`, `var(--tracking-${tracking})`)
2520
+ ];
2521
+ var shadow = (layer, strength) => `${layer} color-mix(in oklch, var(--shadow) ${strength}, transparent)`;
2522
+ function defaultScale() {
2523
+ return [
2524
+ {
2525
+ id: "spacing",
2526
+ title: "Space: the gap between things",
2527
+ themed: true,
2528
+ tokens: [t("--spacing", "0.25rem", "4px: every space is a whole number of these, so 4 is 16px and 24 is 96px")]
2529
+ },
2530
+ {
2531
+ id: "size",
2532
+ title: "Size: the extent of a thing",
2533
+ themed: false,
2534
+ tokens: [
2535
+ t("--size-xs", "1rem", "16px: small icon"),
2536
+ t("--size-sm", "1.25rem", "20px: default icon"),
2537
+ t("--size-md", "1.5rem", "24px: large icon, small avatar"),
2538
+ t("--size-lg", "2rem", "32px: compact control, avatar"),
2539
+ t("--size-xl", "2.5rem", "40px: default control height"),
2540
+ t("--size-2xl", "3rem", "48px: touch control, large avatar"),
2541
+ t("--size-3xl", "4rem", "64px: feature avatar, empty-state icon")
2542
+ ]
2543
+ },
2544
+ {
2545
+ id: "text",
2546
+ title: "Type sizes, each with its line height and tracking",
2547
+ themed: true,
2548
+ tokens: [
2549
+ ...textStep("xs", "0.75rem", "12px", "normal", "normal", "captions, meta"),
2550
+ ...textStep("sm", "0.875rem", "14px", "normal", "normal", "labels, secondary text"),
2551
+ ...textStep("base", "1rem", "16px", "normal", "normal", "body"),
2552
+ ...textStep("lg", "1.125rem", "18px", "snug", "normal", "lead copy"),
2553
+ ...textStep("xl", "1.25rem", "20px", "snug", "normal", "subheads"),
2554
+ ...textStep("2xl", "1.5rem", "24px", "tight", "tight", "headings"),
2555
+ ...textStep("3xl", "1.875rem", "30px", "tight", "tight", "headings"),
2556
+ ...textStep("4xl", "2.25rem", "36px", "none", "tight", "display")
2557
+ ]
2558
+ },
2559
+ {
2560
+ id: "leading",
2561
+ title: "Line height",
2562
+ themed: true,
2563
+ tokens: [
2564
+ t("--leading-none", "1.1", "display"),
2565
+ t("--leading-tight", "1.25", "headings"),
2566
+ t("--leading-snug", "1.4", "subheads, lead copy"),
2567
+ t("--leading-normal", "1.5", "body and interface"),
2568
+ t("--leading-relaxed", "1.65", "long reading")
2569
+ ]
2570
+ },
2571
+ {
2572
+ id: "tracking",
2573
+ title: "Tracking",
2574
+ themed: true,
2575
+ tokens: [t("--tracking-tight", "-0.02em", "headings and display"), t("--tracking-normal", "0em", "body"), t("--tracking-wide", "0.04em", "all-caps labels")]
2576
+ },
2577
+ {
2578
+ id: "font-weight",
2579
+ title: "Weights",
2580
+ themed: true,
2581
+ tokens: [t("--font-weight-normal", "400"), t("--font-weight-medium", "500"), t("--font-weight-semibold", "600"), t("--font-weight-bold", "700")]
2582
+ },
2583
+ {
2584
+ id: "radius",
2585
+ title: "Corners, scaled to the element: bigger box, bigger step",
2586
+ themed: true,
2587
+ tokens: [
2588
+ t("--radius-xs", "0.125rem", "2px: checkbox, tag"),
2589
+ t("--radius-sm", "0.25rem", "4px: small control, badge"),
2590
+ t("--radius-md", "0.375rem", "6px: button, input, the default control radius"),
2591
+ t("--radius-lg", "0.5rem", "8px: card"),
2592
+ t("--radius-xl", "0.75rem", "12px: modal, sheet, large panel"),
2593
+ t("--radius-2xl", "1rem", "16px: feature surface"),
2594
+ t("--radius-full", "9999px", "pill, avatar")
2595
+ ]
2596
+ },
2597
+ {
2598
+ id: "shadow",
2599
+ title: "Elevation: a contact shadow and an ambient one, over the --shadow colour",
2600
+ themed: true,
2601
+ tokens: [
2602
+ t("--shadow-xs", `${shadow("0 1px 1px -0.5px", "10%")}, ${shadow("0 2px 4px -2px", "8%")}`, "a resting input or button"),
2603
+ t("--shadow-sm", `${shadow("0 1px 1px -0.5px", "12%")}, ${shadow("0 3px 8px -3px", "10%")}`, "a resting card"),
2604
+ t("--shadow-md", `${shadow("0 1px 1px -0.5px", "14%")}, ${shadow("0 6px 16px -4px", "14%")}`, "a dropdown, popover or menu"),
2605
+ t("--shadow-lg", `${shadow("0 1px 2px -1px", "16%")}, ${shadow("0 12px 28px -6px", "16%")}`, "a dialog or sheet"),
2606
+ t("--shadow-xl", `${shadow("0 2px 4px -2px", "18%")}, ${shadow("0 24px 48px -12px", "20%")}`, "a full-screen overlay")
2607
+ ]
2608
+ },
2609
+ {
2610
+ id: "duration",
2611
+ title: "How long a change takes",
2612
+ themed: false,
2613
+ tokens: [t("--duration-fast", "120ms", "hover, press, colour and opacity"), t("--duration-base", "200ms", "small surfaces entering or leaving"), t("--duration-slow", "320ms", "dialogs, sheets, layout shifts")]
2614
+ },
2615
+ {
2616
+ id: "ease",
2617
+ title: "How a change moves",
2618
+ themed: true,
2619
+ tokens: [
2620
+ t("--ease-out", "cubic-bezier(0.2, 0, 0, 1)", "entering, responding to input"),
2621
+ t("--ease-in", "cubic-bezier(0.4, 0, 1, 1)", "leaving"),
2622
+ t("--ease-in-out", "cubic-bezier(0.4, 0, 0.2, 1)", "starts and ends on screen")
2623
+ ]
2624
+ },
2625
+ {
2626
+ id: "breakpoint",
2627
+ title: "Screen sizes: where a page can change shape, from each size up",
2628
+ themed: true,
2629
+ tokens: [
2630
+ t("--breakpoint-sm", "40rem", "640px: a large phone, on its side"),
2631
+ t("--breakpoint-md", "48rem", "768px: a tablet, upright"),
2632
+ t("--breakpoint-lg", "64rem", "1024px: a tablet on its side, a small laptop"),
2633
+ t("--breakpoint-xl", "80rem", "1280px: a laptop"),
2634
+ t("--breakpoint-2xl", "96rem", "1536px: a desktop")
2635
+ ]
2636
+ },
2637
+ {
2638
+ id: "container",
2639
+ title: "Widths content is set to",
2640
+ themed: true,
2641
+ tokens: [
2642
+ t("--container-3xs", "16rem"),
2643
+ t("--container-2xs", "18rem"),
2644
+ t("--container-xs", "20rem", "320px: a narrow panel"),
2645
+ t("--container-sm", "24rem", "384px: a dialog"),
2646
+ t("--container-md", "28rem", "448px: a form"),
2647
+ t("--container-lg", "32rem", "512px: a wide dialog"),
2648
+ t("--container-xl", "36rem"),
2649
+ t("--container-2xl", "42rem", "672px: reading width"),
2650
+ t("--container-3xl", "48rem"),
2651
+ t("--container-4xl", "56rem"),
2652
+ t("--container-5xl", "64rem", "1024px: a page of an app"),
2653
+ t("--container-6xl", "72rem"),
2654
+ t("--container-7xl", "80rem", "1280px: the widest a page frame gets")
2655
+ ]
2656
+ }
2657
+ ];
2658
+ }
2659
+ var TIER_OF = [
2660
+ [/^--spacing(-|$)/, "spacing"],
2661
+ [/^--size-/, "size"],
2662
+ [/^--text-/, "text"],
2663
+ [/^--leading-/, "leading"],
2664
+ [/^--tracking-/, "tracking"],
2665
+ [/^--font-weight-/, "font-weight"],
2666
+ [/^--radius-/, "radius"],
2667
+ [/^--shadow-/, "shadow"],
2668
+ [/^--duration-/, "duration"],
2669
+ [/^--ease-/, "ease"],
2670
+ [/^--breakpoint-/, "breakpoint"],
2671
+ [/^--container-/, "container"]
2672
+ ];
2673
+ function applyScaleOverrides(tiers, overrides) {
2674
+ const out = tiers.map((tier) => ({ ...tier, tokens: [...tier.tokens] }));
2675
+ for (const [name, o] of Object.entries(overrides)) {
2676
+ const id = TIER_OF.find(([re]) => re.test(name))?.[1];
2677
+ if (!id) throw new Error(`override "${name}" names no scale tier (--spacing, --size-*, --text-*, --leading-*, --tracking-*, --font-weight-*, --radius-*, --shadow-*, --duration-*, --ease-*, --breakpoint-*, --container-*)`);
2678
+ const tier = out.find((x) => x.id === id);
2679
+ const at = tier.tokens.findIndex((x) => x.name === name);
2680
+ if (o === null) {
2681
+ if (at >= 0) tier.tokens.splice(at, 1);
2682
+ tier.tokens = tier.tokens.filter((x) => !x.name.startsWith(`${name}--`));
2683
+ continue;
2684
+ }
2685
+ const value = typeof o === "string" ? o : o.value;
2686
+ const description = typeof o === "string" ? tier.tokens[at]?.description : o.description ?? tier.tokens[at]?.description;
2687
+ const token = { name, value, description };
2688
+ if (at >= 0) tier.tokens[at] = token;
2689
+ else {
2690
+ const owner = /^(--text-[\w-]+?)--/.exec(name)?.[1];
2691
+ const after = owner ? tier.tokens.map((x) => x.name.startsWith(owner)).lastIndexOf(true) : -1;
2692
+ tier.tokens.splice(after >= 0 ? after + 1 : tier.tokens.length, 0, token);
2693
+ }
2694
+ }
2695
+ for (const tier of out) if (ORDERED.has(tier.id)) tier.tokens.sort((a, b) => Number.parseFloat(a.value) - Number.parseFloat(b.value));
2696
+ return out;
2697
+ }
2698
+ var ORDERED = /* @__PURE__ */ new Set(["leading", "tracking", "font-weight"]);
2699
+ var decl = (tok, indent) => {
2700
+ const value = tok.value.includes("),") && tok.value.length > 70 ? `
2701
+ ${indent} ${tok.value.replace(/\),\s*/g, "),\n" + indent + " ")}` : tok.value;
2702
+ return `${indent}${tok.name}:${value.startsWith("\n") ? "" : " "}${value};${tok.description ? ` /* ${tok.description} */` : ""}`;
2703
+ };
2704
+ function block(tiers, indent) {
2705
+ const out = [];
2706
+ for (const tier of tiers) {
2707
+ if (!tier.tokens.length) continue;
2708
+ out.push("", `${indent}/* ${tier.title} */`);
2709
+ for (const tok of tier.tokens) out.push(decl(tok, indent));
2710
+ }
2711
+ return out.slice(1);
2712
+ }
2713
+ function toCss(tiers) {
2714
+ const screens = tiers.find((x) => x.id === "breakpoint")?.tokens ?? [];
2715
+ return [
2716
+ ":root {",
2717
+ ...block(tiers, " "),
2718
+ "}",
2719
+ ...screens.length ? [
2720
+ "",
2721
+ "/* Screen sizes for media queries: @media (--breakpoint-md) { \u2026 }. A custom property can't go in @media, so these",
2722
+ " are custom media queries, which Lightning CSS and postcss-preset-env compile. */",
2723
+ ...screens.map((s) => `@custom-media ${s.name} (width >= ${s.value});`)
2724
+ ] : []
2725
+ ].join("\n");
2726
+ }
2727
+ function toTailwindV4(tiers) {
2728
+ const themed = tiers.filter((x) => x.themed);
2729
+ const plain = tiers.filter((x) => !x.themed && x.tokens.length);
2730
+ return ["@theme static {", ...block(themed, " "), "}", ...plain.length ? ["", "/* Tailwind has no namespace for these: use them as h-(--size-xl), duration-(--duration-base) */", "@layer base {", " :root {", ...block(plain, " "), " }", "}"] : []].join("\n");
2731
+ }
2732
+ function resolve(value, all, depth = 0) {
2733
+ return depth > 5 ? value : value.replace(/var\((--[\w-]+)\)/g, (m, name) => all.has(name) && !/--shadow$/.test(name) ? resolve(all.get(name), all, depth + 1) : m);
2734
+ }
2735
+ function toTailwindV3(tiers) {
2736
+ const all = new Map(tiers.flatMap((x) => x.tokens.map((tok) => [tok.name, tok.value])));
2737
+ const of = (id, prefix) => Object.fromEntries((tiers.find((x) => x.id === id)?.tokens ?? []).filter((tok) => !tok.name.includes("--", 2)).map((tok) => [tok.name.slice(prefix.length), resolve(tok.value, all)]));
2738
+ const base = Number.parseFloat(all.get("--spacing") ?? "0.25");
2739
+ const steps = [0.5, 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32];
2740
+ const text = Object.fromEntries(
2741
+ (tiers.find((x) => x.id === "text")?.tokens ?? []).filter((tok) => !tok.name.includes("--", 2)).map((tok) => {
2742
+ const lh = all.get(`${tok.name}--line-height`);
2743
+ const ls = all.get(`${tok.name}--letter-spacing`);
2744
+ const extra = { ...lh ? { lineHeight: resolve(lh, all) } : {}, ...ls ? { letterSpacing: resolve(ls, all) } : {} };
2745
+ return [tok.name.slice("--text-".length), Object.keys(extra).length ? [tok.value, extra] : tok.value];
2746
+ })
2747
+ );
2748
+ const theme = {
2749
+ screens: of("breakpoint", "--breakpoint-"),
2750
+ extend: {
2751
+ spacing: Object.fromEntries(steps.map((n) => [String(n), `${Math.round(n * base * 1e4) / 1e4}rem`])),
2752
+ size: of("size", "--size-"),
2753
+ fontSize: text,
2754
+ lineHeight: of("leading", "--leading-"),
2755
+ letterSpacing: of("tracking", "--tracking-"),
2756
+ fontWeight: of("font-weight", "--font-weight-"),
2757
+ borderRadius: of("radius", "--radius-"),
2758
+ boxShadow: of("shadow", "--shadow-"),
2759
+ transitionDuration: of("duration", "--duration-"),
2760
+ transitionTimingFunction: of("ease", "--ease-"),
2761
+ maxWidth: of("container", "--container-")
2762
+ }
2763
+ };
2764
+ return `/** @type {import('tailwindcss').Config['theme']} */
2765
+ module.exports = ${JSON.stringify(theme, null, 2)};`;
2766
+ }
2767
+ var DTCG_TYPE = {
2768
+ spacing: "dimension",
2769
+ size: "dimension",
2770
+ text: "dimension",
2771
+ leading: "number",
2772
+ tracking: "dimension",
2773
+ "font-weight": "fontWeight",
2774
+ radius: "dimension",
2775
+ shadow: void 0,
2776
+ duration: "duration",
2777
+ ease: "cubicBezier",
2778
+ breakpoint: "dimension",
2779
+ container: "dimension"
2780
+ };
2781
+ function dtcgValue(value, type) {
2782
+ const ref = /^var\(--([\w-]+?)-([\w]+)\)$/.exec(value);
2783
+ if (ref) return `{${ref[1]}.${ref[2]}}`;
2784
+ if (type === "cubicBezier") return (/cubic-bezier\(([^)]+)\)/.exec(value)?.[1] ?? "").split(",").map((n) => Number(n.trim()));
2785
+ if (type === "fontWeight" || type === "number") return Number(value);
2786
+ return value;
2787
+ }
2788
+ function toDtcg(tiers) {
2789
+ const doc = {};
2790
+ for (const tier of tiers) {
2791
+ const type = DTCG_TYPE[tier.id];
2792
+ if (tier.id === "spacing") {
2793
+ const tok = tier.tokens.find((x) => x.name === "--spacing");
2794
+ if (tok) doc.spacing = { $type: type, $value: tok.value, ...tok.description ? { $description: tok.description } : {} };
2795
+ continue;
2796
+ }
2797
+ const prefix = tier.tokens[0]?.name.match(/^--[a-z]+(?:-weight)?-/)?.[0] ?? "";
2798
+ const group = { $description: tier.title };
2799
+ if (type) group.$type = type;
2800
+ for (const tok of tier.tokens) {
2801
+ const companion = /^--text-([\w-]+?)--(line-height|letter-spacing)$/.exec(tok.name);
2802
+ if (companion) {
2803
+ const owner = group[companion[1]];
2804
+ if (owner) {
2805
+ owner.$extensions = { designtools: { ...owner.$extensions?.designtools ?? {}, [companion[2]]: dtcgValue(tok.value, void 0) } };
2806
+ }
2807
+ continue;
2808
+ }
2809
+ group[tok.name.slice(prefix.length)] = { $value: dtcgValue(tok.value, type), ...tok.description ? { $description: tok.description } : {} };
2810
+ }
2811
+ doc[tier.id] = group;
2812
+ }
2813
+ return JSON.stringify(doc, null, 2);
2814
+ }
2815
+ function toJson(tiers) {
2816
+ return JSON.stringify({ scale: tiers.flatMap((tier) => tier.tokens.map((tok) => ({ ...tok, tier: tier.id }))) }, null, 2);
2817
+ }
2818
+ function exportScale(tiers, format, header) {
2819
+ const body = { css: toCss, "tailwind-v4": toTailwindV4, "tailwind-v3": toTailwindV3, dtcg: toDtcg, json: toJson }[format](tiers);
2820
+ if (!header || format === "dtcg" || format === "json") return `${body}
2821
+ `;
2822
+ return `${header}
2823
+ ${body}
2824
+ `;
2825
+ }
2826
+
2413
2827
  // src/contract.ts
2414
2828
  var ALIASES = new Set(ALIAS_PAIRS.map(([, alias]) => alias));
2415
2829
  var TEXT = 4.5;
@@ -2539,16 +2953,17 @@ export {
2539
2953
  checkSurfaceContrast,
2540
2954
  checkRampChroma,
2541
2955
  computeAccessibilityScore,
2542
- STATUS_GROUNDS,
2543
2956
  GROUND_BASE_TOKENS,
2544
2957
  GROUND_COLOR_PARTS,
2545
2958
  groundTokenNames,
2546
- reservedGroundNames,
2959
+ reservedSurfaceNames,
2960
+ suggestStep,
2547
2961
  generateGroundTokens,
2548
2962
  generateTokens,
2549
2963
  usageReport,
2550
2964
  serialiseUsage,
2551
2965
  WIDE_GAMUT_QUERY,
2966
+ modeSelectors,
2552
2967
  GROUND_SELECTOR,
2553
2968
  exportToCss,
2554
2969
  overrideContract,
@@ -2564,6 +2979,9 @@ export {
2564
2979
  readDeclarations,
2565
2980
  mergeSlice,
2566
2981
  diffSlice,
2982
+ defaultScale,
2983
+ applyScaleOverrides,
2984
+ exportScale,
2567
2985
  stepContract,
2568
2986
  GENERATOR_NAME,
2569
2987
  stableStringify,