@tenphi/glaze 0.9.3 → 0.10.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.
package/dist/index.cjs CHANGED
@@ -346,6 +346,11 @@ function gamutClampedLuminance(linearRgb) {
346
346
  const linearSrgbToOklab = (rgb) => {
347
347
  return transform(cbrt3(transform(rgb, linear_sRGB_to_LMS_M)), LMS_to_OKLab_M);
348
348
  };
349
+ /**
350
+ * Convert OKLab to OKHSL.
351
+ * Input: [L, a, b] where L: 0–1, a/b: roughly -0.5 to 0.5.
352
+ * Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
353
+ */
349
354
  const oklabToOkhsl = (lab) => {
350
355
  const L = lab[0];
351
356
  const a = lab[1];
@@ -393,32 +398,108 @@ function srgbToOkhsl(rgb) {
393
398
  ]));
394
399
  }
395
400
  /**
401
+ * Convert CSS HSL (sRGB-based) to gamma-encoded sRGB [r, g, b] in 0–1 range.
402
+ * h: 0–360, s: 0–1, l: 0–1.
403
+ *
404
+ * Note: CSS HSL is not the same as OKHSL — it's HSL in the sRGB color space.
405
+ * Use this when parsing `hsl(...)` strings before passing to `srgbToOkhsl`.
406
+ */
407
+ function hslToSrgb(h, s, l) {
408
+ const hh = (h % 360 + 360) % 360 / 360;
409
+ const ss = clampVal(s, 0, 1);
410
+ const ll = clampVal(l, 0, 1);
411
+ if (ss === 0) return [
412
+ ll,
413
+ ll,
414
+ ll
415
+ ];
416
+ const q = ll < .5 ? ll * (1 + ss) : ll + ss - ll * ss;
417
+ const p = 2 * ll - q;
418
+ const hueToChannel = (t) => {
419
+ let tt = t;
420
+ if (tt < 0) tt += 1;
421
+ if (tt > 1) tt -= 1;
422
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
423
+ if (tt < 1 / 2) return q;
424
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
425
+ return p;
426
+ };
427
+ return [
428
+ hueToChannel(hh + 1 / 3),
429
+ hueToChannel(hh),
430
+ hueToChannel(hh - 1 / 3)
431
+ ];
432
+ }
433
+ /**
396
434
  * Parse a hex color string (#rgb or #rrggbb) to sRGB [r, g, b] in 0–1 range.
397
435
  * Returns null if the string is not a valid hex color.
436
+ *
437
+ * For 8-digit hex (`#rrggbbaa`) and 4-digit hex (`#rgba`) with alpha,
438
+ * use {@link parseHexAlpha}.
398
439
  */
399
440
  function parseHex(hex) {
441
+ const result = parseHexAlpha(hex);
442
+ if (!result || result.alpha !== void 0) return null;
443
+ return result.rgb;
444
+ }
445
+ /**
446
+ * Parse a hex color string (#rgb, #rrggbb, #rgba, or #rrggbbaa) to
447
+ * sRGB [r, g, b] in 0–1 range plus an optional alpha (0–1).
448
+ * Returns null if the string is not a valid hex color.
449
+ */
450
+ function parseHexAlpha(hex) {
400
451
  const h = hex.startsWith("#") ? hex.slice(1) : hex;
401
452
  if (h.length === 3) {
402
453
  const r = parseInt(h[0] + h[0], 16);
403
454
  const g = parseInt(h[1] + h[1], 16);
404
455
  const b = parseInt(h[2] + h[2], 16);
405
456
  if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
406
- return [
457
+ return { rgb: [
407
458
  r / 255,
408
459
  g / 255,
409
460
  b / 255
410
- ];
461
+ ] };
462
+ }
463
+ if (h.length === 4) {
464
+ const r = parseInt(h[0] + h[0], 16);
465
+ const g = parseInt(h[1] + h[1], 16);
466
+ const b = parseInt(h[2] + h[2], 16);
467
+ const a = parseInt(h[3] + h[3], 16);
468
+ if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
469
+ return {
470
+ rgb: [
471
+ r / 255,
472
+ g / 255,
473
+ b / 255
474
+ ],
475
+ alpha: a / 255
476
+ };
411
477
  }
412
478
  if (h.length === 6) {
413
479
  const r = parseInt(h.slice(0, 2), 16);
414
480
  const g = parseInt(h.slice(2, 4), 16);
415
481
  const b = parseInt(h.slice(4, 6), 16);
416
482
  if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
417
- return [
483
+ return { rgb: [
418
484
  r / 255,
419
485
  g / 255,
420
486
  b / 255
421
- ];
487
+ ] };
488
+ }
489
+ if (h.length === 8) {
490
+ const r = parseInt(h.slice(0, 2), 16);
491
+ const g = parseInt(h.slice(2, 4), 16);
492
+ const b = parseInt(h.slice(4, 6), 16);
493
+ const a = parseInt(h.slice(6, 8), 16);
494
+ if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
495
+ return {
496
+ rgb: [
497
+ r / 255,
498
+ g / 255,
499
+ b / 255
500
+ ],
501
+ alpha: a / 255
502
+ };
422
503
  }
423
504
  return null;
424
505
  }
@@ -810,6 +891,45 @@ function findValueForMixContrast(options) {
810
891
  * Generates robust light, dark, and high-contrast colors from a hue/saturation
811
892
  * seed, preserving contrast for UI pairs via explicit dependencies.
812
893
  */
894
+ /** Internal name of the user-facing standalone color in the synthesized def map. */
895
+ const STANDALONE_VALUE = "value";
896
+ /** Internal name of the hidden static-anchor seed used for relative lightness / contrast. */
897
+ const STANDALONE_SEED = "seed";
898
+ /** Internal name of an externally-resolved `GlazeColorToken` injected as a base reference. */
899
+ const STANDALONE_BASE = "externalBase";
900
+ /**
901
+ * Build the create-time scaling snapshot used when the caller did not
902
+ * pass an explicit `scaling`. All windows are snapshotted from the
903
+ * current `globalConfig` so later `glaze.configure()` calls don't
904
+ * retroactively change the resolved variants of an already-created
905
+ * token (matches the documented "frozen at create time" semantics).
906
+ *
907
+ * String value-shorthand inputs use an extended dark window
908
+ * `[globalConfig.darkLightness[0], 100]` so a totally-black input can
909
+ * Möbius-invert to totally-white in dark mode; object / tuple /
910
+ * structured inputs use `globalConfig.darkLightness` verbatim.
911
+ */
912
+ function defaultStandaloneScaling(extendDark) {
913
+ const [lo, hi] = globalConfig.darkLightness;
914
+ return {
915
+ lightLightness: false,
916
+ darkLightness: extendDark ? [lo, 100] : [lo, hi]
917
+ };
918
+ }
919
+ /** Reserved internal names that user-supplied `name` must not collide with. */
920
+ const RESERVED_STANDALONE_NAMES = new Set([
921
+ STANDALONE_VALUE,
922
+ STANDALONE_SEED,
923
+ STANDALONE_BASE
924
+ ]);
925
+ /**
926
+ * Discriminate a `GlazeColorToken` from a raw `GlazeColorValue`.
927
+ * Used to widen `base?` so it accepts either a token reference or a
928
+ * raw value (auto-wrapped into `glaze.color(value)`).
929
+ */
930
+ function isGlazeColorToken(candidate) {
931
+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) && "resolve" in candidate && typeof candidate.resolve === "function";
932
+ }
813
933
  let globalConfig = {
814
934
  lightLightness: [10, 100],
815
935
  darkLightness: [15, 95],
@@ -830,6 +950,41 @@ function pairNormal(p) {
830
950
  function pairHC(p) {
831
951
  return Array.isArray(p) ? p[1] : p;
832
952
  }
953
+ /**
954
+ * Dedupe contrast warnings within a single process. The cache survives
955
+ * the lifetime of a token because tokens memoize their resolution; the
956
+ * limit is a soft cap to keep noise bounded across long-lived sessions
957
+ * (e.g. dev servers with HMR re-resolving themes repeatedly).
958
+ */
959
+ const CONTRAST_WARN_CACHE_LIMIT = 256;
960
+ const contrastWarnCache = /* @__PURE__ */ new Set();
961
+ function schemeLabel(isDark, isHighContrast) {
962
+ if (isDark && isHighContrast) return "darkContrast";
963
+ if (isDark) return "dark";
964
+ if (isHighContrast) return "lightContrast";
965
+ return "light";
966
+ }
967
+ function formatContrastTarget(input, ratio) {
968
+ return typeof input === "string" ? `"${input}" (${ratio.toFixed(2)})` : ratio.toFixed(2);
969
+ }
970
+ /**
971
+ * Slack factor below the requested target before we emit a warning.
972
+ * The contrast solver already overshoots by `OVERSHOOT` (currently 1%)
973
+ * to absorb rounding noise (`see findLightnessForContrast` in
974
+ * `contrast-solver.ts`), so an `actual` ratio within ~2x that overshoot
975
+ * is effectively a pass and not worth nagging the user about.
976
+ */
977
+ const CONTRAST_WARN_SLACK = .98;
978
+ function warnContrastUnmet(name, isDark, isHighContrast, target, actual) {
979
+ const targetRatio = resolveMinContrast(target);
980
+ if (actual >= targetRatio * CONTRAST_WARN_SLACK) return;
981
+ const scheme = schemeLabel(isDark, isHighContrast);
982
+ const key = `${name}|${scheme}|${targetRatio.toFixed(3)}|${actual.toFixed(2)}`;
983
+ if (contrastWarnCache.has(key)) return;
984
+ if (contrastWarnCache.size >= CONTRAST_WARN_CACHE_LIMIT) contrastWarnCache.clear();
985
+ contrastWarnCache.add(key);
986
+ console.warn(`glaze: color "${name}" cannot meet contrast ${formatContrastTarget(target, targetRatio)} in ${scheme} scheme (got ${actual.toFixed(2)}). Try widening the lightness window, lowering the contrast target, or picking a base color further from this color's lightness.`);
987
+ }
833
988
  function isShadowDef(def) {
834
989
  return def.type === "shadow";
835
990
  }
@@ -891,36 +1046,38 @@ function computeShadow(bg, fg, intensity, tuning) {
891
1046
  alpha
892
1047
  };
893
1048
  }
894
- function validateColorDefs(defs) {
895
- const names = new Set(Object.keys(defs));
1049
+ function validateColorDefs(defs, externalBases) {
1050
+ const localNames = new Set(Object.keys(defs));
1051
+ const allNames = new Set([...localNames, ...externalBases ? externalBases.keys() : []]);
896
1052
  for (const [name, def] of Object.entries(defs)) {
897
1053
  if (isShadowDef(def)) {
898
- if (!names.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
899
- if (isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
1054
+ if (!allNames.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
1055
+ if (localNames.has(def.bg) && isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
900
1056
  if (def.fg !== void 0) {
901
- if (!names.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
902
- if (isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
1057
+ if (!allNames.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
1058
+ if (localNames.has(def.fg) && isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
903
1059
  }
904
1060
  continue;
905
1061
  }
906
1062
  if (isMixDef(def)) {
907
- if (!names.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
908
- if (!names.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
909
- if (isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
910
- if (isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
1063
+ if (!allNames.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
1064
+ if (!allNames.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
1065
+ if (localNames.has(def.base) && isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
1066
+ if (localNames.has(def.target) && isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
911
1067
  continue;
912
1068
  }
913
1069
  const regDef = def;
914
1070
  if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
915
1071
  if (regDef.lightness !== void 0 && !isAbsoluteLightness(regDef.lightness) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "lightness" without "base".`);
916
- if (regDef.base && !names.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
917
- if (regDef.base && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
1072
+ if (regDef.base && !allNames.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
1073
+ if (regDef.base && localNames.has(regDef.base) && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
918
1074
  if (!isAbsoluteLightness(regDef.lightness) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "lightness" (root) or "base" (dependent).`);
919
1075
  if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived lightness unpredictable.`);
920
1076
  }
921
1077
  const visited = /* @__PURE__ */ new Set();
922
1078
  const inStack = /* @__PURE__ */ new Set();
923
1079
  function dfs(name) {
1080
+ if (!localNames.has(name)) return;
924
1081
  if (inStack.has(name)) throw new Error(`glaze: circular base reference detected involving "${name}".`);
925
1082
  if (visited.has(name)) return;
926
1083
  inStack.add(name);
@@ -938,7 +1095,7 @@ function validateColorDefs(defs) {
938
1095
  inStack.delete(name);
939
1096
  visited.add(name);
940
1097
  }
941
- for (const name of names) dfs(name);
1098
+ for (const name of localNames) dfs(name);
942
1099
  }
943
1100
  function topoSort(defs) {
944
1101
  const result = [];
@@ -947,6 +1104,7 @@ function topoSort(defs) {
947
1104
  if (visited.has(name)) return;
948
1105
  visited.add(name);
949
1106
  const def = defs[name];
1107
+ if (def === void 0) return;
950
1108
  if (isShadowDef(def)) {
951
1109
  visit(def.bg);
952
1110
  if (def.fg) visit(def.fg);
@@ -962,32 +1120,43 @@ function topoSort(defs) {
962
1120
  for (const name of Object.keys(defs)) visit(name);
963
1121
  return result;
964
1122
  }
965
- function lightnessWindow(isHighContrast, kind) {
1123
+ /**
1124
+ * Resolve the active lightness window for a scheme.
1125
+ * - HC variants always return `[0, 100]` (existing behavior, predates per-call overrides).
1126
+ * - Otherwise, per-call `scaling` (e.g. from `glaze.color()`'s third arg) wins;
1127
+ * `false` is interpreted as `[0, 100]` (no remap). Falls back to `globalConfig.*Lightness`.
1128
+ */
1129
+ function lightnessWindow(isHighContrast, kind, scaling) {
966
1130
  if (isHighContrast) return [0, 100];
1131
+ if (scaling) {
1132
+ const override = kind === "dark" ? scaling.darkLightness : scaling.lightLightness;
1133
+ if (override === false) return [0, 100];
1134
+ if (override !== void 0) return override;
1135
+ }
967
1136
  return kind === "dark" ? globalConfig.darkLightness : globalConfig.lightLightness;
968
1137
  }
969
- function mapLightnessLight(l, mode, isHighContrast) {
1138
+ function mapLightnessLight(l, mode, isHighContrast, scaling) {
970
1139
  if (mode === "static") return l;
971
- const [lo, hi] = lightnessWindow(isHighContrast, "light");
1140
+ const [lo, hi] = lightnessWindow(isHighContrast, "light", scaling);
972
1141
  return l * (hi - lo) / 100 + lo;
973
1142
  }
974
1143
  function mobiusCurve(t, beta) {
975
1144
  if (beta >= 1) return t;
976
1145
  return t / (t + beta * (1 - t));
977
1146
  }
978
- function mapLightnessDark(l, mode, isHighContrast) {
1147
+ function mapLightnessDark(l, mode, isHighContrast, scaling) {
979
1148
  if (mode === "static") return l;
980
1149
  const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
981
- const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
1150
+ const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark", scaling);
982
1151
  if (mode === "fixed") return l * (darkHi - darkLo) / 100 + darkLo;
983
- const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
1152
+ const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light", scaling);
984
1153
  const t = (lightHi - (l * (lightHi - lightLo) / 100 + lightLo)) / (lightHi - lightLo);
985
1154
  return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
986
1155
  }
987
- function lightMappedToDark(lightL, isHighContrast) {
1156
+ function lightMappedToDark(lightL, isHighContrast, scaling) {
988
1157
  const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
989
- const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
990
- const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
1158
+ const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light", scaling);
1159
+ const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark", scaling);
991
1160
  const t = (lightHi - clamp(lightL, lightLo, lightHi)) / (lightHi - lightLo);
992
1161
  return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
993
1162
  }
@@ -995,9 +1164,9 @@ function mapSaturationDark(s, mode) {
995
1164
  if (mode === "static") return s;
996
1165
  return s * (1 - globalConfig.darkDesaturation);
997
1166
  }
998
- function schemeLightnessRange(isDark, mode, isHighContrast) {
1167
+ function schemeLightnessRange(isDark, mode, isHighContrast, scaling) {
999
1168
  if (mode === "static") return [0, 1];
1000
- const [lo, hi] = lightnessWindow(isHighContrast, isDark ? "dark" : "light");
1169
+ const [lo, hi] = lightnessWindow(isHighContrast, isDark ? "dark" : "light", scaling);
1001
1170
  return [lo / 100, hi / 100];
1002
1171
  }
1003
1172
  function clamp(v, min, max) {
@@ -1057,26 +1226,28 @@ function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effective
1057
1226
  const parsed = parseRelativeOrAbsolute(isHighContrast ? pairHC(rawLightness) : pairNormal(rawLightness));
1058
1227
  if (parsed.relative) {
1059
1228
  const delta = parsed.value;
1060
- if (isDark && mode === "auto") preferredL = lightMappedToDark(clamp(getSchemeVariant(baseResolved, false, isHighContrast).l * 100 + delta, 0, 100), isHighContrast);
1229
+ if (isDark && mode === "auto") preferredL = lightMappedToDark(clamp(getSchemeVariant(baseResolved, false, isHighContrast).l * 100 + delta, 0, 100), isHighContrast, ctx.scaling);
1061
1230
  else preferredL = clamp(baseL + delta, 0, 100);
1062
- } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode, isHighContrast);
1063
- else preferredL = mapLightnessLight(parsed.value, mode, isHighContrast);
1231
+ } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode, isHighContrast, ctx.scaling);
1232
+ else preferredL = mapLightnessLight(parsed.value, mode, isHighContrast, ctx.scaling);
1064
1233
  }
1065
1234
  const rawContrast = def.contrast;
1066
1235
  if (rawContrast !== void 0) {
1067
1236
  const minCr = isHighContrast ? pairHC(rawContrast) : pairNormal(rawContrast);
1068
1237
  const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode) : satFactor * ctx.saturation / 100;
1069
1238
  const baseLinearRgb = okhslToLinearSrgb(baseVariant.h, baseVariant.s, baseVariant.l);
1070
- const windowRange = schemeLightnessRange(isDark, mode, isHighContrast);
1239
+ const windowRange = schemeLightnessRange(isDark, mode, isHighContrast, ctx.scaling);
1240
+ const result = findLightnessForContrast({
1241
+ hue: effectiveHue,
1242
+ saturation: effectiveSat,
1243
+ preferredLightness: clamp(preferredL / 100, windowRange[0], windowRange[1]),
1244
+ baseLinearRgb,
1245
+ contrast: minCr,
1246
+ lightnessRange: [0, 1]
1247
+ });
1248
+ if (!result.met) warnContrastUnmet(name, isDark, isHighContrast, minCr, result.contrast);
1071
1249
  return {
1072
- l: findLightnessForContrast({
1073
- hue: effectiveHue,
1074
- saturation: effectiveSat,
1075
- preferredLightness: clamp(preferredL / 100, windowRange[0], windowRange[1]),
1076
- baseLinearRgb,
1077
- contrast: minCr,
1078
- lightnessRange: [0, 1]
1079
- }).lightness * 100,
1250
+ l: result.lightness * 100,
1080
1251
  satFactor
1081
1252
  };
1082
1253
  }
@@ -1112,13 +1283,13 @@ function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
1112
1283
  let finalL;
1113
1284
  let finalSat;
1114
1285
  if (isDark && isRoot) {
1115
- finalL = mapLightnessDark(lightL, mode, isHighContrast);
1286
+ finalL = mapLightnessDark(lightL, mode, isHighContrast, ctx.scaling);
1116
1287
  finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
1117
1288
  } else if (isDark && !isRoot) {
1118
1289
  finalL = lightL;
1119
1290
  finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
1120
1291
  } else if (isRoot) {
1121
- finalL = mapLightnessLight(lightL, mode, isHighContrast);
1292
+ finalL = mapLightnessLight(lightL, mode, isHighContrast, ctx.scaling);
1122
1293
  finalSat = satFactor * ctx.saturation / 100;
1123
1294
  } else {
1124
1295
  finalL = lightL;
@@ -1216,15 +1387,17 @@ function resolveMixForScheme(def, ctx, isDark, isHighContrast) {
1216
1387
  alpha: 1
1217
1388
  };
1218
1389
  }
1219
- function resolveAllColors(hue, saturation, defs) {
1220
- validateColorDefs(defs);
1390
+ function resolveAllColors(hue, saturation, defs, scaling, externalBases) {
1391
+ validateColorDefs(defs, externalBases);
1221
1392
  const order = topoSort(defs);
1222
1393
  const ctx = {
1223
1394
  hue,
1224
1395
  saturation,
1225
1396
  defs,
1226
- resolved: /* @__PURE__ */ new Map()
1397
+ resolved: /* @__PURE__ */ new Map(),
1398
+ scaling
1227
1399
  };
1400
+ if (externalBases) for (const [name, color] of externalBases) ctx.resolved.set(name, color);
1228
1401
  function defMode(def) {
1229
1402
  if (isShadowDef(def) || isMixDef(def)) return void 0;
1230
1403
  return def.mode ?? "auto";
@@ -1576,32 +1749,406 @@ function createPalette(themes, paletteOptions) {
1576
1749
  }
1577
1750
  };
1578
1751
  }
1579
- function createColorToken(input) {
1580
- const defs = { __color__: {
1581
- lightness: input.lightness,
1582
- saturation: input.saturationFactor,
1583
- mode: input.mode
1584
- } };
1752
+ /**
1753
+ * Matches the CSS color functions Glaze itself emits (`rgb()`, `hsl()`,
1754
+ * `okhsl()`, `oklch()`) plus their legacy alpha aliases (`rgba()`, `hsla()`).
1755
+ *
1756
+ * Only bare numeric components are supported. Named colors (`red`),
1757
+ * relative-color syntax (`from <color> ...`), and angle units other
1758
+ * than bare degrees (`deg` is the only suffix tolerated by `parseFloat`)
1759
+ * are out of scope.
1760
+ */
1761
+ const COLOR_FN_RE = /^(rgba?|hsla?|okhsl|oklch)\(\s*([^)]*)\s*\)$/i;
1762
+ function parseNumberOrPercent(raw, percentScale) {
1763
+ if (raw.endsWith("%")) return parseFloat(raw) / 100 * percentScale;
1764
+ return parseFloat(raw);
1765
+ }
1766
+ /**
1767
+ * Split the body of a CSS color function into its components and detect
1768
+ * whether an alpha channel was present.
1769
+ *
1770
+ * Handles both modern slash syntax (`R G B / A` or `R, G, B / A`) and
1771
+ * legacy comma syntax (`R, G, B, A`). The alpha value itself is discarded
1772
+ * by the caller — standalone Glaze colors have no opacity field.
1773
+ */
1774
+ function splitColorBody(body) {
1775
+ const slashIdx = body.indexOf("/");
1776
+ if (slashIdx !== -1) return {
1777
+ components: body.slice(0, slashIdx).trim().split(/[\s,]+/).filter(Boolean),
1778
+ hadAlpha: body.slice(slashIdx + 1).trim().length > 0
1779
+ };
1780
+ const components = body.split(/[\s,]+/).filter(Boolean);
1781
+ if (components.length === 4) {
1782
+ components.pop();
1783
+ return {
1784
+ components,
1785
+ hadAlpha: true
1786
+ };
1787
+ }
1788
+ return {
1789
+ components,
1790
+ hadAlpha: false
1791
+ };
1792
+ }
1793
+ function warnDroppedAlpha(input) {
1794
+ console.warn(`glaze: alpha component dropped from "${input}" (standalone color has no opacity field).`);
1795
+ }
1796
+ function parseColorString(input) {
1797
+ if (input.startsWith("#")) {
1798
+ const parsed = parseHexAlpha(input);
1799
+ if (!parsed) throw new Error(`glaze: invalid hex color "${input}".`);
1800
+ if (parsed.alpha !== void 0) warnDroppedAlpha(input);
1801
+ const [h, s, l] = srgbToOkhsl(parsed.rgb);
1802
+ return {
1803
+ h,
1804
+ s,
1805
+ l
1806
+ };
1807
+ }
1808
+ const m = input.match(COLOR_FN_RE);
1809
+ if (!m) throw new Error(`glaze: unsupported color string "${input}".`);
1810
+ const fn = m[1].toLowerCase();
1811
+ const { components, hadAlpha } = splitColorBody(m[2].trim());
1812
+ if (hadAlpha) warnDroppedAlpha(input);
1813
+ if (components.length !== 3) throw new Error(`glaze: expected 3 components in "${input}".`);
1814
+ switch (fn) {
1815
+ case "rgb":
1816
+ case "rgba": {
1817
+ const [h, s, l] = srgbToOkhsl([
1818
+ parseNumberOrPercent(components[0], 255) / 255,
1819
+ parseNumberOrPercent(components[1], 255) / 255,
1820
+ parseNumberOrPercent(components[2], 255) / 255
1821
+ ]);
1822
+ return {
1823
+ h,
1824
+ s,
1825
+ l
1826
+ };
1827
+ }
1828
+ case "hsl":
1829
+ case "hsla": {
1830
+ const [oh, os, ol] = srgbToOkhsl(hslToSrgb(parseFloat(components[0]), parseNumberOrPercent(components[1], 1), parseNumberOrPercent(components[2], 1)));
1831
+ return {
1832
+ h: oh,
1833
+ s: os,
1834
+ l: ol
1835
+ };
1836
+ }
1837
+ case "okhsl": return {
1838
+ h: parseFloat(components[0]),
1839
+ s: parseNumberOrPercent(components[1], 1),
1840
+ l: parseNumberOrPercent(components[2], 1)
1841
+ };
1842
+ case "oklch": {
1843
+ const L = parseNumberOrPercent(components[0], 1);
1844
+ const C = parseNumberOrPercent(components[1], .4);
1845
+ const hRad = parseFloat(components[2]) * Math.PI / 180;
1846
+ const [h, s, l] = oklabToOkhsl([
1847
+ L,
1848
+ C * Math.cos(hRad),
1849
+ C * Math.sin(hRad)
1850
+ ]);
1851
+ return {
1852
+ h,
1853
+ s,
1854
+ l
1855
+ };
1856
+ }
1857
+ }
1858
+ throw new Error(`glaze: unsupported color function "${fn}".`);
1859
+ }
1860
+ /**
1861
+ * Validate a user-supplied `OkhslColor`. Catches the common 0-100 vs 0-1
1862
+ * confusion (the structured form uses 0-100, OKHSL objects use 0-1).
1863
+ */
1864
+ function validateOkhslColor(value) {
1865
+ const { h, s, l } = value;
1866
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l)) throw new Error("glaze.color: OkhslColor h/s/l must be finite numbers.");
1867
+ if (s > 1.5 || l > 1.5) throw new Error("glaze.color: OkhslColor s/l must be in 0–1 range. Did you mean the structured form { hue, saturation, lightness } (which uses 0–100)?");
1868
+ }
1869
+ /**
1870
+ * Validate a user-supplied `[r, g, b]` tuple in 0-255.
1871
+ */
1872
+ function validateRgbTuple(value) {
1873
+ for (const n of value) if (!Number.isFinite(n) || n < 0 || n > 255) throw new Error(`glaze.color: RGB tuple components must be finite numbers in 0–255 (got [${value.join(", ")}]).`);
1874
+ }
1875
+ /**
1876
+ * Validate a user-supplied `opacity` override on `glaze.color()`.
1877
+ * Must be a finite number in `0..=1`.
1878
+ */
1879
+ function validateStandaloneOpacity(value) {
1880
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new Error(`glaze.color: opacity must be a finite number in 0–1 (got ${value}).`);
1881
+ }
1882
+ /**
1883
+ * Validate a structured `GlazeColorInput`. Range-checks the `hue` /
1884
+ * `saturation` / `lightness` numerics (and any HC-pair second value)
1885
+ * before the resolver sees them so out-of-range or non-finite inputs
1886
+ * fail with a helpful, top-level error rather than producing a
1887
+ * NaN-laden token. `opacity` is checked here too so all input
1888
+ * validation lives in one place.
1889
+ */
1890
+ function validateStructuredInput(input) {
1891
+ if (!Number.isFinite(input.hue)) throw new Error(`glaze.color: structured hue must be a finite number (got ${input.hue}).`);
1892
+ if (!Number.isFinite(input.saturation) || input.saturation < 0 || input.saturation > 100) throw new Error(`glaze.color: structured saturation must be a finite number in 0–100 (got ${input.saturation}).`);
1893
+ const checkLightness = (value, label) => {
1894
+ if (!Number.isFinite(value) || value < 0 || value > 100) throw new Error(`glaze.color: structured ${label} must be a finite number in 0–100 (got ${value}).`);
1895
+ };
1896
+ if (Array.isArray(input.lightness)) {
1897
+ checkLightness(input.lightness[0], "lightness[normal]");
1898
+ checkLightness(input.lightness[1], "lightness[hc]");
1899
+ } else checkLightness(input.lightness, "lightness");
1900
+ if (input.saturationFactor !== void 0) {
1901
+ if (!Number.isFinite(input.saturationFactor) || input.saturationFactor < 0 || input.saturationFactor > 1) throw new Error(`glaze.color: structured saturationFactor must be a finite number in 0–1 (got ${input.saturationFactor}).`);
1902
+ }
1903
+ if (input.opacity !== void 0) validateStandaloneOpacity(input.opacity);
1904
+ }
1905
+ /**
1906
+ * Validate a user-supplied `name` override. Rejects empty / whitespace-only
1907
+ * strings and names colliding with `glaze`'s reserved internal sentinels.
1908
+ */
1909
+ function validateStandaloneName(name) {
1910
+ if (typeof name !== "string" || name.trim() === "") throw new Error("glaze.color: name must be a non-empty string. Omit `name` if you do not want to set a debug label.");
1911
+ if (RESERVED_STANDALONE_NAMES.has(name)) {
1912
+ const reserved = [...RESERVED_STANDALONE_NAMES].map((n) => `"${n}"`).join(", ");
1913
+ throw new Error(`glaze.color: name "${name}" is reserved (used internally). Reserved names are: ${reserved}. Pick a different name.`);
1914
+ }
1915
+ }
1916
+ /**
1917
+ * Extract an OKHSL color from any `GlazeColorValue` form. Also used by
1918
+ * `glaze.shadow()` so all shadow inputs (hex, color functions, OKHSL,
1919
+ * RGB tuple) go through one parser.
1920
+ */
1921
+ function extractOkhslFromValue(value) {
1922
+ if (typeof value === "string") return parseColorString(value);
1923
+ if (Array.isArray(value)) {
1924
+ const tuple = value;
1925
+ validateRgbTuple(tuple);
1926
+ const [r, g, b] = tuple;
1927
+ const [h, s, l] = srgbToOkhsl([
1928
+ r / 255,
1929
+ g / 255,
1930
+ b / 255
1931
+ ]);
1932
+ return {
1933
+ h,
1934
+ s,
1935
+ l
1936
+ };
1937
+ }
1938
+ validateOkhslColor(value);
1939
+ return value;
1940
+ }
1941
+ /**
1942
+ * Build the `ColorMap` for a value-shorthand `glaze.color()` call.
1943
+ *
1944
+ * The user-facing color (`STANDALONE_VALUE`) defaults to `mode: 'auto'`
1945
+ * for string inputs (Möbius-inverted dark variant — pairs with the
1946
+ * extended dark window so a totally-black input renders as totally-white
1947
+ * in dark mode) and `mode: 'fixed'` for `OkhslColor` / RGB-tuple inputs
1948
+ * (linear, no inversion).
1949
+ *
1950
+ * When the user requests `contrast` or relative `lightness`, a hidden
1951
+ * `STANDALONE_SEED` def is synthesized at `mode: 'static'`. That keeps
1952
+ * the seed pinned to the literal user-provided color across all four
1953
+ * variants, so the contrast solver always anchors against it.
1954
+ */
1955
+ function buildStandaloneValueDefs(main, options, inputIsString) {
1956
+ const seedHue = typeof options?.hue === "number" ? options.hue : main.h;
1957
+ const seedSaturation = options?.saturation ?? main.s * 100;
1958
+ const relativeHue = typeof options?.hue === "string" ? options.hue : void 0;
1959
+ const lightnessOption = options?.lightness;
1960
+ const hasExternalBase = options?.base !== void 0;
1961
+ const needsSeedAnchor = !hasExternalBase && (options?.contrast !== void 0 || lightnessOption !== void 0 && !isAbsoluteLightness(lightnessOption));
1962
+ if (options?.opacity !== void 0) validateStandaloneOpacity(options.opacity);
1963
+ const userName = options?.name;
1964
+ if (userName !== void 0) validateStandaloneName(userName);
1965
+ const primary = userName ?? STANDALONE_VALUE;
1966
+ const valueDef = {
1967
+ hue: relativeHue,
1968
+ saturation: options?.saturationFactor,
1969
+ lightness: lightnessOption ?? main.l * 100,
1970
+ contrast: options?.contrast,
1971
+ mode: options?.mode ?? (inputIsString ? "auto" : "fixed"),
1972
+ opacity: options?.opacity,
1973
+ base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
1974
+ };
1975
+ const defs = { [primary]: valueDef };
1976
+ if (needsSeedAnchor) defs[STANDALONE_SEED] = {
1977
+ hue: main.h,
1978
+ saturation: 1,
1979
+ lightness: main.l * 100,
1980
+ mode: "static"
1981
+ };
1982
+ return {
1983
+ seedHue,
1984
+ seedSaturation,
1985
+ defs,
1986
+ primary
1987
+ };
1988
+ }
1989
+ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveScaling, baseToken, exportData) {
1990
+ let cached;
1991
+ const resolveOnce = () => {
1992
+ if (cached) return cached;
1993
+ cached = resolveAllColors(seedHue, seedSaturation, defs, effectiveScaling, baseToken ? new Map([[STANDALONE_BASE, baseToken.resolve()]]) : void 0);
1994
+ return cached;
1995
+ };
1996
+ const resolveStates = (options) => ({
1997
+ dark: options?.states?.dark ?? globalConfig.states.dark,
1998
+ highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1999
+ });
2000
+ const tokenLike = (options) => {
2001
+ return buildTokenMap(resolveOnce(), "", resolveStates(options), resolveModes(options?.modes), options?.format)[`#${primary}`];
2002
+ };
1585
2003
  return {
1586
2004
  resolve() {
1587
- return resolveAllColors(input.hue, input.saturation, defs).get("__color__");
2005
+ return resolveOnce().get(primary);
1588
2006
  },
1589
- token(options) {
1590
- return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1591
- dark: options?.states?.dark ?? globalConfig.states.dark,
1592
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1593
- }, resolveModes(options?.modes), options?.format)["#__color__"];
2007
+ token: tokenLike,
2008
+ tasty: tokenLike,
2009
+ json(options) {
2010
+ return buildJsonMap(resolveOnce(), resolveModes(options?.modes), options?.format)[primary];
1594
2011
  },
1595
- tasty(options) {
1596
- return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1597
- dark: options?.states?.dark ?? globalConfig.states.dark,
1598
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1599
- }, resolveModes(options?.modes), options?.format)["#__color__"];
2012
+ css(options) {
2013
+ return buildCssMap(new Map([[options.name, resolveOnce().get(primary)]]), "", options.suffix ?? "-color", options.format ?? "rgb");
1600
2014
  },
1601
- json(options) {
1602
- return buildJsonMap(resolveAllColors(input.hue, input.saturation, defs), resolveModes(options?.modes), options?.format)["__color__"];
1603
- }
2015
+ export: exportData
2016
+ };
2017
+ }
2018
+ /**
2019
+ * Resolve `base` (which may be a token reference or a raw color value)
2020
+ * into a `GlazeColorToken`. Raw values are auto-wrapped via
2021
+ * `glaze.color(value)` so they pick up the same auto-invert defaults as
2022
+ * an explicit wrap. Returns `undefined` when no base is provided.
2023
+ */
2024
+ function resolveBaseToken(base) {
2025
+ if (base === void 0) return void 0;
2026
+ if (isGlazeColorToken(base)) return base;
2027
+ return createColorTokenFromValue(base, void 0, void 0);
2028
+ }
2029
+ /**
2030
+ * Build a JSON-safe snapshot of `GlazeColorOverrides`. `base` is
2031
+ * recursively serialized when it was originally a token; raw values are
2032
+ * preserved as-is so `glaze.colorFrom(...)` round-trips them.
2033
+ */
2034
+ function buildOverridesExport(options) {
2035
+ const out = {};
2036
+ if (options.hue !== void 0) out.hue = options.hue;
2037
+ if (options.saturation !== void 0) out.saturation = options.saturation;
2038
+ if (options.lightness !== void 0) out.lightness = options.lightness;
2039
+ if (options.saturationFactor !== void 0) out.saturationFactor = options.saturationFactor;
2040
+ if (options.mode !== void 0) out.mode = options.mode;
2041
+ if (options.contrast !== void 0) out.contrast = options.contrast;
2042
+ if (options.opacity !== void 0) out.opacity = options.opacity;
2043
+ if (options.name !== void 0) out.name = options.name;
2044
+ if (options.base !== void 0) out.base = isGlazeColorToken(options.base) ? options.base.export() : options.base;
2045
+ return out;
2046
+ }
2047
+ function buildStructuredInputExport(input) {
2048
+ const out = {
2049
+ hue: input.hue,
2050
+ saturation: input.saturation,
2051
+ lightness: input.lightness
2052
+ };
2053
+ if (input.saturationFactor !== void 0) out.saturationFactor = input.saturationFactor;
2054
+ if (input.mode !== void 0) out.mode = input.mode;
2055
+ if (input.opacity !== void 0) out.opacity = input.opacity;
2056
+ if (input.contrast !== void 0) out.contrast = input.contrast;
2057
+ if (input.name !== void 0) out.name = input.name;
2058
+ if (input.base !== void 0) out.base = isGlazeColorToken(input.base) ? input.base.export() : input.base;
2059
+ return out;
2060
+ }
2061
+ function createColorToken(input, scaling) {
2062
+ validateStructuredInput(input);
2063
+ const userName = input.name;
2064
+ if (userName !== void 0) validateStandaloneName(userName);
2065
+ const primary = userName ?? STANDALONE_VALUE;
2066
+ const baseToken = resolveBaseToken(input.base);
2067
+ const hasExternalBase = baseToken !== void 0;
2068
+ const needsSeedAnchor = !hasExternalBase && input.contrast !== void 0;
2069
+ const defs = { [primary]: {
2070
+ lightness: input.lightness,
2071
+ saturation: input.saturationFactor,
2072
+ mode: input.mode ?? "fixed",
2073
+ contrast: input.contrast,
2074
+ opacity: input.opacity,
2075
+ base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
2076
+ } };
2077
+ if (needsSeedAnchor) defs[STANDALONE_SEED] = {
2078
+ lightness: pairNormal(input.lightness),
2079
+ saturation: 1,
2080
+ mode: "static"
1604
2081
  };
2082
+ const effectiveScaling = scaling ?? defaultStandaloneScaling(false);
2083
+ const exportData = () => ({
2084
+ form: "structured",
2085
+ input: buildStructuredInputExport(input),
2086
+ scaling: effectiveScaling
2087
+ });
2088
+ return createColorTokenFromDefs(input.hue, input.saturation, defs, primary, effectiveScaling, baseToken, exportData);
2089
+ }
2090
+ function createColorTokenFromValue(value, options, scaling) {
2091
+ const inputIsString = typeof value === "string";
2092
+ const main = extractOkhslFromValue(value);
2093
+ const baseToken = resolveBaseToken(options?.base);
2094
+ const { seedHue, seedSaturation, defs, primary } = buildStandaloneValueDefs(main, options, inputIsString);
2095
+ const effectiveScaling = scaling ?? defaultStandaloneScaling(inputIsString);
2096
+ const exportData = () => ({
2097
+ form: "value",
2098
+ input: value,
2099
+ ...options !== void 0 ? { overrides: buildOverridesExport(options) } : {},
2100
+ scaling: effectiveScaling
2101
+ });
2102
+ return createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveScaling, baseToken, exportData);
2103
+ }
2104
+ /**
2105
+ * Rehydrate a token from its `.export()` snapshot. Recursively rebuilds
2106
+ * any base dependency. Inverse of `GlazeColorToken.export()`.
2107
+ */
2108
+ function colorFromExport(data) {
2109
+ if (data === null || typeof data !== "object") throw new Error(`glaze.colorFrom: expected an object from token.export(), got ${data === null ? "null" : typeof data}.`);
2110
+ if (data.form !== "value" && data.form !== "structured") throw new Error(`glaze.colorFrom: invalid "form" field — expected "value" or "structured" (got ${JSON.stringify(data.form)}).`);
2111
+ if (data.input === void 0) throw new Error(`glaze.colorFrom: missing "input" field — expected the original ${data.form === "value" ? "GlazeColorValue" : "GlazeColorInput"}.`);
2112
+ if (data.form === "value") {
2113
+ const value = data.input;
2114
+ return createColorTokenFromValue(value, data.overrides ? rehydrateOverrides(data.overrides) : void 0, data.scaling);
2115
+ }
2116
+ return createColorToken(rehydrateStructuredInput(data.input), data.scaling);
2117
+ }
2118
+ function rehydrateOverrides(data) {
2119
+ const out = {};
2120
+ if (data.hue !== void 0) out.hue = data.hue;
2121
+ if (data.saturation !== void 0) out.saturation = data.saturation;
2122
+ if (data.lightness !== void 0) out.lightness = data.lightness;
2123
+ if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
2124
+ if (data.mode !== void 0) out.mode = data.mode;
2125
+ if (data.contrast !== void 0) out.contrast = data.contrast;
2126
+ if (data.opacity !== void 0) out.opacity = data.opacity;
2127
+ if (data.name !== void 0) out.name = data.name;
2128
+ if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
2129
+ return out;
2130
+ }
2131
+ function rehydrateStructuredInput(data) {
2132
+ const out = {
2133
+ hue: data.hue,
2134
+ saturation: data.saturation,
2135
+ lightness: data.lightness
2136
+ };
2137
+ if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
2138
+ if (data.mode !== void 0) out.mode = data.mode;
2139
+ if (data.opacity !== void 0) out.opacity = data.opacity;
2140
+ if (data.contrast !== void 0) out.contrast = data.contrast;
2141
+ if (data.name !== void 0) out.name = data.name;
2142
+ if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
2143
+ return out;
2144
+ }
2145
+ /**
2146
+ * Discriminate a `GlazeColorTokenExport` from a raw `GlazeColorValue`.
2147
+ * `GlazeColorTokenExport` always has a `form` field set to either
2148
+ * `'value'` or `'structured'`; raw values never do.
2149
+ */
2150
+ function isExportedToken(candidate) {
2151
+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) && "form" in candidate && (candidate.form === "value" || candidate.form === "structured");
1605
2152
  }
1606
2153
  /**
1607
2154
  * Create a single-hue glaze theme.
@@ -1649,18 +2196,57 @@ glaze.palette = function palette(themes, options) {
1649
2196
  glaze.from = function from(data) {
1650
2197
  return createTheme(data.hue, data.saturation, data.colors);
1651
2198
  };
2199
+ function isStructuredColorInput(input) {
2200
+ return typeof input === "object" && input !== null && !Array.isArray(input) && "hue" in input && "lightness" in input;
2201
+ }
1652
2202
  /**
1653
2203
  * Create a standalone single-color token.
2204
+ *
2205
+ * Two overloads:
2206
+ * - `glaze.color(input, scaling?)` — structured form:
2207
+ * `{ hue, saturation, lightness, ... }` plus an optional per-call
2208
+ * lightness-window override.
2209
+ * - `glaze.color(value, overrides?, scaling?)` — value-shorthand: a hex
2210
+ * string (3/6/8 digits), one of the CSS color functions Glaze itself
2211
+ * emits (`rgb()`, `hsl()`, `okhsl()`, `oklch()`), an `OkhslColor`
2212
+ * object `{ h, s, l }` (0–1 ranges), or an `[r, g, b]` (0–255) tuple.
2213
+ *
2214
+ * Defaults vary by input form:
2215
+ * - String value-shorthand: `mode: 'auto'` with snapshotted scaling
2216
+ * `{ lightLightness: false, darkLightness: [globalConfig.darkLightness[0], 100] }`.
2217
+ * Light preserves the input exactly; dark Möbius-inverts up to 100, so
2218
+ * `glaze.color('#000')` renders as `#fff` in dark mode (and
2219
+ * `glaze.color('#fff')` falls to the dark `lo` floor).
2220
+ * - `OkhslColor` object / RGB-tuple value-shorthand: `mode: 'fixed'`
2221
+ * with `scaling: { lightLightness: false }` — light preserves the
2222
+ * input; dark linearly maps into `globalConfig.darkLightness`.
2223
+ * - Structured form (`{ hue, saturation, lightness, ... }`):
2224
+ * `mode: 'fixed'`; both windows come from `globalConfig`.
2225
+ *
2226
+ * Relative `lightness: '+N'` and `contrast: <ratio>` are anchored to
2227
+ * the literal seed (the value passed in) by default, pinned at
2228
+ * `mode: 'static'` across all four variants. Pass `overrides.base` (a
2229
+ * `GlazeColorToken`) to anchor `contrast` and relative `lightness`
2230
+ * against another color's resolved variant per scheme instead. Relative
2231
+ * `hue: '+N'` always anchors to the seed.
2232
+ *
2233
+ * Alpha components in `rgba()` / `hsla()` / slash-alpha syntax and
2234
+ * 8-digit hex are parsed but dropped with a `console.warn`.
1654
2235
  */
1655
- glaze.color = function color(input) {
1656
- return createColorToken(input);
2236
+ glaze.color = function color(input, arg2, arg3) {
2237
+ if (isStructuredColorInput(input)) return createColorToken(input, arg2);
2238
+ return createColorTokenFromValue(input, arg2, arg3);
1657
2239
  };
1658
2240
  /**
1659
2241
  * Compute a shadow color from a bg/fg pair and intensity.
2242
+ *
2243
+ * Both `bg` and `fg` accept any `GlazeColorValue` form: hex (`#rgb` /
2244
+ * `#rrggbb` / `#rrggbbaa`), `rgb()` / `hsl()` / `okhsl()` / `oklch()`
2245
+ * strings, `OkhslColor` objects, or `[r, g, b]` (0–255) tuples.
1660
2246
  */
1661
2247
  glaze.shadow = function shadow(input) {
1662
- const bg = parseOkhslInput(input.bg);
1663
- const fg = input.fg ? parseOkhslInput(input.fg) : void 0;
2248
+ const bg = extractOkhslFromValue(input.bg);
2249
+ const fg = input.fg ? extractOkhslFromValue(input.fg) : void 0;
1664
2250
  const tuning = resolveShadowTuning(input.tuning);
1665
2251
  return computeShadow({
1666
2252
  ...bg,
@@ -1676,19 +2262,6 @@ glaze.shadow = function shadow(input) {
1676
2262
  glaze.format = function format(variant, colorFormat) {
1677
2263
  return formatVariant(variant, colorFormat);
1678
2264
  };
1679
- function parseOkhslInput(input) {
1680
- if (typeof input === "string") {
1681
- const rgb = parseHex(input);
1682
- if (!rgb) throw new Error(`glaze: invalid hex color "${input}".`);
1683
- const [h, s, l] = srgbToOkhsl(rgb);
1684
- return {
1685
- h,
1686
- s,
1687
- l
1688
- };
1689
- }
1690
- return input;
1691
- }
1692
2265
  /**
1693
2266
  * Create a theme from a hex color string.
1694
2267
  * Extracts hue and saturation from the color.
@@ -1712,6 +2285,26 @@ glaze.fromRgb = function fromRgb(r, g, b) {
1712
2285
  return createTheme(h, s * 100);
1713
2286
  };
1714
2287
  /**
2288
+ * Rehydrate a `glaze.color()` token from a `.export()` snapshot.
2289
+ *
2290
+ * The snapshot is a plain JSON-safe object containing the original
2291
+ * input value, overrides (with any `base` token recursively serialized),
2292
+ * and the captured scaling. The reconstructed token is identical in
2293
+ * behavior to the original at the time of export.
2294
+ *
2295
+ * @example
2296
+ * ```ts
2297
+ * const text = glaze.color('#1a1a1a', { contrast: 'AA' });
2298
+ * const data = text.export(); // JSON-safe
2299
+ * localStorage.setItem('text', JSON.stringify(data));
2300
+ * // ...later...
2301
+ * const restored = glaze.colorFrom(JSON.parse(localStorage.getItem('text')!));
2302
+ * ```
2303
+ */
2304
+ glaze.colorFrom = function colorFrom(data) {
2305
+ return colorFromExport(data);
2306
+ };
2307
+ /**
1715
2308
  * Get the current global configuration (for testing/debugging).
1716
2309
  */
1717
2310
  glaze.getConfig = function getConfig() {
@@ -1747,10 +2340,13 @@ exports.formatOklch = formatOklch;
1747
2340
  exports.formatRgb = formatRgb;
1748
2341
  exports.gamutClampedLuminance = gamutClampedLuminance;
1749
2342
  exports.glaze = glaze;
2343
+ exports.hslToSrgb = hslToSrgb;
1750
2344
  exports.okhslToLinearSrgb = okhslToLinearSrgb;
1751
2345
  exports.okhslToOklab = okhslToOklab;
1752
2346
  exports.okhslToSrgb = okhslToSrgb;
2347
+ exports.oklabToOkhsl = oklabToOkhsl;
1753
2348
  exports.parseHex = parseHex;
2349
+ exports.parseHexAlpha = parseHexAlpha;
1754
2350
  exports.relativeLuminanceFromLinearRgb = relativeLuminanceFromLinearRgb;
1755
2351
  exports.resolveMinContrast = resolveMinContrast;
1756
2352
  exports.srgbToOkhsl = srgbToOkhsl;