@tenphi/glaze 0.0.0-snapshot.99c649d → 0.0.0-snapshot.9ff0fda

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.
package/dist/index.mjs CHANGED
@@ -79,8 +79,8 @@ const OKLab_to_linear_sRGB_coefficients = [
79
79
  .73956515,
80
80
  -.45954404,
81
81
  .08285427,
82
- .12541073,
83
- -.14503204
82
+ .1254107,
83
+ .14503204
84
84
  ]],
85
85
  [[.13110757611180954, 1.813339709266608], [
86
86
  1.35733652,
@@ -252,10 +252,9 @@ const getCs = (L, a, b, cusp) => {
252
252
  ];
253
253
  };
254
254
  /**
255
- * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to linear sRGB.
256
- * Channels may exceed [0, 1] near gamut boundaries — caller must clamp if needed.
255
+ * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLab [L, a, b].
257
256
  */
258
- function okhslToLinearSrgb(h, s, l) {
257
+ function okhslToOklab(h, s, l) {
259
258
  const L = toeInv(l);
260
259
  let a = 0;
261
260
  let b = 0;
@@ -282,11 +281,18 @@ function okhslToLinearSrgb(h, s, l) {
282
281
  a = c * a_;
283
282
  b = c * b_;
284
283
  }
285
- return OKLabToLinearSRGB([
284
+ return [
286
285
  L,
287
286
  a,
288
287
  b
289
- ]);
288
+ ];
289
+ }
290
+ /**
291
+ * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to linear sRGB.
292
+ * Channels may exceed [0, 1] near gamut boundaries — caller must clamp if needed.
293
+ */
294
+ function okhslToLinearSrgb(h, s, l) {
295
+ return OKLabToLinearSRGB(okhslToOklab(h, s, l));
290
296
  }
291
297
  /**
292
298
  * Compute relative luminance Y from linear sRGB channels.
@@ -325,40 +331,15 @@ function okhslToSrgb(h, s, l) {
325
331
  ];
326
332
  }
327
333
  /**
328
- * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLab [L, a, b].
334
+ * Compute WCAG 2 relative luminance from linear sRGB, matching the browser
335
+ * rendering pipeline: gamma-encode, clamp to sRGB gamut [0,1], then linearize.
336
+ * This avoids over/under-estimating luminance for out-of-gamut OKHSL colors.
329
337
  */
330
- function okhslToOklab(h, s, l) {
331
- const L = toeInv(l);
332
- let a = 0;
333
- let b = 0;
334
- const hNorm = constrainAngle(h) / 360;
335
- if (L !== 0 && L !== 1 && s !== 0) {
336
- const a_ = Math.cos(TAU * hNorm);
337
- const b_ = Math.sin(TAU * hNorm);
338
- const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
339
- const mid = .8;
340
- const midInv = 1.25;
341
- let t, k0, k1, k2;
342
- if (s < mid) {
343
- t = midInv * s;
344
- k0 = 0;
345
- k1 = mid * c0;
346
- k2 = 1 - k1 / cMid;
347
- } else {
348
- t = 5 * (s - .8);
349
- k0 = cMid;
350
- k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
351
- k2 = 1 - k1 / (cMax - cMid);
352
- }
353
- const c = k0 + t * k1 / (1 - k2 * t);
354
- a = c * a_;
355
- b = c * b_;
356
- }
357
- return [
358
- L,
359
- a,
360
- b
361
- ];
338
+ function gamutClampedLuminance(linearRgb) {
339
+ const r = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[0]))));
340
+ const g = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[1]))));
341
+ const b = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2]))));
342
+ return .2126 * r + .7152 * g + .0722 * b;
362
343
  }
363
344
  const linearSrgbToOklab = (rgb) => {
364
345
  return transform(cbrt3(transform(rgb, linear_sRGB_to_LMS_M)), LMS_to_OKLab_M);
@@ -447,15 +428,16 @@ function fmt$1(value, decimals) {
447
428
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
448
429
  */
449
430
  function formatOkhsl(h, s, l) {
450
- return `okhsl(${fmt$1(h, 1)} ${fmt$1(s, 1)}% ${fmt$1(l, 1)}%)`;
431
+ return `okhsl(${fmt$1(h, 2)} ${fmt$1(s, 2)}% ${fmt$1(l, 2)}%)`;
451
432
  }
452
433
  /**
453
- * Format OKHSL values as a CSS `rgb(R G B)` string with rounded integer values.
434
+ * Format OKHSL values as a CSS `rgb(R G B)` string.
435
+ * Uses 2 decimal places to avoid 8-bit quantization contrast loss.
454
436
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
455
437
  */
456
438
  function formatRgb(h, s, l) {
457
439
  const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
458
- return `rgb(${Math.round(r * 255)} ${Math.round(g * 255)} ${Math.round(b * 255)})`;
440
+ return `rgb(${parseFloat((r * 255).toFixed(2))} ${parseFloat((g * 255).toFixed(2))} ${parseFloat((b * 255).toFixed(2))})`;
459
441
  }
460
442
  /**
461
443
  * Format OKHSL values as a CSS `hsl(H S% L%)` string.
@@ -475,7 +457,7 @@ function formatHsl(h, s, l) {
475
457
  else if (max === g) hh = ((b - r) / delta + 2) * 60;
476
458
  else hh = ((r - g) / delta + 4) * 60;
477
459
  }
478
- return `hsl(${fmt$1(hh, 1)} ${fmt$1(ss * 100, 1)}% ${fmt$1(ll * 100, 1)}%)`;
460
+ return `hsl(${fmt$1(hh, 2)} ${fmt$1(ss * 100, 2)}% ${fmt$1(ll * 100, 2)}%)`;
479
461
  }
480
462
  /**
481
463
  * Format OKHSL values as a CSS `oklch(L C H)` string.
@@ -486,7 +468,7 @@ function formatOklch(h, s, l) {
486
468
  const C = Math.sqrt(a * a + b * b);
487
469
  let hh = Math.atan2(b, a) * (180 / Math.PI);
488
470
  hh = constrainAngle(hh);
489
- return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 1)})`;
471
+ return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 2)})`;
490
472
  }
491
473
 
492
474
  //#endregion
@@ -511,17 +493,6 @@ function resolveMinContrast(value) {
511
493
  const CACHE_SIZE = 512;
512
494
  const luminanceCache = /* @__PURE__ */ new Map();
513
495
  const cacheOrder = [];
514
- /**
515
- * Compute WCAG 2 relative luminance from linear sRGB, matching the browser
516
- * rendering pipeline: gamma-encode, clamp to sRGB gamut [0,1], then linearize.
517
- * This avoids over/under-estimating luminance for out-of-gamut OKHSL colors.
518
- */
519
- function gamutClampedLuminance(linearRgb) {
520
- const r = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[0]))));
521
- const g = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[1]))));
522
- const b = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2]))));
523
- return .2126 * r + .7152 * g + .0722 * b;
524
- }
525
496
  function cachedLuminance(h, s, l) {
526
497
  const lRounded = Math.round(l * 1e4) / 1e4;
527
498
  const key = `${h}|${s}|${lRounded}`;
@@ -647,10 +618,10 @@ function coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter) {
647
618
  function findLightnessForContrast(options) {
648
619
  const { hue, saturation, preferredLightness, baseLinearRgb, contrast: contrastInput, lightnessRange = [0, 1], epsilon = 1e-4, maxIterations = 14 } = options;
649
620
  const target = resolveMinContrast(contrastInput);
650
- const searchTarget = target + .02;
621
+ const searchTarget = target * 1.007;
651
622
  const yBase = gamutClampedLuminance(baseLinearRgb);
652
623
  const crPref = contrastRatioFromLuminance(cachedLuminance(hue, saturation, preferredLightness), yBase);
653
- if (crPref >= target) return {
624
+ if (crPref >= searchTarget) return {
654
625
  lightness: preferredLightness,
655
626
  contrast: crPref,
656
627
  met: true,
@@ -699,6 +670,135 @@ function findLightnessForContrast(options) {
699
670
  candidates.sort((a, b) => b.contrast - a.contrast);
700
671
  return candidates[0];
701
672
  }
673
+ /**
674
+ * Binary-search one branch [lo, hi] for the nearest passing mix value
675
+ * to `preferred`.
676
+ */
677
+ function searchMixBranch(lo, hi, yBase, target, epsilon, maxIter, preferred, luminanceAt) {
678
+ const crLo = contrastRatioFromLuminance(luminanceAt(lo), yBase);
679
+ const crHi = contrastRatioFromLuminance(luminanceAt(hi), yBase);
680
+ if (crLo < target && crHi < target) {
681
+ if (crLo >= crHi) return {
682
+ lightness: lo,
683
+ contrast: crLo,
684
+ met: false
685
+ };
686
+ return {
687
+ lightness: hi,
688
+ contrast: crHi,
689
+ met: false
690
+ };
691
+ }
692
+ let low = lo;
693
+ let high = hi;
694
+ for (let i = 0; i < maxIter; i++) {
695
+ if (high - low < epsilon) break;
696
+ const mid = (low + high) / 2;
697
+ if (contrastRatioFromLuminance(luminanceAt(mid), yBase) >= target) if (mid < preferred) low = mid;
698
+ else high = mid;
699
+ else if (mid < preferred) high = mid;
700
+ else low = mid;
701
+ }
702
+ const crLow = contrastRatioFromLuminance(luminanceAt(low), yBase);
703
+ const crHigh = contrastRatioFromLuminance(luminanceAt(high), yBase);
704
+ const lowPasses = crLow >= target;
705
+ const highPasses = crHigh >= target;
706
+ if (lowPasses && highPasses) {
707
+ if (Math.abs(low - preferred) <= Math.abs(high - preferred)) return {
708
+ lightness: low,
709
+ contrast: crLow,
710
+ met: true
711
+ };
712
+ return {
713
+ lightness: high,
714
+ contrast: crHigh,
715
+ met: true
716
+ };
717
+ }
718
+ if (lowPasses) return {
719
+ lightness: low,
720
+ contrast: crLow,
721
+ met: true
722
+ };
723
+ if (highPasses) return {
724
+ lightness: high,
725
+ contrast: crHigh,
726
+ met: true
727
+ };
728
+ return crLow >= crHigh ? {
729
+ lightness: low,
730
+ contrast: crLow,
731
+ met: false
732
+ } : {
733
+ lightness: high,
734
+ contrast: crHigh,
735
+ met: false
736
+ };
737
+ }
738
+ /**
739
+ * Find the mix parameter (ratio or opacity) that satisfies a WCAG 2 contrast
740
+ * target against a base color, staying as close to `preferredValue` as possible.
741
+ */
742
+ function findValueForMixContrast(options) {
743
+ const { preferredValue, baseLinearRgb, contrast: contrastInput, luminanceAtValue, epsilon = 1e-4, maxIterations = 20 } = options;
744
+ const target = resolveMinContrast(contrastInput);
745
+ const searchTarget = target * 1.01;
746
+ const yBase = gamutClampedLuminance(baseLinearRgb);
747
+ const crPref = contrastRatioFromLuminance(luminanceAtValue(preferredValue), yBase);
748
+ if (crPref >= searchTarget) return {
749
+ value: preferredValue,
750
+ contrast: crPref,
751
+ met: true
752
+ };
753
+ const darkerResult = preferredValue > 0 ? searchMixBranch(0, preferredValue, yBase, searchTarget, epsilon, maxIterations, preferredValue, luminanceAtValue) : null;
754
+ const lighterResult = preferredValue < 1 ? searchMixBranch(preferredValue, 1, yBase, searchTarget, epsilon, maxIterations, preferredValue, luminanceAtValue) : null;
755
+ if (darkerResult) darkerResult.met = darkerResult.contrast >= target;
756
+ if (lighterResult) lighterResult.met = lighterResult.contrast >= target;
757
+ const darkerPasses = darkerResult?.met ?? false;
758
+ const lighterPasses = lighterResult?.met ?? false;
759
+ if (darkerPasses && lighterPasses) {
760
+ if (Math.abs(darkerResult.lightness - preferredValue) <= Math.abs(lighterResult.lightness - preferredValue)) return {
761
+ value: darkerResult.lightness,
762
+ contrast: darkerResult.contrast,
763
+ met: true
764
+ };
765
+ return {
766
+ value: lighterResult.lightness,
767
+ contrast: lighterResult.contrast,
768
+ met: true
769
+ };
770
+ }
771
+ if (darkerPasses) return {
772
+ value: darkerResult.lightness,
773
+ contrast: darkerResult.contrast,
774
+ met: true
775
+ };
776
+ if (lighterPasses) return {
777
+ value: lighterResult.lightness,
778
+ contrast: lighterResult.contrast,
779
+ met: true
780
+ };
781
+ const candidates = [];
782
+ if (darkerResult) candidates.push({
783
+ ...darkerResult,
784
+ branch: "lower"
785
+ });
786
+ if (lighterResult) candidates.push({
787
+ ...lighterResult,
788
+ branch: "upper"
789
+ });
790
+ if (candidates.length === 0) return {
791
+ value: preferredValue,
792
+ contrast: crPref,
793
+ met: false
794
+ };
795
+ candidates.sort((a, b) => b.contrast - a.contrast);
796
+ return {
797
+ value: candidates[0].lightness,
798
+ contrast: candidates[0].contrast,
799
+ met: candidates[0].met
800
+ };
801
+ }
702
802
 
703
803
  //#endregion
704
804
  //#region src/glaze.ts
@@ -712,6 +812,7 @@ let globalConfig = {
712
812
  lightLightness: [10, 100],
713
813
  darkLightness: [15, 95],
714
814
  darkDesaturation: .1,
815
+ darkCurve: .5,
715
816
  states: {
716
817
  dark: "@dark",
717
818
  highContrast: "@high-contrast"
@@ -730,6 +831,9 @@ function pairHC(p) {
730
831
  function isShadowDef(def) {
731
832
  return def.type === "shadow";
732
833
  }
834
+ function isMixDef(def) {
835
+ return def.type === "mix";
836
+ }
733
837
  const DEFAULT_SHADOW_TUNING = {
734
838
  saturationFactor: .18,
735
839
  maxSaturation: .25,
@@ -797,6 +901,13 @@ function validateColorDefs(defs) {
797
901
  }
798
902
  continue;
799
903
  }
904
+ if (isMixDef(def)) {
905
+ if (!names.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
906
+ if (!names.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
907
+ if (isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
908
+ if (isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
909
+ continue;
910
+ }
800
911
  const regDef = def;
801
912
  if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
802
913
  if (regDef.lightness !== void 0 && !isAbsoluteLightness(regDef.lightness) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "lightness" without "base".`);
@@ -815,6 +926,9 @@ function validateColorDefs(defs) {
815
926
  if (isShadowDef(def)) {
816
927
  dfs(def.bg);
817
928
  if (def.fg) dfs(def.fg);
929
+ } else if (isMixDef(def)) {
930
+ dfs(def.base);
931
+ dfs(def.target);
818
932
  } else {
819
933
  const regDef = def;
820
934
  if (regDef.base) dfs(regDef.base);
@@ -834,6 +948,9 @@ function topoSort(defs) {
834
948
  if (isShadowDef(def)) {
835
949
  visit(def.bg);
836
950
  if (def.fg) visit(def.fg);
951
+ } else if (isMixDef(def)) {
952
+ visit(def.base);
953
+ visit(def.target);
837
954
  } else {
838
955
  const regDef = def;
839
956
  if (regDef.base) visit(regDef.base);
@@ -843,21 +960,44 @@ function topoSort(defs) {
843
960
  for (const name of Object.keys(defs)) visit(name);
844
961
  return result;
845
962
  }
846
- function mapLightnessLight(l, mode) {
963
+ function lightnessWindow(isHighContrast, kind) {
964
+ if (isHighContrast) return [0, 100];
965
+ return kind === "dark" ? globalConfig.darkLightness : globalConfig.lightLightness;
966
+ }
967
+ function mapLightnessLight(l, mode, isHighContrast) {
847
968
  if (mode === "static") return l;
848
- const [lo, hi] = globalConfig.lightLightness;
969
+ const [lo, hi] = lightnessWindow(isHighContrast, "light");
849
970
  return l * (hi - lo) / 100 + lo;
850
971
  }
851
- function mapLightnessDark(l, mode) {
972
+ function mobiusCurve(t, beta) {
973
+ if (beta >= 1) return t;
974
+ return t / (t + beta * (1 - t));
975
+ }
976
+ function mapLightnessDark(l, mode, isHighContrast) {
852
977
  if (mode === "static") return l;
853
- const [lo, hi] = globalConfig.darkLightness;
854
- if (mode === "fixed") return l * (hi - lo) / 100 + lo;
855
- return (100 - l) * (hi - lo) / 100 + lo;
978
+ const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
979
+ const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
980
+ if (mode === "fixed") return l * (darkHi - darkLo) / 100 + darkLo;
981
+ const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
982
+ const t = (lightHi - (l * (lightHi - lightLo) / 100 + lightLo)) / (lightHi - lightLo);
983
+ return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
984
+ }
985
+ function lightMappedToDark(lightL, isHighContrast) {
986
+ const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
987
+ const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
988
+ const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
989
+ const t = (lightHi - clamp(lightL, lightLo, lightHi)) / (lightHi - lightLo);
990
+ return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
856
991
  }
857
992
  function mapSaturationDark(s, mode) {
858
993
  if (mode === "static") return s;
859
994
  return s * (1 - globalConfig.darkDesaturation);
860
995
  }
996
+ function schemeLightnessRange(isDark, mode, isHighContrast) {
997
+ if (mode === "static") return [0, 1];
998
+ const [lo, hi] = lightnessWindow(isHighContrast, isDark ? "dark" : "light");
999
+ return [lo / 100, hi / 100];
1000
+ }
861
1001
  function clamp(v, min, max) {
862
1002
  return Math.max(min, Math.min(max, v));
863
1003
  }
@@ -914,24 +1054,26 @@ function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effective
914
1054
  else {
915
1055
  const parsed = parseRelativeOrAbsolute(isHighContrast ? pairHC(rawLightness) : pairNormal(rawLightness));
916
1056
  if (parsed.relative) {
917
- let delta = parsed.value;
918
- if (isDark && mode === "auto") delta = -delta;
919
- preferredL = clamp(baseL + delta, 0, 100);
920
- } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode);
921
- else preferredL = clamp(parsed.value, 0, 100);
1057
+ const delta = parsed.value;
1058
+ if (isDark && mode === "auto") preferredL = lightMappedToDark(clamp(getSchemeVariant(baseResolved, false, isHighContrast).l * 100 + delta, 0, 100), isHighContrast);
1059
+ else preferredL = clamp(baseL + delta, 0, 100);
1060
+ } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode, isHighContrast);
1061
+ else preferredL = mapLightnessLight(parsed.value, mode, isHighContrast);
922
1062
  }
923
1063
  const rawContrast = def.contrast;
924
1064
  if (rawContrast !== void 0) {
925
1065
  const minCr = isHighContrast ? pairHC(rawContrast) : pairNormal(rawContrast);
926
1066
  const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode) : satFactor * ctx.saturation / 100;
927
1067
  const baseLinearRgb = okhslToLinearSrgb(baseVariant.h, baseVariant.s, baseVariant.l);
1068
+ const windowRange = schemeLightnessRange(isDark, mode, isHighContrast);
928
1069
  return {
929
1070
  l: findLightnessForContrast({
930
1071
  hue: effectiveHue,
931
1072
  saturation: effectiveSat,
932
- preferredLightness: preferredL / 100,
1073
+ preferredLightness: clamp(preferredL / 100, windowRange[0], windowRange[1]),
933
1074
  baseLinearRgb,
934
- contrast: minCr
1075
+ contrast: minCr,
1076
+ lightnessRange: [0, 1]
935
1077
  }).lightness * 100,
936
1078
  satFactor
937
1079
  };
@@ -949,6 +1091,7 @@ function getSchemeVariant(color, isDark, isHighContrast) {
949
1091
  }
950
1092
  function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
951
1093
  if (isShadowDef(def)) return resolveShadowForScheme(def, ctx, isDark, isHighContrast);
1094
+ if (isMixDef(def)) return resolveMixForScheme(def, ctx, isDark, isHighContrast);
952
1095
  const regDef = def;
953
1096
  const mode = regDef.mode ?? "auto";
954
1097
  const isRoot = isAbsoluteLightness(regDef.lightness) && !regDef.base;
@@ -967,13 +1110,13 @@ function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
967
1110
  let finalL;
968
1111
  let finalSat;
969
1112
  if (isDark && isRoot) {
970
- finalL = mapLightnessDark(lightL, mode);
1113
+ finalL = mapLightnessDark(lightL, mode, isHighContrast);
971
1114
  finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
972
1115
  } else if (isDark && !isRoot) {
973
1116
  finalL = lightL;
974
1117
  finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
975
1118
  } else if (isRoot) {
976
- finalL = mapLightnessLight(lightL, mode);
1119
+ finalL = mapLightnessLight(lightL, mode, isHighContrast);
977
1120
  finalSat = satFactor * ctx.saturation / 100;
978
1121
  } else {
979
1122
  finalL = lightL;
@@ -994,6 +1137,83 @@ function resolveShadowForScheme(def, ctx, isDark, isHighContrast) {
994
1137
  const tuning = resolveShadowTuning(def.tuning);
995
1138
  return computeShadow(bgVariant, fgVariant, intensity, tuning);
996
1139
  }
1140
+ function variantToLinearRgb(v) {
1141
+ return okhslToLinearSrgb(v.h, v.s, v.l);
1142
+ }
1143
+ /**
1144
+ * Resolve hue for OKHSL mixing, handling achromatic colors.
1145
+ * When one color has no saturation, its hue is meaningless —
1146
+ * use the hue from the color that has saturation (matches CSS
1147
+ * color-mix "missing component" behavior).
1148
+ */
1149
+ function mixHue(base, target, t) {
1150
+ const SAT_EPSILON = 1e-6;
1151
+ const baseHasSat = base.s > SAT_EPSILON;
1152
+ const targetHasSat = target.s > SAT_EPSILON;
1153
+ if (baseHasSat && targetHasSat) return circularLerp(base.h, target.h, t);
1154
+ if (targetHasSat) return target.h;
1155
+ return base.h;
1156
+ }
1157
+ function linearSrgbLerp(base, target, t) {
1158
+ return [
1159
+ base[0] + (target[0] - base[0]) * t,
1160
+ base[1] + (target[1] - base[1]) * t,
1161
+ base[2] + (target[2] - base[2]) * t
1162
+ ];
1163
+ }
1164
+ function linearRgbToVariant(rgb) {
1165
+ const [h, s, l] = srgbToOkhsl([
1166
+ Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[0]))),
1167
+ Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[1]))),
1168
+ Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[2])))
1169
+ ]);
1170
+ return {
1171
+ h,
1172
+ s,
1173
+ l,
1174
+ alpha: 1
1175
+ };
1176
+ }
1177
+ function resolveMixForScheme(def, ctx, isDark, isHighContrast) {
1178
+ const baseResolved = ctx.resolved.get(def.base);
1179
+ const targetResolved = ctx.resolved.get(def.target);
1180
+ const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
1181
+ const targetVariant = getSchemeVariant(targetResolved, isDark, isHighContrast);
1182
+ let t = clamp(isHighContrast ? pairHC(def.value) : pairNormal(def.value), 0, 100) / 100;
1183
+ const blend = def.blend ?? "opaque";
1184
+ const space = def.space ?? "okhsl";
1185
+ const baseLinear = variantToLinearRgb(baseVariant);
1186
+ const targetLinear = variantToLinearRgb(targetVariant);
1187
+ if (def.contrast !== void 0) {
1188
+ const minCr = isHighContrast ? pairHC(def.contrast) : pairNormal(def.contrast);
1189
+ let luminanceAt;
1190
+ if (blend === "transparent") luminanceAt = (v) => gamutClampedLuminance(linearSrgbLerp(baseLinear, targetLinear, v));
1191
+ else if (space === "srgb") luminanceAt = (v) => gamutClampedLuminance(linearSrgbLerp(baseLinear, targetLinear, v));
1192
+ else luminanceAt = (v) => {
1193
+ return gamutClampedLuminance(okhslToLinearSrgb(mixHue(baseVariant, targetVariant, v), baseVariant.s + (targetVariant.s - baseVariant.s) * v, baseVariant.l + (targetVariant.l - baseVariant.l) * v));
1194
+ };
1195
+ t = findValueForMixContrast({
1196
+ preferredValue: t,
1197
+ baseLinearRgb: baseLinear,
1198
+ targetLinearRgb: targetLinear,
1199
+ contrast: minCr,
1200
+ luminanceAtValue: luminanceAt
1201
+ }).value;
1202
+ }
1203
+ if (blend === "transparent") return {
1204
+ h: targetVariant.h,
1205
+ s: targetVariant.s,
1206
+ l: targetVariant.l,
1207
+ alpha: clamp(t, 0, 1)
1208
+ };
1209
+ if (space === "srgb") return linearRgbToVariant(linearSrgbLerp(baseLinear, targetLinear, t));
1210
+ return {
1211
+ h: mixHue(baseVariant, targetVariant, t),
1212
+ s: clamp(baseVariant.s + (targetVariant.s - baseVariant.s) * t, 0, 1),
1213
+ l: clamp(baseVariant.l + (targetVariant.l - baseVariant.l) * t, 0, 1),
1214
+ alpha: 1
1215
+ };
1216
+ }
997
1217
  function resolveAllColors(hue, saturation, defs) {
998
1218
  validateColorDefs(defs);
999
1219
  const order = topoSort(defs);
@@ -1004,7 +1224,8 @@ function resolveAllColors(hue, saturation, defs) {
1004
1224
  resolved: /* @__PURE__ */ new Map()
1005
1225
  };
1006
1226
  function defMode(def) {
1007
- return isShadowDef(def) ? void 0 : def.mode ?? "auto";
1227
+ if (isShadowDef(def) || isMixDef(def)) return void 0;
1228
+ return def.mode ?? "auto";
1008
1229
  }
1009
1230
  const lightMap = /* @__PURE__ */ new Map();
1010
1231
  for (const name of order) {
@@ -1217,35 +1438,88 @@ function createTheme(hue, saturation, initialColors) {
1217
1438
  }
1218
1439
  };
1219
1440
  }
1220
- function resolvePrefix(options, themeName) {
1221
- if (options?.prefix === true) return `${themeName}-`;
1222
- if (typeof options?.prefix === "object" && options.prefix !== null) return options.prefix[themeName] ?? `${themeName}-`;
1441
+ function resolvePrefix(options, themeName, defaultPrefix = false) {
1442
+ const prefix = options?.prefix ?? defaultPrefix;
1443
+ if (prefix === true) return `${themeName}-`;
1444
+ if (typeof prefix === "object" && prefix !== null) return prefix[themeName] ?? `${themeName}-`;
1223
1445
  return "";
1224
1446
  }
1225
- function createPalette(themes) {
1447
+ function validatePrimaryTheme(primary, themes) {
1448
+ if (primary !== void 0 && !(primary in themes)) {
1449
+ const available = Object.keys(themes).join(", ");
1450
+ throw new Error(`glaze: primary theme "${primary}" not found in palette. Available: ${available}.`);
1451
+ }
1452
+ }
1453
+ /**
1454
+ * Resolve the effective primary for an export call.
1455
+ * `false` disables, a string overrides, `undefined` inherits from palette.
1456
+ */
1457
+ function resolveEffectivePrimary(exportPrimary, palettePrimary) {
1458
+ if (exportPrimary === false) return void 0;
1459
+ return exportPrimary ?? palettePrimary;
1460
+ }
1461
+ /**
1462
+ * Filter a resolved color map, skipping keys already in `seen`.
1463
+ * Warns on collision and keeps the first-written value (first-write-wins).
1464
+ * Returns a new map containing only non-colliding entries.
1465
+ */
1466
+ function filterCollisions(resolved, prefix, seen, themeName, isPrimary) {
1467
+ const filtered = /* @__PURE__ */ new Map();
1468
+ const label = isPrimary ? `${themeName} (primary)` : themeName;
1469
+ for (const [name, color] of resolved) {
1470
+ const key = `${prefix}${name}`;
1471
+ if (seen.has(key)) {
1472
+ console.warn(`glaze: token "${key}" from theme "${label}" collides with theme "${seen.get(key)}" — skipping.`);
1473
+ continue;
1474
+ }
1475
+ seen.set(key, label);
1476
+ filtered.set(name, color);
1477
+ }
1478
+ return filtered;
1479
+ }
1480
+ function createPalette(themes, paletteOptions) {
1481
+ validatePrimaryTheme(paletteOptions?.primary, themes);
1226
1482
  return {
1227
1483
  tokens(options) {
1484
+ const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1485
+ if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
1228
1486
  const modes = resolveModes(options?.modes);
1229
1487
  const allTokens = {};
1488
+ const seen = /* @__PURE__ */ new Map();
1230
1489
  for (const [themeName, theme] of Object.entries(themes)) {
1231
- const tokens = buildFlatTokenMap(theme.resolve(), resolvePrefix(options, themeName), modes, options?.format);
1490
+ const resolved = theme.resolve();
1491
+ const prefix = resolvePrefix(options, themeName, true);
1492
+ const tokens = buildFlatTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, modes, options?.format);
1232
1493
  for (const variant of Object.keys(tokens)) {
1233
1494
  if (!allTokens[variant]) allTokens[variant] = {};
1234
1495
  Object.assign(allTokens[variant], tokens[variant]);
1235
1496
  }
1497
+ if (themeName === effectivePrimary) {
1498
+ const unprefixed = buildFlatTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", modes, options?.format);
1499
+ for (const variant of Object.keys(unprefixed)) Object.assign(allTokens[variant], unprefixed[variant]);
1500
+ }
1236
1501
  }
1237
1502
  return allTokens;
1238
1503
  },
1239
1504
  tasty(options) {
1505
+ const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1506
+ if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
1240
1507
  const states = {
1241
1508
  dark: options?.states?.dark ?? globalConfig.states.dark,
1242
1509
  highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1243
1510
  };
1244
1511
  const modes = resolveModes(options?.modes);
1245
1512
  const allTokens = {};
1513
+ const seen = /* @__PURE__ */ new Map();
1246
1514
  for (const [themeName, theme] of Object.entries(themes)) {
1247
- const tokens = buildTokenMap(theme.resolve(), resolvePrefix(options, themeName), states, modes, options?.format);
1515
+ const resolved = theme.resolve();
1516
+ const prefix = resolvePrefix(options, themeName, true);
1517
+ const tokens = buildTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, states, modes, options?.format);
1248
1518
  Object.assign(allTokens, tokens);
1519
+ if (themeName === effectivePrimary) {
1520
+ const unprefixed = buildTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", states, modes, options?.format);
1521
+ Object.assign(allTokens, unprefixed);
1522
+ }
1249
1523
  }
1250
1524
  return allTokens;
1251
1525
  },
@@ -1256,6 +1530,8 @@ function createPalette(themes) {
1256
1530
  return result;
1257
1531
  },
1258
1532
  css(options) {
1533
+ const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1534
+ if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
1259
1535
  const suffix = options?.suffix ?? "-color";
1260
1536
  const format = options?.format ?? "rgb";
1261
1537
  const allLines = {
@@ -1264,14 +1540,26 @@ function createPalette(themes) {
1264
1540
  lightContrast: [],
1265
1541
  darkContrast: []
1266
1542
  };
1543
+ const seen = /* @__PURE__ */ new Map();
1267
1544
  for (const [themeName, theme] of Object.entries(themes)) {
1268
- const css = buildCssMap(theme.resolve(), resolvePrefix(options, themeName), suffix, format);
1545
+ const resolved = theme.resolve();
1546
+ const prefix = resolvePrefix(options, themeName, true);
1547
+ const css = buildCssMap(filterCollisions(resolved, prefix, seen, themeName), prefix, suffix, format);
1269
1548
  for (const key of [
1270
1549
  "light",
1271
1550
  "dark",
1272
1551
  "lightContrast",
1273
1552
  "darkContrast"
1274
1553
  ]) if (css[key]) allLines[key].push(css[key]);
1554
+ if (themeName === effectivePrimary) {
1555
+ const unprefixed = buildCssMap(filterCollisions(resolved, "", seen, themeName, true), "", suffix, format);
1556
+ for (const key of [
1557
+ "light",
1558
+ "dark",
1559
+ "lightContrast",
1560
+ "darkContrast"
1561
+ ]) if (unprefixed[key]) allLines[key].push(unprefixed[key]);
1562
+ }
1275
1563
  }
1276
1564
  return {
1277
1565
  light: allLines.light.join("\n"),
@@ -1331,6 +1619,7 @@ glaze.configure = function configure(config) {
1331
1619
  lightLightness: config.lightLightness ?? globalConfig.lightLightness,
1332
1620
  darkLightness: config.darkLightness ?? globalConfig.darkLightness,
1333
1621
  darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
1622
+ darkCurve: config.darkCurve ?? globalConfig.darkCurve,
1334
1623
  states: {
1335
1624
  dark: config.states?.dark ?? globalConfig.states.dark,
1336
1625
  highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
@@ -1345,8 +1634,8 @@ glaze.configure = function configure(config) {
1345
1634
  /**
1346
1635
  * Compose multiple themes into a palette.
1347
1636
  */
1348
- glaze.palette = function palette(themes) {
1349
- return createPalette(themes);
1637
+ glaze.palette = function palette(themes, options) {
1638
+ return createPalette(themes, options);
1350
1639
  };
1351
1640
  /**
1352
1641
  * Create a theme from a serialized export.
@@ -1430,6 +1719,7 @@ glaze.resetConfig = function resetConfig() {
1430
1719
  lightLightness: [10, 100],
1431
1720
  darkLightness: [15, 95],
1432
1721
  darkDesaturation: .1,
1722
+ darkCurve: .5,
1433
1723
  states: {
1434
1724
  dark: "@dark",
1435
1725
  highContrast: "@high-contrast"
@@ -1442,5 +1732,5 @@ glaze.resetConfig = function resetConfig() {
1442
1732
  };
1443
1733
 
1444
1734
  //#endregion
1445
- export { contrastRatioFromLuminance, findLightnessForContrast, formatHsl, formatOkhsl, formatOklch, formatRgb, glaze, okhslToLinearSrgb, okhslToOklab, okhslToSrgb, parseHex, relativeLuminanceFromLinearRgb, resolveMinContrast, srgbToOkhsl };
1735
+ export { contrastRatioFromLuminance, findLightnessForContrast, findValueForMixContrast, formatHsl, formatOkhsl, formatOklch, formatRgb, gamutClampedLuminance, glaze, okhslToLinearSrgb, okhslToOklab, okhslToSrgb, parseHex, relativeLuminanceFromLinearRgb, resolveMinContrast, srgbToOkhsl };
1446
1736
  //# sourceMappingURL=index.mjs.map