@designtools/tokens 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -68,12 +68,43 @@ import {
68
68
  filterDeficiencyProt,
69
69
  filterDeficiencyDeuter,
70
70
  filterDeficiencyTrit,
71
- parse
71
+ parse,
72
+ toGamut,
73
+ inGamut,
74
+ clampChroma
72
75
  } from "culori";
73
- import { APCAcontrast, sRGBtoY } from "apca-w3";
76
+ import { APCAcontrast, sRGBtoY, displayP3toY } from "apca-w3";
74
77
  var toOklch = converter("oklch");
75
- var toRgbConverter = converter("rgb");
76
78
  var toHslConverter = converter("hsl");
79
+ var GAMUT_SPACE = { srgb: "rgb", p3: "p3" };
80
+ var GAMUT_MAPPERS = {
81
+ srgb: toGamut("rgb", "oklch"),
82
+ p3: toGamut("p3", "oklch")
83
+ };
84
+ var GAMUT_CHECKS = {
85
+ srgb: inGamut("rgb"),
86
+ p3: inGamut("p3")
87
+ };
88
+ var GAMUT_CONVERTERS = {
89
+ srgb: converter("rgb"),
90
+ p3: converter("p3")
91
+ };
92
+ function isInGamut(color, gamut = "srgb") {
93
+ const parsed = parse(color);
94
+ if (!parsed) throw new Error(`Invalid color: ${color}`);
95
+ return GAMUT_CHECKS[gamut](parsed);
96
+ }
97
+ function displayed(color, gamut = "srgb") {
98
+ const parsed = typeof color === "string" ? parse(color) : color;
99
+ if (!parsed) throw new Error(`Cannot convert ${String(color)} to RGB`);
100
+ const mapped = GAMUT_CHECKS[gamut](parsed) ? GAMUT_CONVERTERS[gamut](parsed) : GAMUT_MAPPERS[gamut](parsed);
101
+ if (!mapped) throw new Error(`Cannot convert ${color} to ${GAMUT_SPACE[gamut]}`);
102
+ const unit = (v) => Math.min(1, Math.max(0, v ?? 0));
103
+ return { r: unit(mapped.r), g: unit(mapped.g), b: unit(mapped.b) };
104
+ }
105
+ function displayedSrgb(color) {
106
+ return { mode: "rgb", ...displayed(color, "srgb") };
107
+ }
77
108
  function parseToOklch(color) {
78
109
  const result = toOklch(color);
79
110
  if (!result) {
@@ -82,7 +113,7 @@ function parseToOklch(color) {
82
113
  return result;
83
114
  }
84
115
  function oklchToHex(color) {
85
- const hex = formatHex(color);
116
+ const hex = formatHex(displayedSrgb(color));
86
117
  return hex || "#000000";
87
118
  }
88
119
  function computeScaleChroma(scaleValue, baseChroma) {
@@ -122,6 +153,23 @@ var LIGHTNESS_FACTORS = {
122
153
  achromatic: [0.98, 0.95, 0.9, 0.8, 0.66, 0.38, 0, -0.26, -0.44, -0.62, -0.8, -0.92]
123
154
  }
124
155
  };
156
+ function printOklch(l, c, h) {
157
+ return `oklch(${l} ${c.toFixed(4)} ${h})`;
158
+ }
159
+ function formatOklchInGamut(lightness, chroma, hue, gamut = "srgb") {
160
+ const l = (lightness * 100).toFixed(2) + "%";
161
+ const h = hue.toFixed(2);
162
+ const c = Math.max(0, chroma);
163
+ const printed = printOklch(l, c, h);
164
+ if (isInGamut(printed, gamut)) return printed;
165
+ const at = { mode: "oklch", l: Number(l.slice(0, -1)) / 100, c, h: Number(h) };
166
+ const capped = clampChroma(at, "oklch", GAMUT_SPACE[gamut]);
167
+ let fit = Math.floor((capped.c ?? 0) * 1e4) / 1e4;
168
+ while (fit > 0 && !isInGamut(printOklch(l, fit, h), gamut)) {
169
+ fit = Math.round((fit - 1e-4) * 1e4) / 1e4;
170
+ }
171
+ return printOklch(l, fit, h);
172
+ }
125
173
  function buildScale(baseColor, strategy, options) {
126
174
  const base = parseToOklch(baseColor);
127
175
  const baseLightness = base.l;
@@ -130,6 +178,7 @@ function buildScale(baseColor, strategy, options) {
130
178
  const isAchromatic = baseChroma < 0.01;
131
179
  const seedShade = options?.seedShade ?? DEFAULT_SEED_SHADE;
132
180
  const emitted = resolveShades(options?.shades);
181
+ const gamut = options?.gamut ?? "srgb";
133
182
  const maxLightness = Math.max(0.98, baseLightness);
134
183
  const minLightness = Math.min(0.15, baseLightness);
135
184
  const headroomUp = maxLightness - baseLightness;
@@ -144,7 +193,7 @@ function buildScale(baseColor, strategy, options) {
144
193
  const shade = VALID_SHADES[i];
145
194
  if (!emitted.includes(shade)) continue;
146
195
  if (shade === seedShade) {
147
- scale[shade] = getOklchString(baseColor);
196
+ scale[shade] = formatOklchInGamut(baseLightness, baseChroma, baseHue, gamut);
148
197
  continue;
149
198
  }
150
199
  const factor = factors[i];
@@ -153,10 +202,7 @@ function buildScale(baseColor, strategy, options) {
153
202
  const chromaShade = chromaShadeFor(i, seedShade);
154
203
  const normalizedPosition = (chromaShade - 25) / 925;
155
204
  const chroma = isAchromatic ? baseChroma : computeChroma(normalizedPosition, baseChroma);
156
- const l = (lightness * 100).toFixed(2) + "%";
157
- const c = Math.max(0, chroma).toFixed(4);
158
- const h = baseHue.toFixed(2);
159
- scale[shade] = `oklch(${l} ${c} ${h})`;
205
+ scale[shade] = formatOklchInGamut(lightness, chroma, baseHue, gamut);
160
206
  }
161
207
  return scale;
162
208
  }
@@ -180,30 +226,19 @@ function adjustChroma(color, chroma) {
180
226
  c: Math.max(0, chroma)
181
227
  });
182
228
  }
183
- function toRgb(color) {
184
- const rgb = toRgbConverter(color);
185
- if (!rgb || !("r" in rgb) || !("g" in rgb) || !("b" in rgb)) {
186
- throw new Error(`Cannot convert ${color} to RGB`);
187
- }
188
- return {
189
- r: rgb.r,
190
- g: rgb.g,
191
- b: rgb.b
192
- };
193
- }
194
- function getRelativeLuminance(color) {
195
- const rgb = toRgb(color);
196
- const rsRGB = rgb.r;
197
- const gsRGB = rgb.g;
198
- const bsRGB = rgb.b;
199
- const r = rsRGB <= 0.03928 ? rsRGB / 12.92 : Math.pow((rsRGB + 0.055) / 1.055, 2.4);
200
- const g = gsRGB <= 0.03928 ? gsRGB / 12.92 : Math.pow((gsRGB + 0.055) / 1.055, 2.4);
201
- const b = bsRGB <= 0.03928 ? bsRGB / 12.92 : Math.pow((bsRGB + 0.055) / 1.055, 2.4);
202
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
203
- }
204
- function getContrastRatio(color1, color2) {
205
- const lum1 = getRelativeLuminance(color1);
206
- const lum2 = getRelativeLuminance(color2);
229
+ var LUMINANCE_WEIGHTS = {
230
+ srgb: [0.2126, 0.7152, 0.0722],
231
+ p3: [0.2289746, 0.6917385, 0.0792869]
232
+ };
233
+ function getRelativeLuminance(color, gamut = "srgb") {
234
+ const rgb = displayed(color, gamut);
235
+ const [wr, wg, wb] = LUMINANCE_WEIGHTS[gamut];
236
+ const linear = (c) => c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
237
+ return wr * linear(rgb.r) + wg * linear(rgb.g) + wb * linear(rgb.b);
238
+ }
239
+ function getContrastRatio(color1, color2, gamut = "srgb") {
240
+ const lum1 = getRelativeLuminance(color1, gamut);
241
+ const lum2 = getRelativeLuminance(color2, gamut);
207
242
  const lighter = Math.max(lum1, lum2);
208
243
  const darker = Math.min(lum1, lum2);
209
244
  return (lighter + 0.05) / (darker + 0.05);
@@ -214,12 +249,11 @@ function meetsWCAG_AA(ratio, isLargeText = false) {
214
249
  function meetsWCAG_AAA(ratio, isLargeText = false) {
215
250
  return isLargeText ? ratio >= 4.5 : ratio >= 7;
216
251
  }
217
- function getAPCAContrast(foreground, background) {
218
- const fgRgb = toRgb(foreground);
219
- const bgRgb = toRgb(background);
220
- const fgY = sRGBtoY([fgRgb.r * 255, fgRgb.g * 255, fgRgb.b * 255]);
221
- const bgY = sRGBtoY([bgRgb.r * 255, bgRgb.g * 255, bgRgb.b * 255]);
222
- return Math.abs(APCAcontrast(fgY, bgY));
252
+ function getAPCAContrast(foreground, background, gamut = "srgb") {
253
+ const fg = displayed(foreground, gamut);
254
+ const bg = displayed(background, gamut);
255
+ const toY = (c) => gamut === "p3" ? displayP3toY([c.r, c.g, c.b]) : sRGBtoY([c.r * 255, c.g * 255, c.b * 255]);
256
+ return Math.abs(APCAcontrast(toY(fg), toY(bg)));
223
257
  }
224
258
  function findContrastingColorAPCA(background, lightColor, darkColor) {
225
259
  const lightLc = getAPCAContrast(lightColor, background);
@@ -235,7 +269,7 @@ function simulateCVD(color, cvd) {
235
269
  if (cvd === "none") return color;
236
270
  const parsed = parse(color);
237
271
  if (!parsed) return color;
238
- const simulated = cvdFilters[cvd](parsed);
272
+ const simulated = cvdFilters[cvd](displayedSrgb(parsed));
239
273
  return formatHex(simulated) || color;
240
274
  }
241
275
  function classifyAPCALevel(lcValue) {
@@ -284,14 +318,13 @@ function getOklchString(color) {
284
318
  function formatColorAs(color, format) {
285
319
  switch (format) {
286
320
  case "hex":
287
- return formatHex(color) || "#000000";
321
+ return formatHex(displayedSrgb(color)) || "#000000";
288
322
  case "rgb": {
289
- const rgb = toRgbConverter(color);
290
- if (!rgb) return "rgb(0, 0, 0)";
291
- return formatRgb(rgb) || "rgb(0, 0, 0)";
323
+ return formatRgb(displayedSrgb(color)) || "rgb(0, 0, 0)";
292
324
  }
293
325
  case "hsl": {
294
- const hsl = toHslConverter(color);
326
+ const hsl = toHslConverter(displayedSrgb(color));
327
+ if (hsl && Math.round((hsl.s ?? 0) * 1e4) === 0) hsl.h = 0;
295
328
  if (!hsl) return "hsl(0, 0%, 0%)";
296
329
  return formatHsl(hsl) || "hsl(0, 0%, 0%)";
297
330
  }
@@ -315,6 +348,11 @@ function aliasOf(name) {
315
348
  }
316
349
  return void 0;
317
350
  }
351
+ function familySeedShade(name, seedShade, seedShades) {
352
+ if (name === "primary") return seedShade ?? seedShades?.primary;
353
+ const alias = aliasOf(name);
354
+ return seedShades?.[name] ?? (alias ? seedShades?.[alias] : void 0);
355
+ }
318
356
  function clamp(v, min, max) {
319
357
  return Math.min(max, Math.max(min, v));
320
358
  }
@@ -351,17 +389,21 @@ function deriveWarningColor(primaryColor) {
351
389
  };
352
390
  return oklchToHex(warning);
353
391
  }
354
- function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", scaleOptions) {
392
+ function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", options) {
355
393
  const gen = lightnessStrategy === "perceptual" ? generateColorScaleAPCA : generateColorScale;
356
- const genScale = (color) => gen(color, scaleOptions);
394
+ const genScale = (name, color) => gen(color, {
395
+ shades: options?.shades,
396
+ gamut: options?.gamut,
397
+ seedShade: familySeedShade(name, options?.seedShade, options?.seedShades)
398
+ });
357
399
  const palette = {};
358
400
  palette.black = "oklch(0 0 0)";
359
401
  palette.white = "oklch(1 0 0)";
360
- palette.primary = genScale(brandColors.primary);
361
- palette.neutral = genScale(brandColors.neutral);
362
- const successScale = genScale(deriveSuccessColor(brandColors.primary));
363
- const destructiveScale = genScale(deriveDestructiveColor(brandColors.primary));
364
- const warningScale = genScale(deriveWarningColor(brandColors.primary));
402
+ palette.primary = genScale("primary", brandColors.primary);
403
+ palette.neutral = genScale("neutral", brandColors.neutral);
404
+ const successScale = genScale("success", deriveSuccessColor(brandColors.primary));
405
+ const destructiveScale = genScale("destructive", deriveDestructiveColor(brandColors.primary));
406
+ const warningScale = genScale("warning", deriveWarningColor(brandColors.primary));
365
407
  palette.success = successScale;
366
408
  palette.destructive = destructiveScale;
367
409
  palette.warning = warningScale;
@@ -370,7 +412,7 @@ function generatePrimitivePalette(brandColors, lightnessStrategy = "fixed", scal
370
412
  palette.yellow = warningScale;
371
413
  if (brandColors.additionalColors) {
372
414
  for (const [name, color] of Object.entries(brandColors.additionalColors)) {
373
- palette[name] = genScale(color);
415
+ palette[name] = genScale(name, color);
374
416
  }
375
417
  for (const [semantic, alias] of ALIAS_PAIRS) {
376
418
  const overrodeSemantic = semantic in brandColors.additionalColors;
@@ -444,14 +486,18 @@ function getContrastThresholds(algorithm, target) {
444
486
  }
445
487
  }
446
488
  }
447
- function findBestForeground(background, scale, neutralScale, white, black, algorithm, contrastTarget, colorName, activeShades) {
489
+ function findBestForeground(views, white, black, algorithm, contrastTarget, colorName, activeShades) {
448
490
  const { floor, target } = getContrastThresholds(algorithm, contrastTarget);
449
- const getContrast = (fg) => algorithm === "apca" ? getAPCAContrast(fg, background) : getContrastRatio(background, fg);
450
- function searchScale(s, refColorName) {
491
+ const getContrast = (fgOf) => Math.min(
492
+ ...views.map(
493
+ (view) => algorithm === "apca" ? getAPCAContrast(fgOf(view), view.background, view.gamut) : getContrastRatio(view.background, fgOf(view), view.gamut)
494
+ )
495
+ );
496
+ function searchScale(which, refColorName) {
451
497
  let bestPassing = null;
452
498
  let bestOverall = null;
453
499
  for (const shade of activeShades) {
454
- const c = getContrast(s[shade]);
500
+ const c = getContrast((view) => view[which][shade]);
455
501
  if (c >= floor) {
456
502
  if (!bestPassing || Math.abs(c - target) < Math.abs(bestPassing.contrast - target)) {
457
503
  bestPassing = { shade, contrast: c };
@@ -464,17 +510,17 @@ function findBestForeground(background, scale, neutralScale, white, black, algor
464
510
  const pick = bestPassing ?? bestOverall;
465
511
  if (!pick) return null;
466
512
  return {
467
- value: s[pick.shade],
513
+ value: views[0][which][pick.shade],
468
514
  ref: { type: "shade", colorName: refColorName, shade: pick.shade },
469
515
  contrast: pick.contrast,
470
516
  passes: pick === bestPassing
471
517
  };
472
518
  }
473
- const ownResult = searchScale(scale, colorName);
519
+ const ownResult = searchScale("scale", colorName);
474
520
  if (ownResult?.passes) {
475
521
  return { value: ownResult.value, ref: ownResult.ref };
476
522
  }
477
- const neutralResult = searchScale(neutralScale, "neutral");
523
+ const neutralResult = searchScale("neutral", "neutral");
478
524
  if (neutralResult?.passes) {
479
525
  if (!ownResult?.passes) {
480
526
  return { value: neutralResult.value, ref: neutralResult.ref };
@@ -490,21 +536,30 @@ function findBestForeground(background, scale, neutralScale, white, black, algor
490
536
  if (neutralResult) {
491
537
  return { value: neutralResult.value, ref: neutralResult.ref };
492
538
  }
493
- const whiteC = getContrast(white);
494
- const blackC = getContrast(black);
539
+ const whiteC = getContrast(() => white);
540
+ const blackC = getContrast(() => black);
495
541
  if (whiteC >= blackC) return { value: white, ref: { type: "white" } };
496
542
  return { value: black, ref: { type: "black" } };
497
543
  }
498
- function createExtendedSemanticColor(scale, neutral, white, black, mode, contrastAlgorithm = "wcag", contrastTarget = "aa", overrides, colorName = "primary", shades, seedShade) {
544
+ function createExtendedSemanticColor(scale, neutral, white, black, mode, contrastAlgorithm = "wcag", contrastTarget = "aa", overrides, colorName = "primary", shades, seedShade, gamuts = { own: "srgb" }) {
499
545
  const activeShades = shadeKeys(shades);
500
- const findFg = (bg) => findBestForeground(bg, scale, neutral, white, black, contrastAlgorithm, contrastTarget, colorName, activeShades);
546
+ const findFg = (bgShade) => {
547
+ const views = [
548
+ { background: scale[bgShade], scale, neutral, gamut: gamuts.own }
549
+ ];
550
+ if (gamuts.other) {
551
+ const o = gamuts.other;
552
+ views.push({ background: o.scale[bgShade], scale: o.scale, neutral: o.neutral, gamut: o.gamut });
553
+ }
554
+ return findBestForeground(views, white, black, contrastAlgorithm, contrastTarget, colorName, activeShades);
555
+ };
501
556
  const { DEFAULT: defaultShade, subdued: subduedShade, highlight: highlightShade } = extendedBridgeShades(mode, seedShade, activeShades, overrides);
502
557
  const DEFAULT = scale[defaultShade];
503
558
  const subdued = scale[subduedShade];
504
559
  const highlight = scale[highlightShade];
505
- const fgResult = overrides?.["on-DEFAULT"] ? { value: scale[overrides["on-DEFAULT"]], ref: { type: "shade", colorName, shade: overrides["on-DEFAULT"] } } : findFg(DEFAULT);
506
- const sfgResult = overrides?.["on-subdued"] ? { value: scale[overrides["on-subdued"]], ref: { type: "shade", colorName, shade: overrides["on-subdued"] } } : findFg(subdued);
507
- const hfgResult = overrides?.["on-highlight"] ? { value: scale[overrides["on-highlight"]], ref: { type: "shade", colorName, shade: overrides["on-highlight"] } } : findFg(highlight);
560
+ const fgResult = overrides?.["on-DEFAULT"] ? { value: scale[overrides["on-DEFAULT"]], ref: { type: "shade", colorName, shade: overrides["on-DEFAULT"] } } : findFg(defaultShade);
561
+ const sfgResult = overrides?.["on-subdued"] ? { value: scale[overrides["on-subdued"]], ref: { type: "shade", colorName, shade: overrides["on-subdued"] } } : findFg(subduedShade);
562
+ const hfgResult = overrides?.["on-highlight"] ? { value: scale[overrides["on-highlight"]], ref: { type: "shade", colorName, shade: overrides["on-highlight"] } } : findFg(highlightShade);
508
563
  return {
509
564
  DEFAULT,
510
565
  foreground: fgResult.value,
@@ -519,12 +574,12 @@ function createExtendedSemanticColor(scale, neutral, white, black, mode, contras
519
574
  }
520
575
  };
521
576
  }
522
- function generateSemanticTokens(palette, mode, options) {
577
+ function generateSemanticTokens(palette, mode, options, gamuts = { own: "srgb" }) {
523
578
  const contrastAlgorithm = options?.contrastAlgorithm ?? "wcag";
524
579
  const contrastTarget = options?.contrastTarget ?? "aa";
525
580
  const shadeOverrides = options?.shadeOverrides ?? {};
526
581
  const activeShades = shadeKeys(options?.shades);
527
- const seedShade = options?.seedShade;
582
+ const anchor = (name) => familySeedShade(name, options?.seedShade, options?.seedShades);
528
583
  const neutral = palette.neutral;
529
584
  if (!neutral) {
530
585
  throw new Error("Neutral palette not found");
@@ -538,6 +593,17 @@ function generateSemanticTokens(palette, mode, options) {
538
593
  if (!primary || !success || !destructive || !warning) {
539
594
  throw new Error("Required color palettes not found");
540
595
  }
596
+ const other = gamuts.other;
597
+ const gamutsFor = (name) => ({
598
+ own: gamuts.own,
599
+ ...other ? {
600
+ other: {
601
+ gamut: other.gamut,
602
+ scale: other.palette[name],
603
+ neutral: other.palette.neutral
604
+ }
605
+ } : {}
606
+ });
541
607
  const muted = mode === "light" ? {
542
608
  DEFAULT: neutral[snapShade(25, activeShades)],
543
609
  foreground: neutral[snapShade(500, activeShades)]
@@ -546,11 +612,11 @@ function generateSemanticTokens(palette, mode, options) {
546
612
  foreground: neutral[snapShade(200, activeShades)]
547
613
  };
548
614
  const tokens = {
549
- primary: createExtendedSemanticColor(primary, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.primary?.[mode], "primary", activeShades, seedShade),
550
- neutral: createExtendedSemanticColor(neutral, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.neutral?.[mode], "neutral", activeShades, seedShade),
551
- success: createExtendedSemanticColor(success, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.success?.[mode], "success", activeShades, seedShade),
552
- destructive: createExtendedSemanticColor(destructive, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.destructive?.[mode], "destructive", activeShades, seedShade),
553
- warning: createExtendedSemanticColor(warning, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.warning?.[mode], "warning", activeShades, seedShade),
615
+ primary: createExtendedSemanticColor(primary, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.primary?.[mode], "primary", activeShades, anchor("primary"), gamutsFor("primary")),
616
+ neutral: createExtendedSemanticColor(neutral, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.neutral?.[mode], "neutral", activeShades, anchor("neutral"), gamutsFor("neutral")),
617
+ success: createExtendedSemanticColor(success, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.success?.[mode], "success", activeShades, anchor("success"), gamutsFor("success")),
618
+ destructive: createExtendedSemanticColor(destructive, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.destructive?.[mode], "destructive", activeShades, anchor("destructive"), gamutsFor("destructive")),
619
+ warning: createExtendedSemanticColor(warning, neutral, white, black, mode, contrastAlgorithm, contrastTarget, shadeOverrides.warning?.[mode], "warning", activeShades, anchor("warning"), gamutsFor("warning")),
554
620
  muted
555
621
  };
556
622
  const coreColors = [
@@ -578,7 +644,8 @@ function generateSemanticTokens(palette, mode, options) {
578
644
  shadeOverrides[colorName]?.[mode],
579
645
  colorName,
580
646
  activeShades,
581
- seedShade
647
+ anchor(colorName),
648
+ gamutsFor(colorName)
582
649
  );
583
650
  }
584
651
  }
@@ -641,7 +708,7 @@ function generateUtilityTokens(palette, mode, overrides, shades, seedShade) {
641
708
  shadow: neutral[overrides?.shadow ? snap(overrides.shadow) : defaults.shadow]
642
709
  };
643
710
  }
644
- function checkSemanticContrast(tokens) {
711
+ function checkSemanticContrast(tokens, gamut = "srgb") {
645
712
  const results = {};
646
713
  for (const [name, color] of Object.entries(tokens)) {
647
714
  if (name === "muted") {
@@ -650,7 +717,8 @@ function checkSemanticContrast(tokens) {
650
717
  const extendedColor = color;
651
718
  const ratio = getContrastRatio(
652
719
  extendedColor.DEFAULT,
653
- extendedColor.foreground
720
+ extendedColor.foreground,
721
+ gamut
654
722
  );
655
723
  results[`${name}/default`] = {
656
724
  ratio: Math.round(ratio * 100) / 100,
@@ -659,7 +727,8 @@ function checkSemanticContrast(tokens) {
659
727
  };
660
728
  const subduedRatio = getContrastRatio(
661
729
  extendedColor.subdued,
662
- extendedColor["subdued-foreground"]
730
+ extendedColor["subdued-foreground"],
731
+ gamut
663
732
  );
664
733
  results[`${name}/subdued`] = {
665
734
  ratio: Math.round(subduedRatio * 100) / 100,
@@ -668,7 +737,8 @@ function checkSemanticContrast(tokens) {
668
737
  };
669
738
  const highlightRatio = getContrastRatio(
670
739
  extendedColor.highlight,
671
- extendedColor["highlight-foreground"]
740
+ extendedColor["highlight-foreground"],
741
+ gamut
672
742
  );
673
743
  results[`${name}/highlight`] = {
674
744
  ratio: Math.round(highlightRatio * 100) / 100,
@@ -678,7 +748,8 @@ function checkSemanticContrast(tokens) {
678
748
  }
679
749
  const mutedRatio = getContrastRatio(
680
750
  tokens.muted.DEFAULT,
681
- tokens.muted.foreground
751
+ tokens.muted.foreground,
752
+ gamut
682
753
  );
683
754
  results["muted"] = {
684
755
  ratio: Math.round(mutedRatio * 100) / 100,
@@ -687,30 +758,30 @@ function checkSemanticContrast(tokens) {
687
758
  };
688
759
  return results;
689
760
  }
690
- function checkSemanticContrastAPCA(tokens) {
761
+ function checkSemanticContrastAPCA(tokens, gamut = "srgb") {
691
762
  const results = {};
692
763
  for (const [name, color] of Object.entries(tokens)) {
693
764
  if (name === "muted") {
694
765
  continue;
695
766
  }
696
767
  const ext = color;
697
- const defaultLc = getAPCAContrast(ext.foreground, ext.DEFAULT);
768
+ const defaultLc = getAPCAContrast(ext.foreground, ext.DEFAULT, gamut);
698
769
  results[`${name}/default`] = {
699
770
  lcValue: Math.round(defaultLc * 10) / 10,
700
771
  level: classifyAPCALevel(defaultLc)
701
772
  };
702
- const subduedLc = getAPCAContrast(ext["subdued-foreground"], ext.subdued);
773
+ const subduedLc = getAPCAContrast(ext["subdued-foreground"], ext.subdued, gamut);
703
774
  results[`${name}/subdued`] = {
704
775
  lcValue: Math.round(subduedLc * 10) / 10,
705
776
  level: classifyAPCALevel(subduedLc)
706
777
  };
707
- const highlightLc = getAPCAContrast(ext["highlight-foreground"], ext.highlight);
778
+ const highlightLc = getAPCAContrast(ext["highlight-foreground"], ext.highlight, gamut);
708
779
  results[`${name}/highlight`] = {
709
780
  lcValue: Math.round(highlightLc * 10) / 10,
710
781
  level: classifyAPCALevel(highlightLc)
711
782
  };
712
783
  }
713
- const mutedLc = getAPCAContrast(tokens.muted.foreground, tokens.muted.DEFAULT);
784
+ const mutedLc = getAPCAContrast(tokens.muted.foreground, tokens.muted.DEFAULT, gamut);
714
785
  results["muted"] = {
715
786
  lcValue: Math.round(mutedLc * 10) / 10,
716
787
  level: classifyAPCALevel(mutedLc)
@@ -718,9 +789,9 @@ function checkSemanticContrastAPCA(tokens) {
718
789
  return results;
719
790
  }
720
791
  var NON_TEXT_CONTRAST_MIN = 3;
721
- function checkSurfaceContrast(surface, utility) {
792
+ function checkSurfaceContrast(surface, utility, gamut = "srgb") {
722
793
  const pair = (bg, fg, nonText = false, advisory = false) => {
723
- const ratio = getContrastRatio(bg, fg);
794
+ const ratio = getContrastRatio(bg, fg, gamut);
724
795
  return {
725
796
  ratio: Math.round(ratio * 100) / 100,
726
797
  passesAA: meetsWCAG_AA(ratio),
@@ -760,13 +831,13 @@ function checkRampChroma(palette) {
760
831
  }
761
832
  return results;
762
833
  }
763
- function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa") {
834
+ function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa", gamut = "srgb") {
764
835
  const { floor } = getContrastThresholds(algorithm, contrastTarget);
765
836
  const skipKeys = /* @__PURE__ */ new Set(["muted"]);
766
837
  let passed = 0;
767
838
  let total = 0;
768
839
  if (algorithm === "wcag") {
769
- const results = checkSemanticContrast(tokens);
840
+ const results = checkSemanticContrast(tokens, gamut);
770
841
  for (const [key, result] of Object.entries(results)) {
771
842
  const colorName = key.split("/")[0];
772
843
  if (skipKeys.has(colorName)) continue;
@@ -776,7 +847,7 @@ function computeAccessibilityScore(tokens, algorithm, contrastTarget = "aa") {
776
847
  }
777
848
  }
778
849
  } else {
779
- const results = checkSemanticContrastAPCA(tokens);
850
+ const results = checkSemanticContrastAPCA(tokens, gamut);
780
851
  for (const [key, result] of Object.entries(results)) {
781
852
  const colorName = key.split("/")[0];
782
853
  if (skipKeys.has(colorName)) continue;
@@ -865,35 +936,39 @@ var defaultShadows = {
865
936
  }
866
937
  };
867
938
  function generateTokens(brandColors, options) {
868
- const primitives = generatePrimitivePalette(
869
- brandColors,
870
- options?.lightnessStrategy ?? "fixed",
871
- { seedShade: options?.seedShade, shades: options?.shades }
872
- );
873
- const lightSemantic = generateSemanticTokens(primitives, "light", options);
874
- const darkSemantic = generateSemanticTokens(primitives, "dark", options);
875
- const lightSurface = generateSurfaceTokens(primitives, "light", options?.surfaceShadeOverrides?.light, options?.shades);
876
- const darkSurface = generateSurfaceTokens(primitives, "dark", options?.surfaceShadeOverrides?.dark, options?.shades);
877
- const lightUtility = generateUtilityTokens(primitives, "light", options?.utilityShadeOverrides?.light, options?.shades, options?.seedShade);
878
- const darkUtility = generateUtilityTokens(primitives, "dark", options?.utilityShadeOverrides?.dark, options?.shades, options?.seedShade);
879
- return {
880
- primitives,
939
+ const strategy = options?.lightnessStrategy ?? "fixed";
940
+ const scaleOptions = {
941
+ seedShade: options?.seedShade,
942
+ seedShades: options?.seedShades,
943
+ shades: options?.shades
944
+ };
945
+ const primitives = generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "srgb" });
946
+ const wide = options?.gamut === "p3" ? generatePrimitivePalette(brandColors, strategy, { ...scaleOptions, gamut: "p3" }) : void 0;
947
+ const colourTiers = (palette, gamuts) => ({
948
+ primitives: palette,
881
949
  semantic: {
882
- light: lightSemantic,
883
- dark: darkSemantic
950
+ light: generateSemanticTokens(palette, "light", options, gamuts),
951
+ dark: generateSemanticTokens(palette, "dark", options, gamuts)
884
952
  },
885
953
  surface: {
886
- light: lightSurface,
887
- dark: darkSurface
954
+ light: generateSurfaceTokens(palette, "light", options?.surfaceShadeOverrides?.light, options?.shades),
955
+ dark: generateSurfaceTokens(palette, "dark", options?.surfaceShadeOverrides?.dark, options?.shades)
888
956
  },
889
957
  utility: {
890
- light: lightUtility,
891
- dark: darkUtility
892
- },
958
+ light: generateUtilityTokens(palette, "light", options?.utilityShadeOverrides?.light, options?.shades, options?.seedShade),
959
+ dark: generateUtilityTokens(palette, "dark", options?.utilityShadeOverrides?.dark, options?.shades, options?.seedShade)
960
+ }
961
+ });
962
+ return {
963
+ ...colourTiers(primitives, {
964
+ own: "srgb",
965
+ ...wide ? { other: { gamut: "p3", palette: wide } } : {}
966
+ }),
893
967
  spacing: {},
894
968
  typography: defaultTypography,
895
969
  radii: defaultRadii,
896
- shadows: defaultShadows
970
+ shadows: defaultShadows,
971
+ ...wide ? { p3: colourTiers(wide, { own: "p3", other: { gamut: "srgb", palette: primitives } }) } : {}
897
972
  };
898
973
  }
899
974
 
@@ -920,7 +995,28 @@ function emitPrimitiveVars(tokens, colorFormat, want, indent, inFamily, scoped)
920
995
  }
921
996
  return lines;
922
997
  }
923
- function getExtendedMappings(mode, colorName, overrides, active, seedShade) {
998
+ var WIDE_GAMUT_QUERY = "@media (color-gamut: p3)";
999
+ function emitWideGamutBlock(tokens, inFamily) {
1000
+ if (!tokens.p3) return [];
1001
+ const lines = [];
1002
+ for (const [name, scale] of Object.entries(tokens.p3.primitives)) {
1003
+ if (typeof scale === "string" || !inFamily(name)) continue;
1004
+ lines.push(...colorScaleToCssVars(name, scale, "oklch", " "));
1005
+ }
1006
+ if (lines.length === 0) return [];
1007
+ return [
1008
+ "",
1009
+ "/* Wide gamut: the same ramps with the chroma a P3 display can show. Every",
1010
+ " semantic pairing is contrast-checked on these values and on the sRGB ones. */",
1011
+ `${WIDE_GAMUT_QUERY} {`,
1012
+ " :root {",
1013
+ ...lines,
1014
+ " }",
1015
+ "}"
1016
+ ];
1017
+ }
1018
+ function getExtendedMappings(mode, colorName, overrides, active, anchors) {
1019
+ const seedShade = familySeedShade(colorName, anchors.seedShade, anchors.seedShades);
924
1020
  return extendedBridgeShades(mode, seedShade, active, overrides?.[colorName]?.[mode]);
925
1021
  }
926
1022
  var MUTED_SHADE_MAPPINGS = {
@@ -981,13 +1077,13 @@ function emitSurfaceVars(surface, colorFormat, indent) {
981
1077
  }
982
1078
  return lines;
983
1079
  }
984
- function emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, seedShade) {
1080
+ function emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors) {
985
1081
  const lines = [];
986
1082
  const extendedSemanticNames = ["primary", "neutral", "success", "destructive", "warning"];
987
1083
  for (const name of extendedSemanticNames) {
988
1084
  if (!inFamily(name)) continue;
989
1085
  const color = tokens.semantic[mode][name];
990
- const mappings = getExtendedMappings(mode, name, shadeOverrides, active, seedShade);
1086
+ const mappings = getExtendedMappings(mode, name, shadeOverrides, active, anchors);
991
1087
  lines.push(`${indent}--${name}: var(--color-${name}-${mappings.DEFAULT});`);
992
1088
  lines.push(`${indent}--${name}-foreground: ${color._refs ? refToVar(color._refs.foreground) : formatColor(color.foreground, colorFormat)};`);
993
1089
  lines.push(`${indent}--${name}-subdued: var(--color-${name}-${mappings.subdued});`);
@@ -998,7 +1094,7 @@ function emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, act
998
1094
  for (const [name, color] of Object.entries(tokens.semantic[mode])) {
999
1095
  if (!extendedSemanticNames.includes(name) && name !== "muted" && inFamily(name)) {
1000
1096
  const ext = color;
1001
- const mappings = getExtendedMappings(mode, name, shadeOverrides, active, seedShade);
1097
+ const mappings = getExtendedMappings(mode, name, shadeOverrides, active, anchors);
1002
1098
  lines.push(`${indent}--${name}: var(--color-${name}-${mappings.DEFAULT});`);
1003
1099
  lines.push(`${indent}--${name}-foreground: ${ext._refs ? refToVar(ext._refs.foreground) : formatColor(ext.foreground, colorFormat)};`);
1004
1100
  lines.push(`${indent}--${name}-subdued: var(--color-${name}-${mappings.subdued});`);
@@ -1030,8 +1126,9 @@ function emitUtilityVars(mode, indent, active, seedShade) {
1030
1126
  }
1031
1127
  return lines;
1032
1128
  }
1033
- function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shades, families, seedShade) {
1129
+ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shades, families, seedShade, seedShades) {
1034
1130
  const lines = [];
1131
+ const anchors = { seedShade, seedShades };
1035
1132
  const active = resolveShades(shades);
1036
1133
  const want = sectionSet(sections);
1037
1134
  const scoped = !!families && families.length > 0;
@@ -1052,7 +1149,7 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1052
1149
  }
1053
1150
  if (want.has("semantic")) {
1054
1151
  if (withComments) body.push(`${indent}/* Semantic Colors */`);
1055
- body.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, seedShade));
1152
+ body.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1056
1153
  }
1057
1154
  while (body.length > 0 && body[body.length - 1] === "") body.pop();
1058
1155
  return body;
@@ -1062,6 +1159,7 @@ function exportToCss(tokens, colorFormat = "hex", shadeOverrides, sections, shad
1062
1159
  lines.push(" /* Primitive Colors */");
1063
1160
  lines.push(...emitPrimitiveVars(tokens, colorFormat, want, " ", inFamily, scoped));
1064
1161
  lines.push("}");
1162
+ lines.push(...emitWideGamutBlock(tokens, inFamily));
1065
1163
  }
1066
1164
  if (wantModes) {
1067
1165
  if (wantPrimitives) lines.push("");
@@ -1104,9 +1202,10 @@ function overrideContract() {
1104
1202
  " * Then check BOTH colour schemes. A headless browser defaults to light and",
1105
1203
  " * will report a broken dark mode as passing.",
1106
1204
  " *",
1107
- " * A --color-<name>-<step> ramp step cannot be overridden this way at all:",
1108
- " * Tailwind inlines its literal value into every utility it emits, so there",
1109
- " * is no var() left to intercept. Change the seed and regenerate instead.",
1205
+ " * Do not override a --color-<name>-<step> ramp step by hand: the contrast",
1206
+ " * search never saw it, --check cannot detect it, and Tailwind still inlines",
1207
+ " * its old value into opacity-modifier fallbacks. Change the seed and",
1208
+ " * regenerate instead.",
1110
1209
  " */"
1111
1210
  ].join("\n");
1112
1211
  }
@@ -1178,8 +1277,9 @@ function emitThemeRebinding(aliases, indent) {
1178
1277
  }
1179
1278
  return lines;
1180
1279
  }
1181
- function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, seedShade) {
1280
+ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases, want, indent, active, inFamily, scoped, anchors) {
1182
1281
  const lines = [];
1282
+ const seedShade = anchors.seedShade;
1183
1283
  if (want.has("surface") && !scoped) {
1184
1284
  lines.push(`${indent}/* Surface */`);
1185
1285
  lines.push(...emitSurfaceVars(tokens.surface[mode], colorFormat, indent));
@@ -1192,14 +1292,15 @@ function emitTailwindV4Mode(tokens, mode, colorFormat, shadeOverrides, aliases,
1192
1292
  }
1193
1293
  if (want.has("semantic")) {
1194
1294
  lines.push(`${indent}/* Semantic Colors */`);
1195
- lines.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, seedShade));
1295
+ lines.push(...emitSemanticVars(tokens, mode, colorFormat, shadeOverrides, indent, active, inFamily, scoped, anchors));
1196
1296
  }
1197
1297
  while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
1198
1298
  lines.push(...emitThemeRebinding(aliases, indent));
1199
1299
  return lines;
1200
1300
  }
1201
- function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replacePalette = true, sections, shades, families, seedShade) {
1301
+ function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replacePalette = true, sections, shades, families, seedShade, seedShades) {
1202
1302
  const lines = [];
1303
+ const anchors = { seedShade, seedShades };
1203
1304
  const active = resolveShades(shades);
1204
1305
  const want = sectionSet(sections);
1205
1306
  const scoped = !!families && families.length > 0;
@@ -1227,22 +1328,23 @@ function exportToTailwindV4(tokens, colorFormat = "hex", shadeOverrides, replace
1227
1328
  }
1228
1329
  }
1229
1330
  lines.push("}");
1331
+ if (wantPrimitives) lines.push(...emitWideGamutBlock(tokens, inFamily));
1230
1332
  if (wantModes) {
1231
1333
  lines.push("");
1232
1334
  lines.push("/* Light Mode */");
1233
1335
  lines.push(`${MODE_SELECTORS.light} {`);
1234
- lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, seedShade));
1336
+ lines.push(...emitTailwindV4Mode(tokens, "light", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
1235
1337
  lines.push("}");
1236
1338
  lines.push("");
1237
1339
  lines.push("/* Dark Mode */");
1238
1340
  lines.push(`${MODE_SELECTORS.dark} {`);
1239
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, seedShade));
1341
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
1240
1342
  lines.push("}");
1241
1343
  lines.push("");
1242
1344
  lines.push("/* System Preference: Dark Mode */");
1243
1345
  lines.push("@media (prefers-color-scheme: dark) {");
1244
1346
  lines.push(` ${MODE_SELECTORS.systemDark} {`);
1245
- lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, seedShade));
1347
+ lines.push(...emitTailwindV4Mode(tokens, "dark", colorFormat, shadeOverrides, aliases, want, " ", active, inFamily, scoped, anchors));
1246
1348
  lines.push(" }");
1247
1349
  lines.push("}");
1248
1350
  }
@@ -1453,6 +1555,12 @@ function selectTokenSections(tokens, sections, families) {
1453
1555
  }
1454
1556
  if (want.has("surface") && !scoped) out.surface = tokens.surface;
1455
1557
  if (want.has("utility") && !scoped) out.utility = tokens.utility;
1558
+ if (tokens.p3) {
1559
+ const wide = selectTokenSections({ ...tokens, ...tokens.p3, p3: void 0 }, sections, families);
1560
+ out.p3 = Object.fromEntries(
1561
+ ["primitives", "semantic", "surface", "utility"].filter((tier) => wide[tier] !== void 0).map((tier) => [tier, wide[tier]])
1562
+ );
1563
+ }
1456
1564
  return out;
1457
1565
  }
1458
1566
  function exportTokens(tokens, format, options) {
@@ -1463,6 +1571,7 @@ function exportTokens(tokens, format, options) {
1463
1571
  const shades = options?.shades;
1464
1572
  const families = options?.families;
1465
1573
  const seedShade = options?.seedShade;
1574
+ const seedShades = options?.seedShades;
1466
1575
  if (families && families.length > 0 && !SECTIONED_FORMATS.includes(format)) {
1467
1576
  throw new Error(
1468
1577
  `Format "${format}" cannot be scoped to colour families; supported: ${SECTIONED_FORMATS.join(", ")}`
@@ -1475,11 +1584,11 @@ function exportTokens(tokens, format, options) {
1475
1584
  }
1476
1585
  switch (format) {
1477
1586
  case "css":
1478
- return exportToCss(tokens, colorFormat, shadeOverrides, sections, shades, families, seedShade);
1587
+ return exportToCss(tokens, colorFormat, shadeOverrides, sections, shades, families, seedShade, seedShades);
1479
1588
  case "tailwind-v3":
1480
1589
  return exportToTailwindV3(tokens, colorFormat);
1481
1590
  case "tailwind-v4":
1482
- return exportToTailwindV4(tokens, colorFormat, shadeOverrides, replacePalette, sections, shades, families, seedShade);
1591
+ return exportToTailwindV4(tokens, colorFormat, shadeOverrides, replacePalette, sections, shades, families, seedShade, seedShades);
1483
1592
  case "dtcg":
1484
1593
  return exportToDtcg(tokens);
1485
1594
  default:
@@ -1502,7 +1611,7 @@ function walk(css, onDeclaration) {
1502
1611
  const trimmed = line.trim();
1503
1612
  const declaration = /^(--[a-z0-9-]+)\s*:\s*(.+?);\s*$/i.exec(trimmed);
1504
1613
  if (declaration && stack.length > 0) {
1505
- onDeclaration(line, index, stack[stack.length - 1], declaration[1], declaration[2]);
1614
+ onDeclaration(line, index, stack.join(" > "), declaration[1], declaration[2]);
1506
1615
  }
1507
1616
  for (const char of trimmed) {
1508
1617
  if (char === "{") {
@@ -1663,8 +1772,10 @@ export {
1663
1772
  snapShade,
1664
1773
  reanchorFactors,
1665
1774
  chromaShadeFor,
1775
+ isInGamut,
1666
1776
  parseToOklch,
1667
1777
  oklchToHex,
1778
+ formatOklchInGamut,
1668
1779
  generateColorScale,
1669
1780
  generateColorScaleAPCA,
1670
1781
  adjustLightness,
@@ -1683,6 +1794,7 @@ export {
1683
1794
  DEFAULT_NEUTRAL_COLOR,
1684
1795
  ALIAS_PAIRS,
1685
1796
  aliasOf,
1797
+ familySeedShade,
1686
1798
  generatePrimitivePalette,
1687
1799
  getShade,
1688
1800
  extendedBridgeShades,
@@ -1696,6 +1808,7 @@ export {
1696
1808
  checkRampChroma,
1697
1809
  computeAccessibilityScore,
1698
1810
  generateTokens,
1811
+ WIDE_GAMUT_QUERY,
1699
1812
  exportToCss,
1700
1813
  overrideContract,
1701
1814
  TOKEN_SECTIONS,