@tenphi/glaze 0.0.0-snapshot.78261ef → 0.0.0-snapshot.7b8c12f
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/README.md +85 -1096
- package/dist/index.cjs +3058 -852
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1165 -113
- package/dist/index.d.mts +1165 -113
- package/dist/index.mjs +3027 -852
- package/dist/index.mjs.map +1 -1
- package/docs/api.md +1683 -0
- package/docs/methodology.md +636 -0
- package/docs/migration.md +315 -0
- package/docs/okhst.md +170 -0
- package/package.json +9 -9
package/dist/index.mjs
CHANGED
|
@@ -96,7 +96,12 @@ const K2 = .03;
|
|
|
96
96
|
const K3 = (1 + K1) / (1 + K2);
|
|
97
97
|
const EPSILON = 1e-10;
|
|
98
98
|
const constrainAngle = (angle) => (angle % 360 + 360) % 360;
|
|
99
|
+
/**
|
|
100
|
+
* OKHSL toe function: maps OKLab lightness L to perceptual lightness l.
|
|
101
|
+
* Exported for the OKHST tone transfers in `okhst.ts`.
|
|
102
|
+
*/
|
|
99
103
|
const toe = (x) => .5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
|
|
104
|
+
/** Inverse OKHSL toe: maps perceptual lightness l back to OKLab lightness L. */
|
|
100
105
|
const toeInv = (x) => (x ** 2 + K1 * x) / (K3 * (x + K2));
|
|
101
106
|
const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
102
107
|
const dotXY = (a, b) => a[0] * b[0] + a[1] * b[1];
|
|
@@ -251,10 +256,48 @@ const getCs = (L, a, b, cusp) => {
|
|
|
251
256
|
cMax
|
|
252
257
|
];
|
|
253
258
|
};
|
|
259
|
+
const CYAN_A = Math.cos(199.8 * Math.PI / 180);
|
|
260
|
+
const CYAN_B = Math.sin(199.8 * Math.PI / 180);
|
|
261
|
+
const BLUE_A = Math.cos(267.4 * Math.PI / 180);
|
|
262
|
+
const BLUE_B = Math.sin(267.4 * Math.PI / 180);
|
|
263
|
+
let cyanCusp;
|
|
264
|
+
let blueCusp;
|
|
265
|
+
/**
|
|
266
|
+
* Computes the maximum safe OKLCH chroma that fits inside the sRGB gamut
|
|
267
|
+
* for all possible hues at a given OKLab lightness `L`.
|
|
268
|
+
*/
|
|
269
|
+
function computeSafeChromaOKLCH(L) {
|
|
270
|
+
if (!cyanCusp) cyanCusp = findCuspOKLCH(CYAN_A, CYAN_B);
|
|
271
|
+
if (!blueCusp) blueCusp = findCuspOKLCH(BLUE_A, BLUE_B);
|
|
272
|
+
const c1 = findGamutIntersectionOKLCH(CYAN_A, CYAN_B, L, 1, L, cyanCusp);
|
|
273
|
+
const c2 = findGamutIntersectionOKLCH(BLUE_A, BLUE_B, L, 1, L, blueCusp);
|
|
274
|
+
return Math.min(c1, c2);
|
|
275
|
+
}
|
|
276
|
+
/** Per-hue cusp-lightness cache. The cusp is mode-independent, so keying on
|
|
277
|
+
* a rounded hue is safe and keeps the cache small. */
|
|
278
|
+
const cuspLightnessCache = /* @__PURE__ */ new Map();
|
|
279
|
+
/**
|
|
280
|
+
* OKHSL lightness of the gamut cusp for a hue — the lightness where the
|
|
281
|
+
* realizable chroma peaks. Reuses the same `find_cusp` OKHSL already runs for
|
|
282
|
+
* its `s` normalization (no new color math); the OKLab cusp lightness is run
|
|
283
|
+
* through the OKHSL `toe` and clamped to `[0.001, 0.999]` so divisions that
|
|
284
|
+
* key off it stay safe. Cached per (rounded) hue.
|
|
285
|
+
*
|
|
286
|
+
* @param h Hue, 0–360.
|
|
287
|
+
*/
|
|
288
|
+
function cuspLightness(h) {
|
|
289
|
+
const key = Math.round(constrainAngle(h) * 100) / 100;
|
|
290
|
+
const cached = cuspLightnessCache.get(key);
|
|
291
|
+
if (cached !== void 0) return cached;
|
|
292
|
+
const hNorm = key / 360;
|
|
293
|
+
const lc = clampVal(toe(findCuspOKLCH(Math.cos(TAU * hNorm), Math.sin(TAU * hNorm))[0]), .001, .999);
|
|
294
|
+
cuspLightnessCache.set(key, lc);
|
|
295
|
+
return lc;
|
|
296
|
+
}
|
|
254
297
|
/**
|
|
255
298
|
* Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLab [L, a, b].
|
|
256
299
|
*/
|
|
257
|
-
function okhslToOklab(h, s, l) {
|
|
300
|
+
function okhslToOklab(h, s, l, pastel = false) {
|
|
258
301
|
const L = toeInv(l);
|
|
259
302
|
let a = 0;
|
|
260
303
|
let b = 0;
|
|
@@ -262,24 +305,30 @@ function okhslToOklab(h, s, l) {
|
|
|
262
305
|
if (L !== 0 && L !== 1 && s !== 0) {
|
|
263
306
|
const a_ = Math.cos(TAU * hNorm);
|
|
264
307
|
const b_ = Math.sin(TAU * hNorm);
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
if (s < mid) {
|
|
270
|
-
t = midInv * s;
|
|
271
|
-
k0 = 0;
|
|
272
|
-
k1 = mid * c0;
|
|
273
|
-
k2 = 1 - k1 / cMid;
|
|
308
|
+
if (pastel) {
|
|
309
|
+
const c = s * computeSafeChromaOKLCH(L);
|
|
310
|
+
a = c * a_;
|
|
311
|
+
b = c * b_;
|
|
274
312
|
} else {
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
313
|
+
const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
|
|
314
|
+
const mid = .8;
|
|
315
|
+
const midInv = 1.25;
|
|
316
|
+
let t, k0, k1, k2;
|
|
317
|
+
if (s < mid) {
|
|
318
|
+
t = midInv * s;
|
|
319
|
+
k0 = 0;
|
|
320
|
+
k1 = mid * c0;
|
|
321
|
+
k2 = 1 - k1 / cMid;
|
|
322
|
+
} else {
|
|
323
|
+
t = 5 * (s - .8);
|
|
324
|
+
k0 = cMid;
|
|
325
|
+
k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
|
|
326
|
+
k2 = 1 - k1 / (cMax - cMid);
|
|
327
|
+
}
|
|
328
|
+
const c = k0 + t * k1 / (1 - k2 * t);
|
|
329
|
+
a = c * a_;
|
|
330
|
+
b = c * b_;
|
|
279
331
|
}
|
|
280
|
-
const c = k0 + t * k1 / (1 - k2 * t);
|
|
281
|
-
a = c * a_;
|
|
282
|
-
b = c * b_;
|
|
283
332
|
}
|
|
284
333
|
return [
|
|
285
334
|
L,
|
|
@@ -291,8 +340,8 @@ function okhslToOklab(h, s, l) {
|
|
|
291
340
|
* Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to linear sRGB.
|
|
292
341
|
* Channels may exceed [0, 1] near gamut boundaries — caller must clamp if needed.
|
|
293
342
|
*/
|
|
294
|
-
function okhslToLinearSrgb(h, s, l) {
|
|
295
|
-
return OKLabToLinearSRGB(okhslToOklab(h, s, l));
|
|
343
|
+
function okhslToLinearSrgb(h, s, l, pastel = false) {
|
|
344
|
+
return OKLabToLinearSRGB(okhslToOklab(h, s, l, pastel));
|
|
296
345
|
}
|
|
297
346
|
/**
|
|
298
347
|
* Compute relative luminance Y from linear sRGB channels.
|
|
@@ -322,8 +371,8 @@ const sRGBGammaToLinear = (val) => {
|
|
|
322
371
|
/**
|
|
323
372
|
* Convert OKHSL to gamma-encoded sRGB (clamped to 0–1).
|
|
324
373
|
*/
|
|
325
|
-
function okhslToSrgb(h, s, l) {
|
|
326
|
-
const lin = okhslToLinearSrgb(h, s, l);
|
|
374
|
+
function okhslToSrgb(h, s, l, pastel = false) {
|
|
375
|
+
const lin = okhslToLinearSrgb(h, s, l, pastel);
|
|
327
376
|
return [
|
|
328
377
|
Math.max(0, Math.min(1, sRGBLinearToGamma(lin[0]))),
|
|
329
378
|
Math.max(0, Math.min(1, sRGBLinearToGamma(lin[1]))),
|
|
@@ -341,10 +390,31 @@ function gamutClampedLuminance(linearRgb) {
|
|
|
341
390
|
const b = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2]))));
|
|
342
391
|
return .2126 * r + .7152 * g + .0722 * b;
|
|
343
392
|
}
|
|
393
|
+
/**
|
|
394
|
+
* Compute APCA screen luminance (`Ys`) from linear sRGB.
|
|
395
|
+
*
|
|
396
|
+
* APCA does not use the WCAG piecewise sRGB EOTF; it defines its own
|
|
397
|
+
* luminance as `0.2126·R^2.4 + 0.7152·G^2.4 + 0.0722·B^2.4` over the
|
|
398
|
+
* gamma-encoded (display) channels with a simple 2.4 exponent. The APCA
|
|
399
|
+
* soft-clamp threshold in `apcaContrast` is calibrated against this basis,
|
|
400
|
+
* so the solver must feed it `Ys`, not WCAG relative luminance. Channels
|
|
401
|
+
* are gamut-clamped to [0, 1] first, matching `gamutClampedLuminance`.
|
|
402
|
+
*/
|
|
403
|
+
function apcaLuminanceFromLinearRgb(linearRgb) {
|
|
404
|
+
const r = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[0])));
|
|
405
|
+
const g = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[1])));
|
|
406
|
+
const b = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2])));
|
|
407
|
+
return .2126 * Math.pow(r, 2.4) + .7152 * Math.pow(g, 2.4) + .0722 * Math.pow(b, 2.4);
|
|
408
|
+
}
|
|
344
409
|
const linearSrgbToOklab = (rgb) => {
|
|
345
410
|
return transform(cbrt3(transform(rgb, linear_sRGB_to_LMS_M)), LMS_to_OKLab_M);
|
|
346
411
|
};
|
|
347
|
-
|
|
412
|
+
/**
|
|
413
|
+
* Convert OKLab to OKHSL.
|
|
414
|
+
* Input: [L, a, b] where L: 0–1, a/b: roughly -0.5 to 0.5.
|
|
415
|
+
* Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
|
|
416
|
+
*/
|
|
417
|
+
const oklabToOkhsl = (lab, pastel = false) => {
|
|
348
418
|
const L = lab[0];
|
|
349
419
|
const a = lab[1];
|
|
350
420
|
const b = lab[2];
|
|
@@ -354,23 +424,32 @@ const oklabToOkhsl = (lab) => {
|
|
|
354
424
|
0,
|
|
355
425
|
toe(L)
|
|
356
426
|
];
|
|
427
|
+
const L_EXTREME_EPSILON = 1e-6;
|
|
428
|
+
if (L >= 1 - L_EXTREME_EPSILON || L <= L_EXTREME_EPSILON) return [
|
|
429
|
+
0,
|
|
430
|
+
0,
|
|
431
|
+
toe(L)
|
|
432
|
+
];
|
|
357
433
|
const a_ = a / C;
|
|
358
434
|
const b_ = b / C;
|
|
359
435
|
let h = Math.atan2(b, a) * (180 / Math.PI);
|
|
360
436
|
h = constrainAngle(h);
|
|
361
|
-
const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
|
|
362
|
-
const mid = .8;
|
|
363
|
-
const midInv = 1.25;
|
|
364
437
|
let s;
|
|
365
|
-
if (C
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
438
|
+
if (pastel) s = C / computeSafeChromaOKLCH(L);
|
|
439
|
+
else {
|
|
440
|
+
const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
|
|
441
|
+
const mid = .8;
|
|
442
|
+
const midInv = 1.25;
|
|
443
|
+
if (C < cMid) {
|
|
444
|
+
const k1 = mid * c0;
|
|
445
|
+
s = C / (k1 + C * (1 - k1 / cMid)) / midInv;
|
|
446
|
+
} else {
|
|
447
|
+
const k0 = cMid;
|
|
448
|
+
const k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
|
|
449
|
+
const k2 = 1 - k1 / (cMax - cMid);
|
|
450
|
+
const cDiff = C - k0;
|
|
451
|
+
s = mid + cDiff / (k1 + cDiff * k2) / 5;
|
|
452
|
+
}
|
|
374
453
|
}
|
|
375
454
|
const l = toe(L);
|
|
376
455
|
return [
|
|
@@ -383,40 +462,116 @@ const oklabToOkhsl = (lab) => {
|
|
|
383
462
|
* Convert gamma-encoded sRGB (0–1 per channel) to OKHSL.
|
|
384
463
|
* Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
|
|
385
464
|
*/
|
|
386
|
-
function srgbToOkhsl(rgb) {
|
|
465
|
+
function srgbToOkhsl(rgb, pastel = false) {
|
|
387
466
|
return oklabToOkhsl(linearSrgbToOklab([
|
|
388
467
|
sRGBGammaToLinear(rgb[0]),
|
|
389
468
|
sRGBGammaToLinear(rgb[1]),
|
|
390
469
|
sRGBGammaToLinear(rgb[2])
|
|
391
|
-
]));
|
|
470
|
+
]), pastel);
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Convert CSS HSL (sRGB-based) to gamma-encoded sRGB [r, g, b] in 0–1 range.
|
|
474
|
+
* h: 0–360, s: 0–1, l: 0–1.
|
|
475
|
+
*
|
|
476
|
+
* Note: CSS HSL is not the same as OKHSL — it's HSL in the sRGB color space.
|
|
477
|
+
* Use this when parsing `hsl(...)` strings before passing to `srgbToOkhsl`.
|
|
478
|
+
*/
|
|
479
|
+
function hslToSrgb(h, s, l) {
|
|
480
|
+
const hh = (h % 360 + 360) % 360 / 360;
|
|
481
|
+
const ss = clampVal(s, 0, 1);
|
|
482
|
+
const ll = clampVal(l, 0, 1);
|
|
483
|
+
if (ss === 0) return [
|
|
484
|
+
ll,
|
|
485
|
+
ll,
|
|
486
|
+
ll
|
|
487
|
+
];
|
|
488
|
+
const q = ll < .5 ? ll * (1 + ss) : ll + ss - ll * ss;
|
|
489
|
+
const p = 2 * ll - q;
|
|
490
|
+
const hueToChannel = (t) => {
|
|
491
|
+
let tt = t;
|
|
492
|
+
if (tt < 0) tt += 1;
|
|
493
|
+
if (tt > 1) tt -= 1;
|
|
494
|
+
if (tt < 1 / 6) return p + (q - p) * 6 * tt;
|
|
495
|
+
if (tt < 1 / 2) return q;
|
|
496
|
+
if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
|
|
497
|
+
return p;
|
|
498
|
+
};
|
|
499
|
+
return [
|
|
500
|
+
hueToChannel(hh + 1 / 3),
|
|
501
|
+
hueToChannel(hh),
|
|
502
|
+
hueToChannel(hh - 1 / 3)
|
|
503
|
+
];
|
|
392
504
|
}
|
|
393
505
|
/**
|
|
394
506
|
* Parse a hex color string (#rgb or #rrggbb) to sRGB [r, g, b] in 0–1 range.
|
|
395
507
|
* Returns null if the string is not a valid hex color.
|
|
508
|
+
*
|
|
509
|
+
* For 8-digit hex (`#rrggbbaa`) and 4-digit hex (`#rgba`) with alpha,
|
|
510
|
+
* use {@link parseHexAlpha}.
|
|
396
511
|
*/
|
|
397
512
|
function parseHex(hex) {
|
|
513
|
+
const result = parseHexAlpha(hex);
|
|
514
|
+
if (!result || result.alpha !== void 0) return null;
|
|
515
|
+
return result.rgb;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Parse a hex color string (#rgb, #rrggbb, #rgba, or #rrggbbaa) to
|
|
519
|
+
* sRGB [r, g, b] in 0–1 range plus an optional alpha (0–1).
|
|
520
|
+
* Returns null if the string is not a valid hex color.
|
|
521
|
+
*/
|
|
522
|
+
function parseHexAlpha(hex) {
|
|
398
523
|
const h = hex.startsWith("#") ? hex.slice(1) : hex;
|
|
399
524
|
if (h.length === 3) {
|
|
400
525
|
const r = parseInt(h[0] + h[0], 16);
|
|
401
526
|
const g = parseInt(h[1] + h[1], 16);
|
|
402
527
|
const b = parseInt(h[2] + h[2], 16);
|
|
403
528
|
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
|
404
|
-
return [
|
|
529
|
+
return { rgb: [
|
|
405
530
|
r / 255,
|
|
406
531
|
g / 255,
|
|
407
532
|
b / 255
|
|
408
|
-
];
|
|
533
|
+
] };
|
|
534
|
+
}
|
|
535
|
+
if (h.length === 4) {
|
|
536
|
+
const r = parseInt(h[0] + h[0], 16);
|
|
537
|
+
const g = parseInt(h[1] + h[1], 16);
|
|
538
|
+
const b = parseInt(h[2] + h[2], 16);
|
|
539
|
+
const a = parseInt(h[3] + h[3], 16);
|
|
540
|
+
if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
|
|
541
|
+
return {
|
|
542
|
+
rgb: [
|
|
543
|
+
r / 255,
|
|
544
|
+
g / 255,
|
|
545
|
+
b / 255
|
|
546
|
+
],
|
|
547
|
+
alpha: a / 255
|
|
548
|
+
};
|
|
409
549
|
}
|
|
410
550
|
if (h.length === 6) {
|
|
411
551
|
const r = parseInt(h.slice(0, 2), 16);
|
|
412
552
|
const g = parseInt(h.slice(2, 4), 16);
|
|
413
553
|
const b = parseInt(h.slice(4, 6), 16);
|
|
414
554
|
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
|
415
|
-
return [
|
|
555
|
+
return { rgb: [
|
|
416
556
|
r / 255,
|
|
417
557
|
g / 255,
|
|
418
558
|
b / 255
|
|
419
|
-
];
|
|
559
|
+
] };
|
|
560
|
+
}
|
|
561
|
+
if (h.length === 8) {
|
|
562
|
+
const r = parseInt(h.slice(0, 2), 16);
|
|
563
|
+
const g = parseInt(h.slice(2, 4), 16);
|
|
564
|
+
const b = parseInt(h.slice(4, 6), 16);
|
|
565
|
+
const a = parseInt(h.slice(6, 8), 16);
|
|
566
|
+
if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
|
|
567
|
+
return {
|
|
568
|
+
rgb: [
|
|
569
|
+
r / 255,
|
|
570
|
+
g / 255,
|
|
571
|
+
b / 255
|
|
572
|
+
],
|
|
573
|
+
alpha: a / 255
|
|
574
|
+
};
|
|
420
575
|
}
|
|
421
576
|
return null;
|
|
422
577
|
}
|
|
@@ -427,24 +582,44 @@ function fmt$1(value, decimals) {
|
|
|
427
582
|
* Format OKHSL values as a CSS `okhsl(H S% L%)` string.
|
|
428
583
|
* h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
|
|
429
584
|
*/
|
|
430
|
-
function formatOkhsl(h, s, l) {
|
|
431
|
-
|
|
585
|
+
function formatOkhsl(h, s, l, pastel = false) {
|
|
586
|
+
let outS = s;
|
|
587
|
+
if (pastel) outS = oklabToOkhsl(okhslToOklab(h, s / 100, l / 100, true), false)[1] * 100;
|
|
588
|
+
return `okhsl(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(l, 2)}%)`;
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Format OKHST values as a CSS `okhst(H S% T%)` string.
|
|
592
|
+
* h: 0–360, s: 0–100, t: 0–100 (percentage scale for s and t).
|
|
593
|
+
*
|
|
594
|
+
* Pastel recompute matches `formatOkhsl`: convert via OKLab so external
|
|
595
|
+
* parsers that only understand non-pastel OKHST render identically.
|
|
596
|
+
*/
|
|
597
|
+
function formatOkhst(h, s, t, pastel = false) {
|
|
598
|
+
let outS = s;
|
|
599
|
+
if (pastel) {
|
|
600
|
+
const REF_EPS = .05;
|
|
601
|
+
const den = Math.log(1 + REF_EPS) - Math.log(REF_EPS);
|
|
602
|
+
const y = Math.exp(t / 100 * den + Math.log(REF_EPS)) - REF_EPS;
|
|
603
|
+
const l = toe(Math.cbrt(Math.max(0, y)));
|
|
604
|
+
outS = oklabToOkhsl(okhslToOklab(h, s / 100, l, true), false)[1] * 100;
|
|
605
|
+
}
|
|
606
|
+
return `okhst(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(t, 2)}%)`;
|
|
432
607
|
}
|
|
433
608
|
/**
|
|
434
609
|
* Format OKHSL values as a CSS `rgb(R G B)` string.
|
|
435
610
|
* Uses 2 decimal places to avoid 8-bit quantization contrast loss.
|
|
436
611
|
* h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
|
|
437
612
|
*/
|
|
438
|
-
function formatRgb(h, s, l) {
|
|
439
|
-
const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
|
|
613
|
+
function formatRgb(h, s, l, pastel = false) {
|
|
614
|
+
const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
|
|
440
615
|
return `rgb(${parseFloat((r * 255).toFixed(2))} ${parseFloat((g * 255).toFixed(2))} ${parseFloat((b * 255).toFixed(2))})`;
|
|
441
616
|
}
|
|
442
617
|
/**
|
|
443
618
|
* Format OKHSL values as a CSS `hsl(H S% L%)` string.
|
|
444
619
|
* h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
|
|
445
620
|
*/
|
|
446
|
-
function formatHsl(h, s, l) {
|
|
447
|
-
const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
|
|
621
|
+
function formatHsl(h, s, l, pastel = false) {
|
|
622
|
+
const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
|
|
448
623
|
const max = Math.max(r, g, b);
|
|
449
624
|
const min = Math.min(r, g, b);
|
|
450
625
|
const delta = max - min;
|
|
@@ -463,393 +638,1061 @@ function formatHsl(h, s, l) {
|
|
|
463
638
|
* Format OKHSL values as a CSS `oklch(L C H)` string.
|
|
464
639
|
* h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
|
|
465
640
|
*/
|
|
466
|
-
function formatOklch(h, s, l) {
|
|
467
|
-
const [L,
|
|
468
|
-
const C = Math.sqrt(a * a + b * b);
|
|
469
|
-
let hh = Math.atan2(b, a) * (180 / Math.PI);
|
|
470
|
-
hh = constrainAngle(hh);
|
|
641
|
+
function formatOklch(h, s, l, pastel = false) {
|
|
642
|
+
const [L, C, hh] = okhslToOklch(h, s / 100, l / 100, pastel);
|
|
471
643
|
return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 2)})`;
|
|
472
644
|
}
|
|
645
|
+
/**
|
|
646
|
+
* Convert gamma-encoded sRGB channels (0–1) to a 6-digit lowercase hex
|
|
647
|
+
* string (`#rrggbb`). Channels are clamped to [0,1] and rounded to 8-bit.
|
|
648
|
+
* Alpha is not encoded here — DTCG carries it as a separate `alpha` field.
|
|
649
|
+
*/
|
|
650
|
+
function srgbToHex(rgb) {
|
|
651
|
+
const toByte = (c) => Math.max(0, Math.min(255, Math.round(c * 255)));
|
|
652
|
+
const r = toByte(rgb[0]);
|
|
653
|
+
const g = toByte(rgb[1]);
|
|
654
|
+
const b = toByte(rgb[2]);
|
|
655
|
+
return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLCH components `[L, C, H]`.
|
|
659
|
+
* L: 0–1, C: 0–~0.4 (chroma), H: 0–360 (hue). Shared by `formatOklch` and
|
|
660
|
+
* the DTCG `oklch` colorSpace exporter so the two never drift apart.
|
|
661
|
+
*/
|
|
662
|
+
function okhslToOklch(h, s, l, pastel = false) {
|
|
663
|
+
const [L, a, b] = okhslToOklab(h, s, l, pastel);
|
|
664
|
+
return [
|
|
665
|
+
L,
|
|
666
|
+
Math.sqrt(a * a + b * b),
|
|
667
|
+
constrainAngle(Math.atan2(b, a) * (180 / Math.PI))
|
|
668
|
+
];
|
|
669
|
+
}
|
|
473
670
|
|
|
474
671
|
//#endregion
|
|
475
|
-
//#region src/
|
|
672
|
+
//#region src/config.ts
|
|
476
673
|
/**
|
|
477
|
-
*
|
|
674
|
+
* Build a fresh defaults object. Called from module init and from
|
|
675
|
+
* `resetConfig()` so the two paths can't drift.
|
|
478
676
|
*
|
|
479
|
-
*
|
|
480
|
-
* against a base color. Used by glaze when resolving dependent colors
|
|
481
|
-
* with `contrast`.
|
|
677
|
+
* `pastel: false` is a fixed instance default — not globally configurable.
|
|
482
678
|
*/
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
679
|
+
function defaultConfig() {
|
|
680
|
+
return {
|
|
681
|
+
lightTone: {
|
|
682
|
+
lo: 10,
|
|
683
|
+
hi: 100,
|
|
684
|
+
eps: .05
|
|
685
|
+
},
|
|
686
|
+
darkTone: {
|
|
687
|
+
lo: 15,
|
|
688
|
+
hi: 95,
|
|
689
|
+
eps: .05
|
|
690
|
+
},
|
|
691
|
+
darkDesaturation: .1,
|
|
692
|
+
states: {
|
|
693
|
+
dark: "@media(prefers-color-scheme: dark)",
|
|
694
|
+
highContrast: "@media(prefers-contrast: more)"
|
|
695
|
+
},
|
|
696
|
+
modes: {
|
|
697
|
+
dark: true,
|
|
698
|
+
highContrast: false
|
|
699
|
+
},
|
|
700
|
+
autoFlip: true,
|
|
701
|
+
pastel: false,
|
|
702
|
+
inferRole: true
|
|
703
|
+
};
|
|
492
704
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
luminanceCache.set(key, y);
|
|
507
|
-
cacheOrder.push(key);
|
|
508
|
-
return y;
|
|
705
|
+
let globalConfig = defaultConfig();
|
|
706
|
+
/**
|
|
707
|
+
* Monotonic counter incremented on every `configure()` / `resetConfig()`
|
|
708
|
+
* call. Theme / palette caches read this to invalidate stale resolve
|
|
709
|
+
* results when the config changes between exports.
|
|
710
|
+
*/
|
|
711
|
+
let configVersion = 0;
|
|
712
|
+
/** Live reference to the current config. Mutated by `configure()` / `resetConfig()`. */
|
|
713
|
+
function getConfig() {
|
|
714
|
+
return globalConfig;
|
|
715
|
+
}
|
|
716
|
+
function getConfigVersion() {
|
|
717
|
+
return configVersion;
|
|
509
718
|
}
|
|
510
719
|
/**
|
|
511
|
-
*
|
|
720
|
+
* Public-facing snapshot used by `glaze.getConfig()`. Returns a shallow
|
|
721
|
+
* copy so callers can't mutate the live config.
|
|
512
722
|
*/
|
|
513
|
-
function
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
const mid = (low + high) / 2;
|
|
535
|
-
if (contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase) >= target) if (mid < preferred) low = mid;
|
|
536
|
-
else high = mid;
|
|
537
|
-
else if (mid < preferred) high = mid;
|
|
538
|
-
else low = mid;
|
|
539
|
-
}
|
|
540
|
-
const yLow = cachedLuminance(h, s, low);
|
|
541
|
-
const yHigh = cachedLuminance(h, s, high);
|
|
542
|
-
const crLow = contrastRatioFromLuminance(yLow, yBase);
|
|
543
|
-
const crHigh = contrastRatioFromLuminance(yHigh, yBase);
|
|
544
|
-
const lowPasses = crLow >= target;
|
|
545
|
-
const highPasses = crHigh >= target;
|
|
546
|
-
if (lowPasses && highPasses) {
|
|
547
|
-
if (Math.abs(low - preferred) <= Math.abs(high - preferred)) return {
|
|
548
|
-
lightness: low,
|
|
549
|
-
contrast: crLow,
|
|
550
|
-
met: true
|
|
551
|
-
};
|
|
552
|
-
return {
|
|
553
|
-
lightness: high,
|
|
554
|
-
contrast: crHigh,
|
|
555
|
-
met: true
|
|
556
|
-
};
|
|
557
|
-
}
|
|
558
|
-
if (lowPasses) return {
|
|
559
|
-
lightness: low,
|
|
560
|
-
contrast: crLow,
|
|
561
|
-
met: true
|
|
723
|
+
function snapshotConfig() {
|
|
724
|
+
return { ...globalConfig };
|
|
725
|
+
}
|
|
726
|
+
function configure(config) {
|
|
727
|
+
configVersion++;
|
|
728
|
+
globalConfig = {
|
|
729
|
+
lightTone: config.lightTone ?? globalConfig.lightTone,
|
|
730
|
+
darkTone: config.darkTone ?? globalConfig.darkTone,
|
|
731
|
+
darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
|
|
732
|
+
states: {
|
|
733
|
+
dark: config.states?.dark ?? globalConfig.states.dark,
|
|
734
|
+
highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
|
|
735
|
+
},
|
|
736
|
+
modes: {
|
|
737
|
+
dark: config.modes?.dark ?? globalConfig.modes.dark,
|
|
738
|
+
highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
|
|
739
|
+
},
|
|
740
|
+
shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning,
|
|
741
|
+
autoFlip: config.autoFlip ?? globalConfig.autoFlip,
|
|
742
|
+
pastel: false,
|
|
743
|
+
inferRole: config.inferRole ?? globalConfig.inferRole
|
|
562
744
|
};
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
745
|
+
}
|
|
746
|
+
function resetConfig() {
|
|
747
|
+
configVersion++;
|
|
748
|
+
globalConfig = defaultConfig();
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Merge a per-instance config override over a base resolved config.
|
|
752
|
+
* Only fields present in `override` are replaced; others fall through
|
|
753
|
+
* from `base`. `false` for tone windows passes through as-is
|
|
754
|
+
* (treated as the full range by `activeWindow()` in okhst.ts).
|
|
755
|
+
*
|
|
756
|
+
* `pastel` is instance-only: `override.pastel ?? false`, never inherited
|
|
757
|
+
* from the global base.
|
|
758
|
+
*/
|
|
759
|
+
function mergeConfig(base, override) {
|
|
760
|
+
if (!override) return base.pastel === false ? base : {
|
|
761
|
+
...base,
|
|
762
|
+
pastel: false
|
|
567
763
|
};
|
|
568
|
-
return coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter);
|
|
569
|
-
}
|
|
570
|
-
/**
|
|
571
|
-
* Fallback coarse scan when binary search is unstable near gamut edges.
|
|
572
|
-
*/
|
|
573
|
-
function coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter) {
|
|
574
|
-
const STEPS = 64;
|
|
575
|
-
const step = (hi - lo) / STEPS;
|
|
576
|
-
let bestL = lo;
|
|
577
|
-
let bestCr = 0;
|
|
578
|
-
let bestMet = false;
|
|
579
|
-
for (let i = 0; i <= STEPS; i++) {
|
|
580
|
-
const l = lo + step * i;
|
|
581
|
-
const cr = contrastRatioFromLuminance(cachedLuminance(h, s, l), yBase);
|
|
582
|
-
if (cr >= target && !bestMet) {
|
|
583
|
-
bestL = l;
|
|
584
|
-
bestCr = cr;
|
|
585
|
-
bestMet = true;
|
|
586
|
-
} else if (cr >= target && bestMet) {
|
|
587
|
-
bestL = l;
|
|
588
|
-
bestCr = cr;
|
|
589
|
-
} else if (!bestMet && cr > bestCr) {
|
|
590
|
-
bestL = l;
|
|
591
|
-
bestCr = cr;
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
if (bestMet && bestL > lo + step) {
|
|
595
|
-
let rLo = bestL - step;
|
|
596
|
-
let rHi = bestL;
|
|
597
|
-
for (let i = 0; i < maxIter; i++) {
|
|
598
|
-
if (rHi - rLo < epsilon) break;
|
|
599
|
-
const mid = (rLo + rHi) / 2;
|
|
600
|
-
const cr = contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase);
|
|
601
|
-
if (cr >= target) {
|
|
602
|
-
rHi = mid;
|
|
603
|
-
bestL = mid;
|
|
604
|
-
bestCr = cr;
|
|
605
|
-
} else rLo = mid;
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
764
|
return {
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
765
|
+
lightTone: override.lightTone !== void 0 ? override.lightTone : base.lightTone,
|
|
766
|
+
darkTone: override.darkTone !== void 0 ? override.darkTone : base.darkTone,
|
|
767
|
+
darkDesaturation: override.darkDesaturation ?? base.darkDesaturation,
|
|
768
|
+
states: base.states,
|
|
769
|
+
modes: base.modes,
|
|
770
|
+
shadowTuning: override.shadowTuning ?? base.shadowTuning,
|
|
771
|
+
autoFlip: override.autoFlip ?? base.autoFlip,
|
|
772
|
+
pastel: override.pastel ?? false,
|
|
773
|
+
inferRole: override.inferRole ?? base.inferRole
|
|
612
774
|
};
|
|
613
775
|
}
|
|
614
776
|
/**
|
|
615
|
-
*
|
|
616
|
-
*
|
|
777
|
+
* Freeze `getConfig() ∪ instanceLocal ∪ exportArg` as a plain, resolve-relevant
|
|
778
|
+
* override for authoring export, so restored snapshots pin these fields. Later
|
|
779
|
+
* wins; nested objects (`shadowTuning`) replace wholesale. The final
|
|
780
|
+
* `structuredClone` detaches tone-window / shadow objects that `mergeConfig`
|
|
781
|
+
* may still share with the live global config.
|
|
617
782
|
*/
|
|
618
|
-
function
|
|
619
|
-
const
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
const yBase = gamutClampedLuminance(baseLinearRgb);
|
|
623
|
-
const crPref = contrastRatioFromLuminance(cachedLuminance(hue, saturation, preferredLightness), yBase);
|
|
624
|
-
if (crPref >= searchTarget) return {
|
|
625
|
-
lightness: preferredLightness,
|
|
626
|
-
contrast: crPref,
|
|
627
|
-
met: true,
|
|
628
|
-
branch: "preferred"
|
|
629
|
-
};
|
|
630
|
-
const [minL, maxL] = lightnessRange;
|
|
631
|
-
const darkerResult = preferredLightness > minL ? searchBranch(hue, saturation, minL, preferredLightness, yBase, searchTarget, epsilon, maxIterations, preferredLightness) : null;
|
|
632
|
-
const lighterResult = preferredLightness < maxL ? searchBranch(hue, saturation, preferredLightness, maxL, yBase, searchTarget, epsilon, maxIterations, preferredLightness) : null;
|
|
633
|
-
if (darkerResult) darkerResult.met = darkerResult.contrast >= target;
|
|
634
|
-
if (lighterResult) lighterResult.met = lighterResult.contrast >= target;
|
|
635
|
-
const darkerPasses = darkerResult?.met ?? false;
|
|
636
|
-
const lighterPasses = lighterResult?.met ?? false;
|
|
637
|
-
if (darkerPasses && lighterPasses) {
|
|
638
|
-
if (Math.abs(darkerResult.lightness - preferredLightness) <= Math.abs(lighterResult.lightness - preferredLightness)) return {
|
|
639
|
-
...darkerResult,
|
|
640
|
-
branch: "darker"
|
|
641
|
-
};
|
|
642
|
-
return {
|
|
643
|
-
...lighterResult,
|
|
644
|
-
branch: "lighter"
|
|
645
|
-
};
|
|
646
|
-
}
|
|
647
|
-
if (darkerPasses) return {
|
|
648
|
-
...darkerResult,
|
|
649
|
-
branch: "darker"
|
|
650
|
-
};
|
|
651
|
-
if (lighterPasses) return {
|
|
652
|
-
...lighterResult,
|
|
653
|
-
branch: "lighter"
|
|
654
|
-
};
|
|
655
|
-
const candidates = [];
|
|
656
|
-
if (darkerResult) candidates.push({
|
|
657
|
-
...darkerResult,
|
|
658
|
-
branch: "darker"
|
|
659
|
-
});
|
|
660
|
-
if (lighterResult) candidates.push({
|
|
661
|
-
...lighterResult,
|
|
662
|
-
branch: "lighter"
|
|
783
|
+
function freezeConfigForExport(instanceLocal, exportArg) {
|
|
784
|
+
const effective = mergeConfig(getConfig(), {
|
|
785
|
+
...instanceLocal,
|
|
786
|
+
...exportArg
|
|
663
787
|
});
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
788
|
+
const out = {
|
|
789
|
+
lightTone: effective.lightTone,
|
|
790
|
+
darkTone: effective.darkTone,
|
|
791
|
+
darkDesaturation: effective.darkDesaturation,
|
|
792
|
+
autoFlip: effective.autoFlip,
|
|
793
|
+
pastel: effective.pastel,
|
|
794
|
+
inferRole: effective.inferRole
|
|
669
795
|
};
|
|
670
|
-
|
|
671
|
-
return
|
|
796
|
+
if (effective.shadowTuning !== void 0) out.shadowTuning = effective.shadowTuning;
|
|
797
|
+
return structuredClone(out);
|
|
672
798
|
}
|
|
799
|
+
|
|
800
|
+
//#endregion
|
|
801
|
+
//#region src/types.ts
|
|
673
802
|
/**
|
|
674
|
-
*
|
|
675
|
-
*
|
|
803
|
+
* Current authoring-export schema version. Bump when the export shape
|
|
804
|
+
* changes in a non-compatible way. Written on every `.export()` snapshot.
|
|
676
805
|
*/
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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
|
-
};
|
|
806
|
+
const GLAZE_EXPORT_VERSION = 1;
|
|
807
|
+
|
|
808
|
+
//#endregion
|
|
809
|
+
//#region src/serialize.ts
|
|
810
|
+
/**
|
|
811
|
+
* Authoring-export helpers: schema version, type guards, and restore
|
|
812
|
+
* validation shared by `themeFrom` / `colorFrom` / `paletteFrom`.
|
|
813
|
+
*/
|
|
814
|
+
function isPlainObject(data) {
|
|
815
|
+
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
737
816
|
}
|
|
738
817
|
/**
|
|
739
|
-
*
|
|
740
|
-
*
|
|
818
|
+
* Reject unknown / invalid schema versions. Missing `version` is allowed
|
|
819
|
+
* (legacy snapshots). Present versions must be an integer in
|
|
820
|
+
* `1..=GLAZE_EXPORT_VERSION`.
|
|
741
821
|
*/
|
|
742
|
-
function
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
if (
|
|
783
|
-
|
|
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
|
-
};
|
|
822
|
+
function assertExportVersion(data, factory) {
|
|
823
|
+
if (data.version === void 0) return;
|
|
824
|
+
if (typeof data.version !== "number" || !Number.isInteger(data.version) || data.version < 1) throw new Error(`${factory}: invalid "version" field — expected an integer >= 1 (got ${JSON.stringify(data.version)}).`);
|
|
825
|
+
if (data.version > GLAZE_EXPORT_VERSION) throw new Error(`${factory}: unsupported export version ${data.version} (this library supports version ${GLAZE_EXPORT_VERSION}). Upgrade @tenphi/glaze to load this snapshot.`);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* When `kind` is present, it must match the factory. Missing `kind` is
|
|
829
|
+
* allowed for legacy snapshots.
|
|
830
|
+
*/
|
|
831
|
+
function assertExportKind(data, expected, factory) {
|
|
832
|
+
if (data.kind === void 0) return;
|
|
833
|
+
if (data.kind !== expected) throw new Error(`${factory}: expected kind "${expected}", got ${JSON.stringify(data.kind)}.`);
|
|
834
|
+
}
|
|
835
|
+
function hasThemeShape(data) {
|
|
836
|
+
return typeof data.hue === "number" && typeof data.saturation === "number" && !("form" in data) && !("themes" in data);
|
|
837
|
+
}
|
|
838
|
+
function hasColorTokenShape(data) {
|
|
839
|
+
return data.form === "value" || data.form === "structured";
|
|
840
|
+
}
|
|
841
|
+
function hasPaletteShape(data) {
|
|
842
|
+
return isPlainObject(data.themes) && !("form" in data) && typeof data.hue !== "number";
|
|
843
|
+
}
|
|
844
|
+
/** Type guard for theme authoring snapshots (prefers `kind`, falls back to shape). */
|
|
845
|
+
function isThemeExport(data) {
|
|
846
|
+
if (!isPlainObject(data)) return false;
|
|
847
|
+
if (data.kind === "theme") return hasThemeShape(data);
|
|
848
|
+
if (data.kind !== void 0) return false;
|
|
849
|
+
return hasThemeShape(data);
|
|
850
|
+
}
|
|
851
|
+
/** Type guard for color-token authoring snapshots. */
|
|
852
|
+
function isColorTokenExport(data) {
|
|
853
|
+
if (!isPlainObject(data)) return false;
|
|
854
|
+
if (data.kind === "color") return hasColorTokenShape(data);
|
|
855
|
+
if (data.kind !== void 0) return false;
|
|
856
|
+
return hasColorTokenShape(data);
|
|
857
|
+
}
|
|
858
|
+
/** Type guard for palette authoring snapshots. */
|
|
859
|
+
function isPaletteExport(data) {
|
|
860
|
+
if (!isPlainObject(data)) return false;
|
|
861
|
+
if (data.kind === "palette") return hasPaletteShape(data);
|
|
862
|
+
if (data.kind !== void 0) return false;
|
|
863
|
+
return hasPaletteShape(data);
|
|
801
864
|
}
|
|
802
865
|
|
|
803
866
|
//#endregion
|
|
804
|
-
//#region src/
|
|
867
|
+
//#region src/format-guard.ts
|
|
868
|
+
const NON_NATIVE_FORMATS = new Set(["okhsl", "okhst"]);
|
|
805
869
|
/**
|
|
806
|
-
*
|
|
807
|
-
*
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
870
|
+
* Throw when a non-native Glaze color space is requested for an export that
|
|
871
|
+
* emits raw CSS or non-Tasty token maps.
|
|
872
|
+
*/
|
|
873
|
+
function assertNativeFormat(format, method) {
|
|
874
|
+
if (format !== void 0 && NON_NATIVE_FORMATS.has(format)) throw new Error(`glaze: ${format} output is only supported by tasty() (not a native CSS color space). Use tasty({ format: '${format}' }) or pick a native format (oklch|hsl|rgb) for ${method}().`);
|
|
875
|
+
}
|
|
876
|
+
const SCHEME_FIELDS = [
|
|
877
|
+
{
|
|
878
|
+
field: "light",
|
|
879
|
+
modes: () => true
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
field: "dark",
|
|
883
|
+
modes: (m) => m.dark
|
|
884
|
+
},
|
|
885
|
+
{
|
|
886
|
+
field: "lightContrast",
|
|
887
|
+
modes: (m) => m.highContrast
|
|
819
888
|
},
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
889
|
+
{
|
|
890
|
+
field: "darkContrast",
|
|
891
|
+
modes: (m) => m.dark && m.highContrast
|
|
823
892
|
}
|
|
824
|
-
|
|
893
|
+
];
|
|
894
|
+
/**
|
|
895
|
+
* Throw when `splitHue` is enabled but any exported color is not pastel.
|
|
896
|
+
* Hue rotation is only clip-free when chroma is bounded by the hue-independent
|
|
897
|
+
* safe chroma (`computeSafeChromaOKLCH`).
|
|
898
|
+
*/
|
|
899
|
+
function assertAllPastel(resolved, modes) {
|
|
900
|
+
const nonPastel = [];
|
|
901
|
+
for (const [name, color] of resolved) for (const { field, modes: active } of SCHEME_FIELDS) {
|
|
902
|
+
if (!active(modes)) continue;
|
|
903
|
+
if (color[field].pastel !== true) {
|
|
904
|
+
if (!nonPastel.includes(name)) nonPastel.push(name);
|
|
905
|
+
break;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
if (nonPastel.length === 0) return;
|
|
909
|
+
throw new Error(`glaze: splitHue requires every color to be pastel (hue rotation is only clip-free when chroma is bounded by the hue-independent safe chroma). Non-pastel: ${nonPastel.join(", ")}. Set pastel: true (per-theme, per-token, or per-color) or drop splitHue.`);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
//#endregion
|
|
913
|
+
//#region src/hc-pair.ts
|
|
825
914
|
function pairNormal(p) {
|
|
826
915
|
return Array.isArray(p) ? p[0] : p;
|
|
827
916
|
}
|
|
828
917
|
function pairHC(p) {
|
|
829
918
|
return Array.isArray(p) ? p[1] : p;
|
|
830
919
|
}
|
|
831
|
-
function
|
|
832
|
-
return
|
|
920
|
+
function clamp(v, min, max) {
|
|
921
|
+
return Math.max(min, Math.min(max, v));
|
|
833
922
|
}
|
|
834
|
-
|
|
835
|
-
|
|
923
|
+
/** Whether a tone value is an extreme keyword (`'max'` / `'min'`). */
|
|
924
|
+
function isExtremeTone(value) {
|
|
925
|
+
return value === "max" || value === "min";
|
|
836
926
|
}
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
};
|
|
847
|
-
function resolveShadowTuning(perColor) {
|
|
927
|
+
/**
|
|
928
|
+
* Parse a value that can be absolute (number) or relative (signed string).
|
|
929
|
+
* Returns the numeric value and whether it's relative.
|
|
930
|
+
*/
|
|
931
|
+
function parseRelativeOrAbsolute(value) {
|
|
932
|
+
if (typeof value === "number") return {
|
|
933
|
+
value,
|
|
934
|
+
relative: false
|
|
935
|
+
};
|
|
848
936
|
return {
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
937
|
+
value: parseFloat(value),
|
|
938
|
+
relative: true
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Parse a tone value into a normalized shape.
|
|
943
|
+
* - `'max'` / `'min'` → `{ kind: 'extreme', value: 100 | 0 }` (an absolute
|
|
944
|
+
* author tone before scheme mapping — `'max'` is 100, `'min'` is 0).
|
|
945
|
+
* - `'+N'` / `'-N'` → `{ kind: 'relative', value: ±N }`.
|
|
946
|
+
* - number → `{ kind: 'absolute', value }`.
|
|
947
|
+
*/
|
|
948
|
+
function parseToneValue(value) {
|
|
949
|
+
if (value === "max") return {
|
|
950
|
+
kind: "extreme",
|
|
951
|
+
value: 100
|
|
952
|
+
};
|
|
953
|
+
if (value === "min") return {
|
|
954
|
+
kind: "extreme",
|
|
955
|
+
value: 0
|
|
956
|
+
};
|
|
957
|
+
if (typeof value === "number") return {
|
|
958
|
+
kind: "absolute",
|
|
959
|
+
value
|
|
960
|
+
};
|
|
961
|
+
return {
|
|
962
|
+
kind: "relative",
|
|
963
|
+
value: parseFloat(value)
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Compute the effective hue for a color, given the theme seed hue
|
|
968
|
+
* and an optional per-color hue override.
|
|
969
|
+
*/
|
|
970
|
+
function resolveEffectiveHue(seedHue, defHue) {
|
|
971
|
+
if (defHue === void 0) return seedHue;
|
|
972
|
+
const parsed = parseRelativeOrAbsolute(defHue);
|
|
973
|
+
if (parsed.relative) return ((seedHue + parsed.value) % 360 + 360) % 360;
|
|
974
|
+
return (parsed.value % 360 + 360) % 360;
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* Check whether a tone value represents an absolute root definition
|
|
978
|
+
* (i.e. a number, not a relative string). Extreme keywords (`'max'` /
|
|
979
|
+
* `'min'`) also count — they need no base.
|
|
980
|
+
*/
|
|
981
|
+
function isAbsoluteTone(tone) {
|
|
982
|
+
if (tone === void 0) return false;
|
|
983
|
+
const normal = Array.isArray(tone) ? tone[0] : tone;
|
|
984
|
+
return typeof normal === "number" || isExtremeTone(normal);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
//#endregion
|
|
988
|
+
//#region src/okhst.ts
|
|
989
|
+
/**
|
|
990
|
+
* OKHST — the contrast-uniform tone space.
|
|
991
|
+
*
|
|
992
|
+
* OKHST is OKHSL with its lightness axis replaced by a contrast-uniform
|
|
993
|
+
* "tone" axis. It shares `h` / `s` with OKHSL verbatim and swaps `l` for
|
|
994
|
+
* `t`. This module owns:
|
|
995
|
+
*
|
|
996
|
+
* - the closed-form tone transfers (`toTone` / `fromTone`) at a fixed
|
|
997
|
+
* reference eps, plus the gray luminance helpers (`lToY` / `yToL`),
|
|
998
|
+
* - the `{ h, s, t }` <-> `{ h, s, l }` color-space converters,
|
|
999
|
+
* - the resolved-variant edge adapter (`variantToOkhsl`),
|
|
1000
|
+
* - the per-scheme tone mapping that replaced the Möbius dark curve
|
|
1001
|
+
* (`mapToneForScheme`), the dark desaturation reducer, and the solver's scheme
|
|
1002
|
+
* tone range.
|
|
1003
|
+
*
|
|
1004
|
+
* See `docs/okhst.md` for the full specification and the calibrated
|
|
1005
|
+
* default constants.
|
|
1006
|
+
*/
|
|
1007
|
+
/**
|
|
1008
|
+
* Reference eps for the OKHST color space. WCAG 2 contrast is
|
|
1009
|
+
* `(Y_hi + 0.05) / (Y_lo + 0.05)`, so an eps of `0.05` makes equal tone
|
|
1010
|
+
* steps yield equal WCAG contrast. This is the canonical eps used by
|
|
1011
|
+
* `okhst()` input, `{ h, s, t }` input, stored `ResolvedColorVariant.t`,
|
|
1012
|
+
* relative `tone` offsets, and the contrast solver.
|
|
1013
|
+
*/
|
|
1014
|
+
const REF_EPS = .05;
|
|
1015
|
+
/**
|
|
1016
|
+
* Gray luminance from OKHSL lightness. For an achromatic color the OKLab
|
|
1017
|
+
* lightness is `toeInv(l)` and luminance is its cube.
|
|
1018
|
+
*/
|
|
1019
|
+
function lToY(l) {
|
|
1020
|
+
const L = toeInv(l);
|
|
1021
|
+
return L * L * L;
|
|
1022
|
+
}
|
|
1023
|
+
/** OKHSL lightness from gray luminance — exact inverse of {@link lToY}. */
|
|
1024
|
+
function yToL(y) {
|
|
1025
|
+
return toe(Math.cbrt(Math.max(0, y)));
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Map a luminance `Y` (0–1) to tone (0–100) at the given eps.
|
|
1029
|
+
* `toneFromY(0) === 0` and `toneFromY(1) === 100` for any eps.
|
|
1030
|
+
*/
|
|
1031
|
+
function toneFromY(y, eps = REF_EPS) {
|
|
1032
|
+
return (Math.log(y + eps) - Math.log(eps)) / (Math.log(1 + eps) - Math.log(eps)) * 100;
|
|
1033
|
+
}
|
|
1034
|
+
/** Map a tone (0–100) back to luminance (0–1). Inverse of {@link toneFromY}. */
|
|
1035
|
+
function yFromTone(t, eps = REF_EPS) {
|
|
1036
|
+
const den = Math.log(1 + eps) - Math.log(eps);
|
|
1037
|
+
return Math.exp(t / 100 * den + Math.log(eps)) - eps;
|
|
1038
|
+
}
|
|
1039
|
+
/** OKHSL lightness (0–1) -> tone (0–100). */
|
|
1040
|
+
function toTone(l, eps = REF_EPS) {
|
|
1041
|
+
return toneFromY(lToY(l), eps);
|
|
1042
|
+
}
|
|
1043
|
+
/** Tone (0–100) -> OKHSL lightness (0–1). Inverse of {@link toTone}. */
|
|
1044
|
+
function fromTone(t, eps = REF_EPS) {
|
|
1045
|
+
return yToL(yFromTone(t, eps));
|
|
1046
|
+
}
|
|
1047
|
+
/** Convert OKHST `{ h, s, t }` (t in 0–1) to OKHSL `{ h, s, l }`. */
|
|
1048
|
+
function okhstToOkhsl(c) {
|
|
1049
|
+
return {
|
|
1050
|
+
h: c.h,
|
|
1051
|
+
s: c.s,
|
|
1052
|
+
l: clamp(fromTone(c.t * 100), 0, 1)
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/** Convert OKHSL `{ h, s, l }` to OKHST `{ h, s, t }` (t in 0–1). */
|
|
1056
|
+
function okhslToOkhst(c) {
|
|
1057
|
+
return {
|
|
1058
|
+
h: c.h,
|
|
1059
|
+
s: c.s,
|
|
1060
|
+
t: clamp(toTone(c.l) / 100, 0, 1)
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Edge adapter: a resolved variant stores canonical tone `t` (0–1). Convert
|
|
1065
|
+
* it to the OKHSL `{ h, s, l }` the formatters and luminance pipeline expect.
|
|
1066
|
+
*/
|
|
1067
|
+
function variantToOkhsl(v) {
|
|
1068
|
+
return {
|
|
1069
|
+
h: v.h,
|
|
1070
|
+
s: v.s,
|
|
1071
|
+
l: clamp(fromTone(v.t * 100), 0, 1)
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Normalize any {@link ToneWindow} form to `{ lo, hi, eps }`.
|
|
1076
|
+
* - `false`: full range `[0, 100]` at the reference eps (boundaries removed,
|
|
1077
|
+
* curve preserved).
|
|
1078
|
+
* - `[lo, hi]`: endpoints at the reference eps (the common form).
|
|
1079
|
+
* - `{ lo, hi, eps }`: passed through (advanced eps tuning).
|
|
1080
|
+
*/
|
|
1081
|
+
function normalizeToneWindow(win) {
|
|
1082
|
+
if (win === false) return {
|
|
1083
|
+
lo: 0,
|
|
1084
|
+
hi: 100,
|
|
1085
|
+
eps: REF_EPS
|
|
1086
|
+
};
|
|
1087
|
+
if (Array.isArray(win)) return {
|
|
1088
|
+
lo: win[0],
|
|
1089
|
+
hi: win[1],
|
|
1090
|
+
eps: REF_EPS
|
|
1091
|
+
};
|
|
1092
|
+
return {
|
|
1093
|
+
lo: win.lo,
|
|
1094
|
+
hi: win.hi,
|
|
1095
|
+
eps: win.eps
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Resolve the active tone window for a scheme as OKHSL-lightness endpoints.
|
|
1100
|
+
* - HC variants always return the full range `[0, 100]` with the mode eps.
|
|
1101
|
+
* - `false` (= "no clamping") is treated as `[0, 100]` with the reference eps.
|
|
1102
|
+
*/
|
|
1103
|
+
function activeWindow(isHighContrast, kind, config) {
|
|
1104
|
+
const win = normalizeToneWindow(kind === "dark" ? config.darkTone : config.lightTone);
|
|
1105
|
+
if (isHighContrast) return {
|
|
1106
|
+
lo: 0,
|
|
1107
|
+
hi: 100,
|
|
1108
|
+
eps: win.eps
|
|
1109
|
+
};
|
|
1110
|
+
return win;
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Remap an authored tone (0–100) into a scheme window and return the final
|
|
1114
|
+
* OKHSL lightness (0–100). The window endpoints are OKHSL lightnesses; the
|
|
1115
|
+
* author tone is positioned within the window's tone interval (using the
|
|
1116
|
+
* window's render eps), then converted back to lightness.
|
|
1117
|
+
*/
|
|
1118
|
+
function remapToneToLightness(authorTone, win) {
|
|
1119
|
+
const loT = toTone(win.lo / 100, win.eps);
|
|
1120
|
+
const hiT = toTone(win.hi / 100, win.eps);
|
|
1121
|
+
return clamp(fromTone(loT + authorTone / 100 * (hiT - loT), win.eps) * 100, 0, 100);
|
|
1122
|
+
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Map an authored tone for a scheme and return the canonical stored tone
|
|
1125
|
+
* (0–100, reference eps).
|
|
1126
|
+
*
|
|
1127
|
+
* - `static`: identity — the same tone renders in every scheme.
|
|
1128
|
+
* - `auto` + dark: invert (`100 - tone`) then remap into the dark window.
|
|
1129
|
+
* - `auto`/`fixed` + light, or `fixed` + dark: remap, no inversion.
|
|
1130
|
+
*
|
|
1131
|
+
* The window remap uses the mode's render eps to land a final OKHSL
|
|
1132
|
+
* lightness; that lightness is then re-expressed as canonical tone so
|
|
1133
|
+
* relative offsets and contrast stay comparable across schemes.
|
|
1134
|
+
*/
|
|
1135
|
+
function mapToneForScheme(authorTone, mode, isDark, isHighContrast, config) {
|
|
1136
|
+
if (mode === "static") return clamp(authorTone, 0, 100);
|
|
1137
|
+
const win = activeWindow(isHighContrast, isDark ? "dark" : "light", config);
|
|
1138
|
+
return clamp(toTone(remapToneToLightness(clamp(isDark && mode === "auto" ? 100 - authorTone : authorTone, 0, 100), win) / 100), 0, 100);
|
|
1139
|
+
}
|
|
1140
|
+
/** Dark-scheme desaturation reducer (unchanged from the legacy pipeline). */
|
|
1141
|
+
function mapSaturationDark(s, mode, config) {
|
|
1142
|
+
if (mode === "static") return s;
|
|
1143
|
+
return s * (1 - config.darkDesaturation);
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Tone search range (0–1) for the contrast solver in a given scheme.
|
|
1147
|
+
* `static` searches the full range; otherwise the scheme window's tone
|
|
1148
|
+
* endpoints (HC bypasses to full range).
|
|
1149
|
+
*/
|
|
1150
|
+
function schemeToneRange(isDark, mode, isHighContrast, config) {
|
|
1151
|
+
if (mode === "static") return [0, 1];
|
|
1152
|
+
const win = activeWindow(isHighContrast, isDark ? "dark" : "light", config);
|
|
1153
|
+
return [clamp(toTone(win.lo / 100) / 100, 0, 1), clamp(toTone(win.hi / 100) / 100, 0, 1)];
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
//#endregion
|
|
1157
|
+
//#region src/contrast-solver.ts
|
|
1158
|
+
/**
|
|
1159
|
+
* Contrast solver — operates in OKHST tone.
|
|
1160
|
+
*
|
|
1161
|
+
* Finds the tone closest to a preferred tone that satisfies a contrast
|
|
1162
|
+
* floor (WCAG 2 ratio or APCA Lc) against a base color. Because tone is
|
|
1163
|
+
* contrast-uniform, the WCAG branch gets a closed-form seed and the search
|
|
1164
|
+
* converges quickly.
|
|
1165
|
+
*
|
|
1166
|
+
* Public API: `findToneForContrast`, `findValueForMixContrast`,
|
|
1167
|
+
* `resolveMinContrast`, `resolveContrastForMode`, `apcaContrast`.
|
|
1168
|
+
*/
|
|
1169
|
+
/**
|
|
1170
|
+
* Luminance of a linear-sRGB color in the basis the metric expects: WCAG
|
|
1171
|
+
* relative luminance for `wcag`, APCA screen luminance (`Ys`) for `apca`.
|
|
1172
|
+
*/
|
|
1173
|
+
function metricLuminance(metric, linearRgb) {
|
|
1174
|
+
return metric === "apca" ? apcaLuminanceFromLinearRgb(linearRgb) : gamutClampedLuminance(linearRgb);
|
|
1175
|
+
}
|
|
1176
|
+
const APCA_PRESETS = {
|
|
1177
|
+
preferred: 90,
|
|
1178
|
+
body: 75,
|
|
1179
|
+
content: 60,
|
|
1180
|
+
large: 45,
|
|
1181
|
+
"non-text": 30,
|
|
1182
|
+
min: 15
|
|
1183
|
+
};
|
|
1184
|
+
/**
|
|
1185
|
+
* APCA-W3 "Enhanced Level" delta added to a bare APCA target in high-contrast
|
|
1186
|
+
* mode when no explicit HC value is provided (analogous to WCAG AAA over AA).
|
|
1187
|
+
* Only applied when neither the outer `contrast` pair nor the inner `apca`
|
|
1188
|
+
* pair carries an explicit HC entry.
|
|
1189
|
+
*/
|
|
1190
|
+
const APCA_HC_ENHANCEMENT = 15;
|
|
1191
|
+
/** Upper bound for an APCA Lc target after HC enhancement. */
|
|
1192
|
+
const APCA_MAX_LC = 106;
|
|
1193
|
+
/**
|
|
1194
|
+
* Resolve an APCA target — a raw Lc number (kept as-is) or an `ApcaPreset`
|
|
1195
|
+
* keyword mapped to its Lc value. The magnitude is forced non-negative.
|
|
1196
|
+
*/
|
|
1197
|
+
function resolveApcaTarget(value) {
|
|
1198
|
+
if (typeof value === "number") return Math.abs(value);
|
|
1199
|
+
return APCA_PRESETS[value];
|
|
1200
|
+
}
|
|
1201
|
+
const CONTRAST_PRESETS = {
|
|
1202
|
+
AA: 4.5,
|
|
1203
|
+
AAA: 7,
|
|
1204
|
+
"AA-large": 3,
|
|
1205
|
+
"AAA-large": 4.5
|
|
1206
|
+
};
|
|
1207
|
+
/**
|
|
1208
|
+
* WCAG high-contrast auto-promotion (analog of APCA's Enhanced Level). A bare
|
|
1209
|
+
* AA / AA-large preset is promoted to its spec-defined "Enhanced" successor
|
|
1210
|
+
* (SC 1.4.3 → SC 1.4.6) in high-contrast mode. AAA / AAA-large are already
|
|
1211
|
+
* the top WCAG tier and are left unchanged. Bare numeric targets have no
|
|
1212
|
+
* defined successor tier and are also left unchanged. An explicit HC value
|
|
1213
|
+
* (outer or inner pair) always overrides.
|
|
1214
|
+
*/
|
|
1215
|
+
const WCAG_HC_PROMOTION = {
|
|
1216
|
+
AA: "AAA",
|
|
1217
|
+
"AA-large": "AAA-large"
|
|
1218
|
+
};
|
|
1219
|
+
function resolveMinContrast(value) {
|
|
1220
|
+
if (typeof value === "number") return Math.max(1, value);
|
|
1221
|
+
return CONTRAST_PRESETS[value];
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Resolve a WCAG target (number or preset) for a mode, applying the
|
|
1225
|
+
* high-contrast auto-promotion when `explicitHC` is false and the value is an
|
|
1226
|
+
* AA-family preset. Bare numbers and AAA-family presets pass through.
|
|
1227
|
+
*/
|
|
1228
|
+
function resolveWcagTarget(value, isHighContrast, explicitHC) {
|
|
1229
|
+
if (typeof value === "number") return resolveMinContrast(value);
|
|
1230
|
+
if (isHighContrast && !explicitHC) {
|
|
1231
|
+
const promoted = WCAG_HC_PROMOTION[value];
|
|
1232
|
+
if (promoted !== void 0) return resolveMinContrast(promoted);
|
|
1233
|
+
}
|
|
1234
|
+
return resolveMinContrast(value);
|
|
1235
|
+
}
|
|
1236
|
+
function pickPair(p, isHighContrast) {
|
|
1237
|
+
return Array.isArray(p) ? isHighContrast ? p[1] : p[0] : p;
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Resolve a `ContrastSpec` (already selected from any outer HC pair) for a
|
|
1241
|
+
* given mode into `{ metric, target }`. Handles the inner metric HC pair and
|
|
1242
|
+
* preset resolution. `polarity` is passed through to the result for the APCA
|
|
1243
|
+
* branch (it controls argument order in the solver); WCAG ignores it.
|
|
1244
|
+
*
|
|
1245
|
+
* `outerExplicitHC` indicates whether the caller selected this `spec` from an
|
|
1246
|
+
* explicit high-contrast entry of the outer `contrast` pair. Together with the
|
|
1247
|
+
* inner metric pair, it decides whether the HC auto-enhancement fires:
|
|
1248
|
+
* - APCA: +15 Lc "Enhanced Level" boost when neither level is explicit.
|
|
1249
|
+
* - WCAG: AA → AAA / AA-large → AAA-large promotion (SC 1.4.3 → 1.4.6) when
|
|
1250
|
+
* neither level is explicit. AAA-family presets and bare numbers are left
|
|
1251
|
+
* unchanged (AAA is the top WCAG tier).
|
|
1252
|
+
* Defaults to `false` (correct for direct callers, which pass a single
|
|
1253
|
+
* selected spec rather than an outer pair).
|
|
1254
|
+
*/
|
|
1255
|
+
function resolveContrastForMode(spec, isHighContrast, polarity, outerExplicitHC) {
|
|
1256
|
+
if (typeof spec === "number" || typeof spec === "string") return {
|
|
1257
|
+
metric: "wcag",
|
|
1258
|
+
target: resolveWcagTarget(spec, isHighContrast, !!outerExplicitHC)
|
|
1259
|
+
};
|
|
1260
|
+
if ("apca" in spec) {
|
|
1261
|
+
const baseTarget = resolveApcaTarget(pickPair(spec.apca, isHighContrast));
|
|
1262
|
+
const innerExplicitHC = Array.isArray(spec.apca);
|
|
1263
|
+
return {
|
|
1264
|
+
metric: "apca",
|
|
1265
|
+
target: isHighContrast && !outerExplicitHC && !innerExplicitHC ? Math.min(baseTarget + APCA_HC_ENHANCEMENT, APCA_MAX_LC) : baseTarget,
|
|
1266
|
+
polarity: polarity ?? "fg"
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
const innerExplicitHC = Array.isArray(spec.wcag);
|
|
1270
|
+
return {
|
|
1271
|
+
metric: "wcag",
|
|
1272
|
+
target: resolveWcagTarget(pickPair(spec.wcag, isHighContrast), isHighContrast, !!outerExplicitHC || innerExplicitHC)
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
const APCA_EXPONENTS = {
|
|
1276
|
+
mainTRC: 2.4,
|
|
1277
|
+
normBG: .56,
|
|
1278
|
+
normTXT: .57,
|
|
1279
|
+
revTXT: .62,
|
|
1280
|
+
revBG: .65
|
|
1281
|
+
};
|
|
1282
|
+
const APCA_BLACK_THRESH = .022;
|
|
1283
|
+
const APCA_BLACK_CLIP = 1.414;
|
|
1284
|
+
const APCA_DELTA_Y_MIN = 5e-4;
|
|
1285
|
+
const APCA_SCALE = 1.14;
|
|
1286
|
+
const APCA_LO_OFFSET = .027;
|
|
1287
|
+
function apcaSoftClamp(y) {
|
|
1288
|
+
const yc = Math.max(0, y);
|
|
1289
|
+
if (yc >= APCA_BLACK_THRESH) return yc;
|
|
1290
|
+
return yc + Math.pow(APCA_BLACK_THRESH - yc, APCA_BLACK_CLIP);
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* APCA lightness contrast (Lc), signed: positive for dark text on light bg,
|
|
1294
|
+
* negative for light text on dark bg. Inputs are screen luminances (0–1).
|
|
1295
|
+
*/
|
|
1296
|
+
function apcaContrast(yText, yBg) {
|
|
1297
|
+
const txt = apcaSoftClamp(yText);
|
|
1298
|
+
const bg = apcaSoftClamp(yBg);
|
|
1299
|
+
if (Math.abs(bg - txt) < APCA_DELTA_Y_MIN) return 0;
|
|
1300
|
+
let sapc;
|
|
1301
|
+
if (bg > txt) {
|
|
1302
|
+
sapc = (Math.pow(bg, APCA_EXPONENTS.normBG) - Math.pow(txt, APCA_EXPONENTS.normTXT)) * APCA_SCALE;
|
|
1303
|
+
return sapc < .1 ? 0 : (sapc - APCA_LO_OFFSET) * 100;
|
|
1304
|
+
}
|
|
1305
|
+
sapc = (Math.pow(bg, APCA_EXPONENTS.revBG) - Math.pow(txt, APCA_EXPONENTS.revTXT)) * APCA_SCALE;
|
|
1306
|
+
return sapc > -.1 ? 0 : (sapc + APCA_LO_OFFSET) * 100;
|
|
1307
|
+
}
|
|
1308
|
+
const CACHE_SIZE = 512;
|
|
1309
|
+
const luminanceCache = /* @__PURE__ */ new Map();
|
|
1310
|
+
const cacheOrder = [];
|
|
1311
|
+
/**
|
|
1312
|
+
* Luminance of an OKHST color `(h, s, t)` with t in 0–1 (reference eps), in
|
|
1313
|
+
* the metric's luminance basis. The metric is part of the cache key because
|
|
1314
|
+
* WCAG and APCA derive different luminances from the same color.
|
|
1315
|
+
*/
|
|
1316
|
+
function cachedLuminance(metric, h, s, t, pastel) {
|
|
1317
|
+
const tRounded = Math.round(t * 1e4) / 1e4;
|
|
1318
|
+
const key = `${metric}|${h}|${s}|${tRounded}|${pastel}`;
|
|
1319
|
+
const cached = luminanceCache.get(key);
|
|
1320
|
+
if (cached !== void 0) return cached;
|
|
1321
|
+
const y = metricLuminance(metric, okhslToLinearSrgb(h, s, fromTone(tRounded * 100, REF_EPS), pastel));
|
|
1322
|
+
if (luminanceCache.size >= CACHE_SIZE) {
|
|
1323
|
+
const evict = cacheOrder.shift();
|
|
1324
|
+
luminanceCache.delete(evict);
|
|
1325
|
+
}
|
|
1326
|
+
luminanceCache.set(key, y);
|
|
1327
|
+
cacheOrder.push(key);
|
|
1328
|
+
return y;
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Score a candidate luminance against the base for a metric. Returns a value
|
|
1332
|
+
* that is `>= target` exactly when the floor is met (WCAG ratio, or APCA Lc
|
|
1333
|
+
* magnitude). For APCA, `polarity` selects the argument order: `'fg'` (the
|
|
1334
|
+
* default) treats the candidate as the text against a background base
|
|
1335
|
+
* (`apcaContrast(yCandidate, yBase)`); `'bg'` treats the candidate as the
|
|
1336
|
+
* background (`apcaContrast(yBase, yCandidate)`). The magnitude is taken
|
|
1337
|
+
* either way. WCAG is symmetric, so polarity is ignored there.
|
|
1338
|
+
*/
|
|
1339
|
+
function metricScore(metric, yCandidate, yBase, polarity) {
|
|
1340
|
+
if (metric === "wcag") return contrastRatioFromLuminance(yCandidate, yBase);
|
|
1341
|
+
const lc = polarity === "bg" ? apcaContrast(yBase, yCandidate) : apcaContrast(yCandidate, yBase);
|
|
1342
|
+
return Math.abs(lc);
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Binary search one branch `[lo, hi]` for the position nearest to `anchor`
|
|
1346
|
+
* that meets `target`. The domain is whatever `lum` interprets (tone 0–1 or
|
|
1347
|
+
* mix parameter 0–1); the search is identical in both cases.
|
|
1348
|
+
*/
|
|
1349
|
+
function searchBranch(lum, lo, hi, yBase, metric, target, epsilon, maxIter, anchor, polarity) {
|
|
1350
|
+
const scoreLo = metricScore(metric, lum(lo), yBase, polarity);
|
|
1351
|
+
const scoreHi = metricScore(metric, lum(hi), yBase, polarity);
|
|
1352
|
+
if (scoreLo < target && scoreHi < target) return scoreLo >= scoreHi ? {
|
|
1353
|
+
pos: lo,
|
|
1354
|
+
contrast: scoreLo,
|
|
1355
|
+
met: false
|
|
1356
|
+
} : {
|
|
1357
|
+
pos: hi,
|
|
1358
|
+
contrast: scoreHi,
|
|
1359
|
+
met: false
|
|
1360
|
+
};
|
|
1361
|
+
let low = lo;
|
|
1362
|
+
let high = hi;
|
|
1363
|
+
for (let i = 0; i < maxIter; i++) {
|
|
1364
|
+
if (high - low < epsilon) break;
|
|
1365
|
+
const mid = (low + high) / 2;
|
|
1366
|
+
if (metricScore(metric, lum(mid), yBase, polarity) >= target) if (mid < anchor) low = mid;
|
|
1367
|
+
else high = mid;
|
|
1368
|
+
else if (mid < anchor) high = mid;
|
|
1369
|
+
else low = mid;
|
|
1370
|
+
}
|
|
1371
|
+
const scoreLow = metricScore(metric, lum(low), yBase, polarity);
|
|
1372
|
+
const scoreHigh = metricScore(metric, lum(high), yBase, polarity);
|
|
1373
|
+
const lowPasses = scoreLow >= target;
|
|
1374
|
+
const highPasses = scoreHigh >= target;
|
|
1375
|
+
if (lowPasses && highPasses) return Math.abs(low - anchor) <= Math.abs(high - anchor) ? {
|
|
1376
|
+
pos: low,
|
|
1377
|
+
contrast: scoreLow,
|
|
1378
|
+
met: true
|
|
1379
|
+
} : {
|
|
1380
|
+
pos: high,
|
|
1381
|
+
contrast: scoreHigh,
|
|
1382
|
+
met: true
|
|
1383
|
+
};
|
|
1384
|
+
if (lowPasses) return {
|
|
1385
|
+
pos: low,
|
|
1386
|
+
contrast: scoreLow,
|
|
1387
|
+
met: true
|
|
1388
|
+
};
|
|
1389
|
+
if (highPasses) return {
|
|
1390
|
+
pos: high,
|
|
1391
|
+
contrast: scoreHigh,
|
|
1392
|
+
met: true
|
|
1393
|
+
};
|
|
1394
|
+
return scoreLow >= scoreHigh ? {
|
|
1395
|
+
pos: low,
|
|
1396
|
+
contrast: scoreLow,
|
|
1397
|
+
met: false
|
|
1398
|
+
} : {
|
|
1399
|
+
pos: high,
|
|
1400
|
+
contrast: scoreHigh,
|
|
1401
|
+
met: false
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Closed-form WCAG tone seed: the gray tone whose luminance produces exactly
|
|
1406
|
+
* the target ratio against the base, on the requested side. Used to bias the
|
|
1407
|
+
* preferred tone before the search so chromatic refinement starts close.
|
|
1408
|
+
*/
|
|
1409
|
+
function wcagToneSeed(yBase, target, darker) {
|
|
1410
|
+
const yTarget = darker ? (yBase + .05) / target - .05 : target * (yBase + .05) - .05;
|
|
1411
|
+
const yClamped = Math.max(0, Math.min(1, yTarget));
|
|
1412
|
+
return Math.max(0, Math.min(1, toneFromY(yClamped, REF_EPS) / 100));
|
|
1413
|
+
}
|
|
1414
|
+
function solveNearestContrast(opts) {
|
|
1415
|
+
const { lum, yBase, metric, target, searchTarget, lo, hi, searchAnchor, distanceAnchor, epsilon, maxIterations, flip, initialIsLower, polarity } = opts;
|
|
1416
|
+
const runBranch = (lower) => lower ? searchBranch(lum, lo, searchAnchor, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity) : searchBranch(lum, searchAnchor, hi, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity);
|
|
1417
|
+
const initialResult = runBranch(initialIsLower);
|
|
1418
|
+
initialResult.met = initialResult.contrast >= target;
|
|
1419
|
+
if (initialResult.met && !flip) return {
|
|
1420
|
+
...initialResult,
|
|
1421
|
+
lower: initialIsLower
|
|
1422
|
+
};
|
|
1423
|
+
if (flip) {
|
|
1424
|
+
const oppositeResult = (initialIsLower ? distanceAnchor < hi : distanceAnchor > lo) ? runBranch(!initialIsLower) : null;
|
|
1425
|
+
if (oppositeResult) oppositeResult.met = oppositeResult.contrast >= target;
|
|
1426
|
+
if (initialResult.met && oppositeResult?.met) return Math.abs(initialResult.pos - distanceAnchor) <= Math.abs(oppositeResult.pos - distanceAnchor) ? {
|
|
1427
|
+
...initialResult,
|
|
1428
|
+
lower: initialIsLower
|
|
1429
|
+
} : {
|
|
1430
|
+
...oppositeResult,
|
|
1431
|
+
lower: !initialIsLower,
|
|
1432
|
+
flipped: true
|
|
1433
|
+
};
|
|
1434
|
+
if (initialResult.met) return {
|
|
1435
|
+
...initialResult,
|
|
1436
|
+
lower: initialIsLower
|
|
1437
|
+
};
|
|
1438
|
+
if (oppositeResult?.met) return {
|
|
1439
|
+
...oppositeResult,
|
|
1440
|
+
lower: !initialIsLower,
|
|
1441
|
+
flipped: true
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
const extreme = initialIsLower ? lo : hi;
|
|
1445
|
+
return {
|
|
1446
|
+
pos: extreme,
|
|
1447
|
+
contrast: metricScore(metric, lum(extreme), yBase, polarity),
|
|
1448
|
+
met: false,
|
|
1449
|
+
lower: initialIsLower
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Find the tone that satisfies a contrast floor against a base color,
|
|
1454
|
+
* staying as close to `preferredTone` as possible.
|
|
1455
|
+
*/
|
|
1456
|
+
function findToneForContrast(options) {
|
|
1457
|
+
const { hue, saturation, preferredTone, baseLinearRgb, contrast, toneRange = [0, 1], epsilon = 1e-4, maxIterations = 18, pastel = false } = options;
|
|
1458
|
+
const { metric, target, polarity } = contrast;
|
|
1459
|
+
const searchTarget = metric === "wcag" ? target * 1.01 : target + .5;
|
|
1460
|
+
const yBase = metricLuminance(metric, baseLinearRgb);
|
|
1461
|
+
const lum = (t) => cachedLuminance(metric, hue, saturation, t, pastel);
|
|
1462
|
+
const scorePref = metricScore(metric, lum(preferredTone), yBase, polarity);
|
|
1463
|
+
if (scorePref >= searchTarget) return {
|
|
1464
|
+
tone: preferredTone,
|
|
1465
|
+
contrast: scorePref,
|
|
1466
|
+
met: true,
|
|
1467
|
+
branch: "preferred"
|
|
1468
|
+
};
|
|
1469
|
+
const [minT, maxT] = toneRange;
|
|
1470
|
+
const canDarker = preferredTone > minT;
|
|
1471
|
+
const canLighter = preferredTone < maxT;
|
|
1472
|
+
let initialIsDarker;
|
|
1473
|
+
if (options.initialDirection !== void 0) initialIsDarker = options.initialDirection === "darker";
|
|
1474
|
+
else if (canDarker && !canLighter) initialIsDarker = true;
|
|
1475
|
+
else if (!canDarker && canLighter) initialIsDarker = false;
|
|
1476
|
+
else if (!canDarker && !canLighter) return {
|
|
1477
|
+
tone: preferredTone,
|
|
1478
|
+
contrast: scorePref,
|
|
1479
|
+
met: false,
|
|
1480
|
+
branch: "preferred"
|
|
1481
|
+
};
|
|
1482
|
+
else initialIsDarker = metricScore(metric, lum(minT), yBase, polarity) >= metricScore(metric, lum(maxT), yBase, polarity);
|
|
1483
|
+
const solved = solveNearestContrast({
|
|
1484
|
+
lum,
|
|
1485
|
+
yBase,
|
|
1486
|
+
metric,
|
|
1487
|
+
target,
|
|
1488
|
+
searchTarget,
|
|
1489
|
+
lo: minT,
|
|
1490
|
+
hi: maxT,
|
|
1491
|
+
searchAnchor: metric === "wcag" ? clamp(initialIsDarker ? Math.min(preferredTone, wcagToneSeed(yBase, target, true)) : Math.max(preferredTone, wcagToneSeed(yBase, target, false)), minT, maxT) : preferredTone,
|
|
1492
|
+
distanceAnchor: preferredTone,
|
|
1493
|
+
epsilon,
|
|
1494
|
+
maxIterations,
|
|
1495
|
+
flip: options.flip ?? false,
|
|
1496
|
+
initialIsLower: initialIsDarker,
|
|
1497
|
+
polarity
|
|
1498
|
+
});
|
|
1499
|
+
return {
|
|
1500
|
+
tone: solved.pos,
|
|
1501
|
+
contrast: solved.contrast,
|
|
1502
|
+
met: solved.met,
|
|
1503
|
+
branch: solved.lower ? "darker" : "lighter",
|
|
1504
|
+
...solved.flipped ? { flipped: true } : {}
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Find the mix parameter (ratio or opacity) that satisfies a contrast floor
|
|
1509
|
+
* against a base color, staying as close to `preferredValue` as possible.
|
|
1510
|
+
*/
|
|
1511
|
+
function findValueForMixContrast(options) {
|
|
1512
|
+
const { preferredValue, baseLinearRgb, contrast, luminanceAtValue, epsilon = 1e-4, maxIterations = 20 } = options;
|
|
1513
|
+
const { metric, target, polarity } = contrast;
|
|
1514
|
+
const searchTarget = metric === "wcag" ? target * 1.01 : target + .5;
|
|
1515
|
+
const yBase = metricLuminance(metric, baseLinearRgb);
|
|
1516
|
+
const scorePref = metricScore(metric, luminanceAtValue(preferredValue), yBase, polarity);
|
|
1517
|
+
if (scorePref >= searchTarget) return {
|
|
1518
|
+
value: preferredValue,
|
|
1519
|
+
contrast: scorePref,
|
|
1520
|
+
met: true
|
|
1521
|
+
};
|
|
1522
|
+
const canLower = preferredValue > 0;
|
|
1523
|
+
const canUpper = preferredValue < 1;
|
|
1524
|
+
let initialIsLower;
|
|
1525
|
+
if (canLower && !canUpper) initialIsLower = true;
|
|
1526
|
+
else if (!canLower && canUpper) initialIsLower = false;
|
|
1527
|
+
else if (!canLower && !canUpper) return {
|
|
1528
|
+
value: preferredValue,
|
|
1529
|
+
contrast: scorePref,
|
|
1530
|
+
met: false
|
|
1531
|
+
};
|
|
1532
|
+
else initialIsLower = metricScore(metric, luminanceAtValue(0), yBase, polarity) >= metricScore(metric, luminanceAtValue(1), yBase, polarity);
|
|
1533
|
+
const solved = solveNearestContrast({
|
|
1534
|
+
lum: luminanceAtValue,
|
|
1535
|
+
yBase,
|
|
1536
|
+
metric,
|
|
1537
|
+
target,
|
|
1538
|
+
searchTarget,
|
|
1539
|
+
lo: 0,
|
|
1540
|
+
hi: 1,
|
|
1541
|
+
searchAnchor: preferredValue,
|
|
1542
|
+
distanceAnchor: preferredValue,
|
|
1543
|
+
epsilon,
|
|
1544
|
+
maxIterations,
|
|
1545
|
+
flip: options.flip ?? false,
|
|
1546
|
+
initialIsLower,
|
|
1547
|
+
polarity
|
|
1548
|
+
});
|
|
1549
|
+
return {
|
|
1550
|
+
value: solved.pos,
|
|
1551
|
+
contrast: solved.contrast,
|
|
1552
|
+
met: solved.met,
|
|
1553
|
+
...solved.flipped ? { flipped: true } : {}
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
//#endregion
|
|
1558
|
+
//#region src/roles.ts
|
|
1559
|
+
const SURFACE_KEYWORDS = new Set([
|
|
1560
|
+
"surface",
|
|
1561
|
+
"bg",
|
|
1562
|
+
"background",
|
|
1563
|
+
"fill",
|
|
1564
|
+
"canvas",
|
|
1565
|
+
"paper",
|
|
1566
|
+
"layer"
|
|
1567
|
+
]);
|
|
1568
|
+
const TEXT_KEYWORDS = new Set([
|
|
1569
|
+
"text",
|
|
1570
|
+
"fg",
|
|
1571
|
+
"foreground",
|
|
1572
|
+
"content",
|
|
1573
|
+
"ink",
|
|
1574
|
+
"label",
|
|
1575
|
+
"stroke"
|
|
1576
|
+
]);
|
|
1577
|
+
const BORDER_KEYWORDS = new Set([
|
|
1578
|
+
"border",
|
|
1579
|
+
"divider",
|
|
1580
|
+
"outline",
|
|
1581
|
+
"separator",
|
|
1582
|
+
"hairline",
|
|
1583
|
+
"rule"
|
|
1584
|
+
]);
|
|
1585
|
+
const ALIAS_TO_ROLE = {
|
|
1586
|
+
surface: "surface",
|
|
1587
|
+
bg: "surface",
|
|
1588
|
+
background: "surface",
|
|
1589
|
+
fill: "surface",
|
|
1590
|
+
canvas: "surface",
|
|
1591
|
+
paper: "surface",
|
|
1592
|
+
layer: "surface",
|
|
1593
|
+
text: "text",
|
|
1594
|
+
fg: "text",
|
|
1595
|
+
foreground: "text",
|
|
1596
|
+
content: "text",
|
|
1597
|
+
ink: "text",
|
|
1598
|
+
label: "text",
|
|
1599
|
+
stroke: "text",
|
|
1600
|
+
border: "border",
|
|
1601
|
+
divider: "border",
|
|
1602
|
+
outline: "border",
|
|
1603
|
+
separator: "border",
|
|
1604
|
+
hairline: "border",
|
|
1605
|
+
rule: "border"
|
|
1606
|
+
};
|
|
1607
|
+
/**
|
|
1608
|
+
* Normalize a `RoleInput` (canonical value or alias) into a canonical `Role`.
|
|
1609
|
+
* Returns `undefined` for unrecognized strings so callers can fall through to
|
|
1610
|
+
* the next step of the resolution chain.
|
|
1611
|
+
*/
|
|
1612
|
+
function normalizeRole(input) {
|
|
1613
|
+
if (input === void 0) return void 0;
|
|
1614
|
+
return ALIAS_TO_ROLE[input];
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Tokenize a color name into lowercase keyword tokens, splitting on
|
|
1618
|
+
* non-alphanumeric boundaries and at camelCase boundaries. Examples:
|
|
1619
|
+
* - `'button-text'` → `['button', 'text']`
|
|
1620
|
+
* - `'inputBg'` → `['input', 'bg']`
|
|
1621
|
+
* - `'card_border-outline'` → `['card', 'border', 'outline']`
|
|
1622
|
+
*/
|
|
1623
|
+
function tokenizeName(name) {
|
|
1624
|
+
const pieces = name.split(/[^0-9a-zA-Z]+/).filter(Boolean);
|
|
1625
|
+
const tokens = [];
|
|
1626
|
+
for (const piece of pieces) {
|
|
1627
|
+
const sub = piece.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/\s+/).filter(Boolean);
|
|
1628
|
+
for (const s of sub) tokens.push(s.toLowerCase());
|
|
1629
|
+
}
|
|
1630
|
+
return tokens;
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Infer a `Role` from a color name by matching its tokens against the role
|
|
1634
|
+
* keyword sets. When multiple tokens match, the **last** recognized token
|
|
1635
|
+
* wins (so `button-text` → `text`, `input-bg` → `surface`, `card-border` →
|
|
1636
|
+
* `border`). Returns `undefined` when no token matches.
|
|
1637
|
+
*/
|
|
1638
|
+
function inferRoleFromName(name) {
|
|
1639
|
+
const tokens = tokenizeName(name);
|
|
1640
|
+
let inferred;
|
|
1641
|
+
for (const token of tokens) if (SURFACE_KEYWORDS.has(token)) inferred = "surface";
|
|
1642
|
+
else if (TEXT_KEYWORDS.has(token)) inferred = "text";
|
|
1643
|
+
else if (BORDER_KEYWORDS.has(token)) inferred = "border";
|
|
1644
|
+
return inferred;
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Map a role to its APCA polarity. `text` and `border` are foreground spots
|
|
1648
|
+
* against their base (the candidate is the text argument); `surface` is the
|
|
1649
|
+
* background (the base is the text argument).
|
|
1650
|
+
*/
|
|
1651
|
+
function roleToPolarity(role) {
|
|
1652
|
+
return role === "surface" ? "bg" : "fg";
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* The opposite role of `role`, used when a color with no explicit role and no
|
|
1656
|
+
* inferable name depends on a base: the dependent color plays the opposite
|
|
1657
|
+
* role of its base. `surface` ↔ `text`; `border` is treated as a foreground
|
|
1658
|
+
* spot, so its opposite is `surface`.
|
|
1659
|
+
*/
|
|
1660
|
+
function oppositeRole(role) {
|
|
1661
|
+
if (role === "surface") return "text";
|
|
1662
|
+
return "surface";
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
//#endregion
|
|
1666
|
+
//#region src/shadow.ts
|
|
1667
|
+
/**
|
|
1668
|
+
* Shadow color computation.
|
|
1669
|
+
*
|
|
1670
|
+
* Owns the shadow / mix def predicates, default tuning constants, the
|
|
1671
|
+
* tuning merge, and the actual `computeShadow` math (hue blend,
|
|
1672
|
+
* saturation cap, lightness clamp, alpha curve). The resolver consumes
|
|
1673
|
+
* this module per scheme variant.
|
|
1674
|
+
*/
|
|
1675
|
+
function isShadowDef(def) {
|
|
1676
|
+
return def.type === "shadow";
|
|
1677
|
+
}
|
|
1678
|
+
function isMixDef(def) {
|
|
1679
|
+
return def.type === "mix";
|
|
1680
|
+
}
|
|
1681
|
+
const DEFAULT_SHADOW_TUNING = {
|
|
1682
|
+
saturationFactor: .18,
|
|
1683
|
+
maxSaturation: .25,
|
|
1684
|
+
lightnessFactor: .25,
|
|
1685
|
+
lightnessBounds: [.05, .2],
|
|
1686
|
+
minGapTarget: .05,
|
|
1687
|
+
alphaMax: 1,
|
|
1688
|
+
bgHueBlend: .2
|
|
1689
|
+
};
|
|
1690
|
+
function resolveShadowTuning(perColor, globalTuning) {
|
|
1691
|
+
return {
|
|
1692
|
+
...DEFAULT_SHADOW_TUNING,
|
|
1693
|
+
...globalTuning,
|
|
1694
|
+
...perColor,
|
|
1695
|
+
lightnessBounds: perColor?.lightnessBounds ?? globalTuning?.lightnessBounds ?? DEFAULT_SHADOW_TUNING.lightnessBounds
|
|
853
1696
|
};
|
|
854
1697
|
}
|
|
855
1698
|
function circularLerp(a, b, t) {
|
|
@@ -890,36 +1733,49 @@ function computeShadow(bg, fg, intensity, tuning) {
|
|
|
890
1733
|
alpha
|
|
891
1734
|
};
|
|
892
1735
|
}
|
|
893
|
-
|
|
894
|
-
|
|
1736
|
+
|
|
1737
|
+
//#endregion
|
|
1738
|
+
//#region src/validation.ts
|
|
1739
|
+
/**
|
|
1740
|
+
* Color graph validation and topological sort.
|
|
1741
|
+
*
|
|
1742
|
+
* `validateColorDefs` rejects bad references (missing / shadow-referencing /
|
|
1743
|
+
* base/contrast/tone mismatches) and detects cycles before the
|
|
1744
|
+
* resolver runs. `topoSort` orders defs so each color is processed after
|
|
1745
|
+
* its base / bg / fg / target dependencies.
|
|
1746
|
+
*/
|
|
1747
|
+
function validateColorDefs(defs, externalBases) {
|
|
1748
|
+
const localNames = new Set(Object.keys(defs));
|
|
1749
|
+
const allNames = new Set([...localNames, ...externalBases ? externalBases.keys() : []]);
|
|
895
1750
|
for (const [name, def] of Object.entries(defs)) {
|
|
896
1751
|
if (isShadowDef(def)) {
|
|
897
|
-
if (!
|
|
898
|
-
if (isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
|
|
1752
|
+
if (!allNames.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
|
|
1753
|
+
if (localNames.has(def.bg) && isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
|
|
899
1754
|
if (def.fg !== void 0) {
|
|
900
|
-
if (!
|
|
901
|
-
if (isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
|
|
1755
|
+
if (!allNames.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
|
|
1756
|
+
if (localNames.has(def.fg) && isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
|
|
902
1757
|
}
|
|
903
1758
|
continue;
|
|
904
1759
|
}
|
|
905
1760
|
if (isMixDef(def)) {
|
|
906
|
-
if (!
|
|
907
|
-
if (!
|
|
908
|
-
if (isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
|
|
909
|
-
if (isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
|
|
1761
|
+
if (!allNames.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
|
|
1762
|
+
if (!allNames.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
|
|
1763
|
+
if (localNames.has(def.base) && isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
|
|
1764
|
+
if (localNames.has(def.target) && isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
|
|
910
1765
|
continue;
|
|
911
1766
|
}
|
|
912
1767
|
const regDef = def;
|
|
913
1768
|
if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
|
|
914
|
-
if (regDef.
|
|
915
|
-
if (regDef.base && !
|
|
916
|
-
if (regDef.base && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
|
|
917
|
-
if (!
|
|
918
|
-
if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived
|
|
1769
|
+
if (regDef.tone !== void 0 && !isAbsoluteTone(regDef.tone) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "tone" without "base".`);
|
|
1770
|
+
if (regDef.base && !allNames.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
|
|
1771
|
+
if (regDef.base && localNames.has(regDef.base) && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
|
|
1772
|
+
if (!isAbsoluteTone(regDef.tone) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "tone" (root) or "base" (dependent).`);
|
|
1773
|
+
if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived tone unpredictable.`);
|
|
919
1774
|
}
|
|
920
1775
|
const visited = /* @__PURE__ */ new Set();
|
|
921
1776
|
const inStack = /* @__PURE__ */ new Set();
|
|
922
1777
|
function dfs(name) {
|
|
1778
|
+
if (!localNames.has(name)) return;
|
|
923
1779
|
if (inStack.has(name)) throw new Error(`glaze: circular base reference detected involving "${name}".`);
|
|
924
1780
|
if (visited.has(name)) return;
|
|
925
1781
|
inStack.add(name);
|
|
@@ -937,7 +1793,7 @@ function validateColorDefs(defs) {
|
|
|
937
1793
|
inStack.delete(name);
|
|
938
1794
|
visited.add(name);
|
|
939
1795
|
}
|
|
940
|
-
for (const name of
|
|
1796
|
+
for (const name of localNames) dfs(name);
|
|
941
1797
|
}
|
|
942
1798
|
function topoSort(defs) {
|
|
943
1799
|
const result = [];
|
|
@@ -946,6 +1802,7 @@ function topoSort(defs) {
|
|
|
946
1802
|
if (visited.has(name)) return;
|
|
947
1803
|
visited.add(name);
|
|
948
1804
|
const def = defs[name];
|
|
1805
|
+
if (def === void 0) return;
|
|
949
1806
|
if (isShadowDef(def)) {
|
|
950
1807
|
visit(def.bg);
|
|
951
1808
|
if (def.fg) visit(def.fg);
|
|
@@ -961,191 +1818,282 @@ function topoSort(defs) {
|
|
|
961
1818
|
for (const name of Object.keys(defs)) visit(name);
|
|
962
1819
|
return result;
|
|
963
1820
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1821
|
+
|
|
1822
|
+
//#endregion
|
|
1823
|
+
//#region src/warnings.ts
|
|
1824
|
+
/**
|
|
1825
|
+
* Contrast-warning dispatcher.
|
|
1826
|
+
*
|
|
1827
|
+
* Tokens memoize their resolution, but a long-lived process (e.g. a dev
|
|
1828
|
+
* server with HMR) can re-resolve the same theme many times. The cache
|
|
1829
|
+
* here dedupes warnings within a session with a soft cap to keep noise
|
|
1830
|
+
* bounded.
|
|
1831
|
+
*/
|
|
1832
|
+
const CONTRAST_WARN_CACHE_LIMIT = 256;
|
|
1833
|
+
const contrastWarnCache = /* @__PURE__ */ new Set();
|
|
1834
|
+
/**
|
|
1835
|
+
* Slack factor below the requested target before we emit a warning.
|
|
1836
|
+
* The contrast solver overshoots to absorb rounding noise, so an actual
|
|
1837
|
+
* value within ~2x that overshoot is effectively a pass.
|
|
1838
|
+
*/
|
|
1839
|
+
const CONTRAST_WARN_SLACK_WCAG = .98;
|
|
1840
|
+
/** APCA Lc is on a 0–106 scale; allow a small absolute slack. */
|
|
1841
|
+
const CONTRAST_WARN_SLACK_APCA = 1.5;
|
|
1842
|
+
function schemeLabel(isDark, isHighContrast) {
|
|
1843
|
+
if (isDark && isHighContrast) return "darkContrast";
|
|
1844
|
+
if (isDark) return "dark";
|
|
1845
|
+
if (isHighContrast) return "lightContrast";
|
|
1846
|
+
return "light";
|
|
1847
|
+
}
|
|
1848
|
+
function metricLabel(c) {
|
|
1849
|
+
return c.metric === "apca" ? `APCA Lc ${c.target.toFixed(1)}` : `WCAG ${c.target.toFixed(2)}`;
|
|
1850
|
+
}
|
|
1851
|
+
function dedupe(key) {
|
|
1852
|
+
if (contrastWarnCache.has(key)) return true;
|
|
1853
|
+
if (contrastWarnCache.size >= CONTRAST_WARN_CACHE_LIMIT) contrastWarnCache.clear();
|
|
1854
|
+
contrastWarnCache.add(key);
|
|
1855
|
+
return false;
|
|
1856
|
+
}
|
|
1857
|
+
/** Warn when the solver could not reach the requested contrast floor. */
|
|
1858
|
+
function warnContrastUnmet(name, isDark, isHighContrast, contrast, actual) {
|
|
1859
|
+
if (actual >= (contrast.metric === "apca" ? contrast.target - CONTRAST_WARN_SLACK_APCA : contrast.target * CONTRAST_WARN_SLACK_WCAG)) return;
|
|
1860
|
+
const scheme = schemeLabel(isDark, isHighContrast);
|
|
1861
|
+
if (dedupe(`unmet|${name}|${scheme}|${contrast.metric}|${contrast.target.toFixed(2)}|${actual.toFixed(2)}`)) return;
|
|
1862
|
+
console.warn(`glaze: color "${name}" cannot meet ${metricLabel(contrast)} in ${scheme} scheme (got ${actual.toFixed(2)}). Try widening the tone window, lowering the contrast target, or picking a base color further from this color's tone.`);
|
|
1001
1863
|
}
|
|
1002
|
-
|
|
1003
|
-
|
|
1864
|
+
/**
|
|
1865
|
+
* Verification (§10): a chromatic swatch inherits the gray tone's
|
|
1866
|
+
* lightness but drifts in real luminance, so a contrast-floored color may
|
|
1867
|
+
* land slightly under the contrast its tone implies. Emit an advisory
|
|
1868
|
+
* warning when the actual measured contrast drifts below the target.
|
|
1869
|
+
*/
|
|
1870
|
+
function warnContrastDrift(name, isDark, isHighContrast, contrast, yColor, yBase) {
|
|
1871
|
+
const actual = contrast.metric === "apca" ? Math.abs(contrast.polarity === "bg" ? apcaContrast(yBase, yColor) : apcaContrast(yColor, yBase)) : contrastRatioFromLuminance(yColor, yBase);
|
|
1872
|
+
if (actual >= (contrast.metric === "apca" ? contrast.target - CONTRAST_WARN_SLACK_APCA : contrast.target * CONTRAST_WARN_SLACK_WCAG)) return;
|
|
1873
|
+
const scheme = schemeLabel(isDark, isHighContrast);
|
|
1874
|
+
if (dedupe(`drift|${name}|${scheme}|${contrast.metric}|${contrast.target.toFixed(2)}|${actual.toFixed(2)}`)) return;
|
|
1875
|
+
console.warn(`glaze: color "${name}" drifts below ${metricLabel(contrast)} in ${scheme} scheme (measured ${actual.toFixed(2)}). Chromatic luminance differs from the gray tone; nudge the tone or saturation if the floor matters.`);
|
|
1004
1876
|
}
|
|
1877
|
+
|
|
1878
|
+
//#endregion
|
|
1879
|
+
//#region src/resolver.ts
|
|
1005
1880
|
/**
|
|
1006
|
-
*
|
|
1007
|
-
*
|
|
1881
|
+
* Color resolution engine.
|
|
1882
|
+
*
|
|
1883
|
+
* Runs the four-pass solver (light → light-HC → dark → dark-HC) that
|
|
1884
|
+
* turns a `ColorMap` into a fully resolved `ResolvedColor` per name.
|
|
1885
|
+
* Owns the per-scheme resolve helpers for regular, shadow, and mix
|
|
1886
|
+
* color defs.
|
|
1887
|
+
*
|
|
1888
|
+
* Variants are stored in OKHST: `h` / `s` are OKHSL hue/saturation and
|
|
1889
|
+
* `t` is the canonical contrast-uniform tone (0–1, reference eps). The
|
|
1890
|
+
* resolver works in tone for regular colors and converts to/from OKHSL
|
|
1891
|
+
* lightness only at the mix/shadow and luminance edges.
|
|
1892
|
+
*
|
|
1893
|
+
* Every function receives a single `GlazeConfigResolved` so the full
|
|
1894
|
+
* per-instance config (including overrides) is available without
|
|
1895
|
+
* re-reading the global singleton mid-resolve.
|
|
1008
1896
|
*/
|
|
1009
|
-
function
|
|
1010
|
-
if (
|
|
1011
|
-
|
|
1012
|
-
|
|
1897
|
+
function getSchemeVariant(color, isDark, isHighContrast) {
|
|
1898
|
+
if (isDark && isHighContrast) return color.darkContrast;
|
|
1899
|
+
if (isDark) return color.dark;
|
|
1900
|
+
if (isHighContrast) return color.lightContrast;
|
|
1901
|
+
return color.light;
|
|
1902
|
+
}
|
|
1903
|
+
/** Edge adapter: resolved variant (`t`) → OKHSL-lightness variant. */
|
|
1904
|
+
function toOkhslVariant(v) {
|
|
1905
|
+
const c = variantToOkhsl(v);
|
|
1906
|
+
return {
|
|
1907
|
+
h: c.h,
|
|
1908
|
+
s: c.s,
|
|
1909
|
+
l: c.l,
|
|
1910
|
+
alpha: v.alpha,
|
|
1911
|
+
pastel: v.pastel
|
|
1013
1912
|
};
|
|
1913
|
+
}
|
|
1914
|
+
/** Edge adapter: OKHSL-lightness variant → resolved variant (`t`). */
|
|
1915
|
+
function toToneVariant(v) {
|
|
1916
|
+
const c = okhslToOkhst({
|
|
1917
|
+
h: v.h,
|
|
1918
|
+
s: v.s,
|
|
1919
|
+
l: v.l
|
|
1920
|
+
});
|
|
1014
1921
|
return {
|
|
1015
|
-
|
|
1016
|
-
|
|
1922
|
+
h: c.h,
|
|
1923
|
+
s: c.s,
|
|
1924
|
+
t: c.t,
|
|
1925
|
+
alpha: v.alpha
|
|
1017
1926
|
};
|
|
1018
1927
|
}
|
|
1019
1928
|
/**
|
|
1020
|
-
*
|
|
1021
|
-
*
|
|
1929
|
+
* Resolve the role of a base color referenced by `baseName`, returning the
|
|
1930
|
+
* role the *dependent* color should take (the opposite of the base's role).
|
|
1931
|
+
* A base that lives in `defs` recursively resolves and is inverted via
|
|
1932
|
+
* `oppositeRole`; an external base (no local def, e.g. an injected standalone
|
|
1933
|
+
* token) is treated as a background, so the dependent defaults to foreground
|
|
1934
|
+
* (`'text'`).
|
|
1022
1935
|
*/
|
|
1023
|
-
function
|
|
1024
|
-
if (
|
|
1025
|
-
const
|
|
1026
|
-
if (
|
|
1027
|
-
return (
|
|
1936
|
+
function resolveBaseRoleInMap(baseName, defs, inferRole, roles) {
|
|
1937
|
+
if (!baseName) return void 0;
|
|
1938
|
+
const baseDef = defs[baseName];
|
|
1939
|
+
if (!baseDef) return "text";
|
|
1940
|
+
return oppositeRole(resolveRoleInMap(baseName, baseDef, defs, inferRole, roles));
|
|
1941
|
+
}
|
|
1942
|
+
/**
|
|
1943
|
+
* Role-resolution core that does not need a full `ResolveContext`. Shared by
|
|
1944
|
+
* the resolver (via `resolveRole`) and `verifyContrastDrift`.
|
|
1945
|
+
*/
|
|
1946
|
+
function resolveRoleInMap(name, def, defs, inferRole, roles) {
|
|
1947
|
+
const cached = roles.get(name);
|
|
1948
|
+
if (cached) return cached;
|
|
1949
|
+
let role;
|
|
1950
|
+
if (isShadowDef(def)) role = "surface";
|
|
1951
|
+
else if (isMixDef(def)) role = normalizeRole(def.role) ?? (inferRole ? inferRoleFromName(name) : void 0) ?? resolveBaseRoleInMap(def.base, defs, inferRole, roles) ?? "text";
|
|
1952
|
+
else {
|
|
1953
|
+
const regDef = def;
|
|
1954
|
+
role = normalizeRole(regDef.role) ?? (inferRole ? inferRoleFromName(name) : void 0) ?? resolveBaseRoleInMap(regDef.base, defs, inferRole, roles) ?? "text";
|
|
1955
|
+
}
|
|
1956
|
+
const finalRole = role ?? "text";
|
|
1957
|
+
roles.set(name, finalRole);
|
|
1958
|
+
return finalRole;
|
|
1028
1959
|
}
|
|
1029
1960
|
/**
|
|
1030
|
-
*
|
|
1031
|
-
*
|
|
1961
|
+
* Resolve a color's semantic `role` (text / surface / border) per the chain:
|
|
1962
|
+
* 1. explicit `def.role` (normalized)
|
|
1963
|
+
* 2. inferred from the color name when `config.inferRole` is on
|
|
1964
|
+
* 3. opposite of the base's role
|
|
1965
|
+
* 4. `'text'` (foreground) default
|
|
1966
|
+
*
|
|
1967
|
+
* Memoized on `ctx.roles` so the four scheme passes share one resolution.
|
|
1968
|
+
* Shadows have no contrast participation and default to `'surface'`.
|
|
1032
1969
|
*/
|
|
1033
|
-
function
|
|
1034
|
-
|
|
1035
|
-
|
|
1970
|
+
function resolveRole(name, def, ctx) {
|
|
1971
|
+
return resolveRoleInMap(name, def, ctx.defs, ctx.config.inferRole, ctx.roles);
|
|
1972
|
+
}
|
|
1973
|
+
function resolveContrastSpec(spec, isHighContrast, polarity) {
|
|
1974
|
+
const outerExplicitHC = Array.isArray(spec);
|
|
1975
|
+
return resolveContrastForMode(isHighContrast ? pairHC(spec) : pairNormal(spec), isHighContrast, polarity, outerExplicitHC);
|
|
1036
1976
|
}
|
|
1037
|
-
|
|
1038
|
-
|
|
1977
|
+
/**
|
|
1978
|
+
* Apply the relative-tone delta against a base, honoring `flip`.
|
|
1979
|
+
*
|
|
1980
|
+
* When `flip` is on and `base + delta` falls outside `[0, 100]`, try mirroring
|
|
1981
|
+
* the delta to the other side of the base. If the mirrored target is also out
|
|
1982
|
+
* of range, keep the original delta so the caller clamps on the authored side.
|
|
1983
|
+
* When off, the caller clamps as usual.
|
|
1984
|
+
*/
|
|
1985
|
+
function applyToneFlip(delta, baseTone, flip) {
|
|
1986
|
+
if (!flip) return delta;
|
|
1987
|
+
const target = baseTone + delta;
|
|
1988
|
+
if (target >= 0 && target <= 100) return delta;
|
|
1989
|
+
const mirrored = baseTone - delta;
|
|
1990
|
+
if (mirrored >= 0 && mirrored <= 100) return -delta;
|
|
1991
|
+
return delta;
|
|
1992
|
+
}
|
|
1993
|
+
function resolveRootColor(def, isHighContrast) {
|
|
1994
|
+
const rawT = def.tone;
|
|
1039
1995
|
return {
|
|
1040
|
-
|
|
1996
|
+
authorTone: clamp(parseToneValue(isHighContrast ? pairHC(rawT) : pairNormal(rawT)).value, 0, 100),
|
|
1041
1997
|
satFactor: clamp(def.saturation ?? 1, 0, 1)
|
|
1042
1998
|
};
|
|
1043
1999
|
}
|
|
1044
|
-
function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue) {
|
|
2000
|
+
function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue, polarity, effectivePastel) {
|
|
1045
2001
|
const baseName = def.base;
|
|
1046
2002
|
const baseResolved = ctx.resolved.get(baseName);
|
|
1047
2003
|
if (!baseResolved) throw new Error(`glaze: base "${baseName}" not yet resolved for "${name}".`);
|
|
1048
2004
|
const mode = def.mode ?? "auto";
|
|
1049
2005
|
const satFactor = clamp(def.saturation ?? 1, 0, 1);
|
|
2006
|
+
const flip = def.autoFlip ?? ctx.config.autoFlip;
|
|
2007
|
+
const pastel = effectivePastel;
|
|
1050
2008
|
const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
|
|
1051
|
-
const
|
|
1052
|
-
let
|
|
1053
|
-
const
|
|
1054
|
-
if (
|
|
2009
|
+
const baseTone = baseVariant.t * 100;
|
|
2010
|
+
let preferredTone;
|
|
2011
|
+
const rawTone = def.tone;
|
|
2012
|
+
if (rawTone === void 0) preferredTone = baseTone;
|
|
1055
2013
|
else {
|
|
1056
|
-
const parsed =
|
|
1057
|
-
if (parsed.relative) {
|
|
1058
|
-
const
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
else preferredL = mapLightnessLight(parsed.value, mode, isHighContrast);
|
|
2014
|
+
const parsed = parseToneValue(isHighContrast ? pairHC(rawTone) : pairNormal(rawTone));
|
|
2015
|
+
if (parsed.kind === "relative") if (isDark && mode === "auto") {
|
|
2016
|
+
const baseLightTone = getSchemeVariant(baseResolved, false, isHighContrast).t * 100;
|
|
2017
|
+
preferredTone = mapToneForScheme(clamp(baseLightTone + applyToneFlip(parsed.value, baseLightTone, flip), 0, 100), "auto", true, isHighContrast, ctx.config);
|
|
2018
|
+
} else preferredTone = clamp(baseTone + applyToneFlip(parsed.value, baseTone, flip), 0, 100);
|
|
2019
|
+
else preferredTone = mapToneForScheme(parsed.value, mode, isDark, isHighContrast, ctx.config);
|
|
1063
2020
|
}
|
|
1064
2021
|
const rawContrast = def.contrast;
|
|
1065
2022
|
if (rawContrast !== void 0) {
|
|
1066
|
-
const
|
|
1067
|
-
const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode) : satFactor * ctx.saturation / 100;
|
|
1068
|
-
const
|
|
1069
|
-
const
|
|
2023
|
+
const resolvedContrast = resolveContrastSpec(rawContrast, isHighContrast, polarity);
|
|
2024
|
+
const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode, ctx.config) : satFactor * ctx.saturation / 100;
|
|
2025
|
+
const baseOkhsl = toOkhslVariant(baseVariant);
|
|
2026
|
+
const baseLinearRgb = okhslToLinearSrgb(baseOkhsl.h, baseOkhsl.s, baseOkhsl.l, baseVariant.pastel ?? ctx.config.pastel);
|
|
2027
|
+
const toneRange = schemeToneRange(isDark, mode, isHighContrast, ctx.config);
|
|
2028
|
+
let initialDirection;
|
|
2029
|
+
if (preferredTone < baseTone) initialDirection = "darker";
|
|
2030
|
+
else if (preferredTone > baseTone) initialDirection = "lighter";
|
|
2031
|
+
const result = findToneForContrast({
|
|
2032
|
+
hue: effectiveHue,
|
|
2033
|
+
saturation: effectiveSat,
|
|
2034
|
+
preferredTone: clamp(preferredTone / 100, toneRange[0], toneRange[1]),
|
|
2035
|
+
baseLinearRgb,
|
|
2036
|
+
contrast: resolvedContrast,
|
|
2037
|
+
toneRange: [0, 1],
|
|
2038
|
+
initialDirection,
|
|
2039
|
+
flip,
|
|
2040
|
+
pastel
|
|
2041
|
+
});
|
|
2042
|
+
if (!result.met) warnContrastUnmet(name, isDark, isHighContrast, resolvedContrast, result.contrast);
|
|
1070
2043
|
return {
|
|
1071
|
-
|
|
1072
|
-
hue: effectiveHue,
|
|
1073
|
-
saturation: effectiveSat,
|
|
1074
|
-
preferredLightness: clamp(preferredL / 100, windowRange[0], windowRange[1]),
|
|
1075
|
-
baseLinearRgb,
|
|
1076
|
-
contrast: minCr,
|
|
1077
|
-
lightnessRange: [0, 1]
|
|
1078
|
-
}).lightness * 100,
|
|
2044
|
+
tone: result.tone * 100,
|
|
1079
2045
|
satFactor
|
|
1080
2046
|
};
|
|
1081
2047
|
}
|
|
1082
2048
|
return {
|
|
1083
|
-
|
|
2049
|
+
tone: clamp(preferredTone, 0, 100),
|
|
1084
2050
|
satFactor
|
|
1085
2051
|
};
|
|
1086
2052
|
}
|
|
1087
|
-
function getSchemeVariant(color, isDark, isHighContrast) {
|
|
1088
|
-
if (isDark && isHighContrast) return color.darkContrast;
|
|
1089
|
-
if (isDark) return color.dark;
|
|
1090
|
-
if (isHighContrast) return color.lightContrast;
|
|
1091
|
-
return color.light;
|
|
1092
|
-
}
|
|
1093
2053
|
function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
|
|
1094
2054
|
if (isShadowDef(def)) return resolveShadowForScheme(def, ctx, isDark, isHighContrast);
|
|
1095
|
-
if (isMixDef(def)) return resolveMixForScheme(def, ctx, isDark, isHighContrast);
|
|
2055
|
+
if (isMixDef(def)) return resolveMixForScheme(name, def, ctx, isDark, isHighContrast);
|
|
1096
2056
|
const regDef = def;
|
|
1097
2057
|
const mode = regDef.mode ?? "auto";
|
|
1098
|
-
const isRoot =
|
|
2058
|
+
const isRoot = isAbsoluteTone(regDef.tone) && !regDef.base;
|
|
1099
2059
|
const effectiveHue = resolveEffectiveHue(ctx.hue, regDef.hue);
|
|
1100
|
-
|
|
2060
|
+
const polarity = roleToPolarity(resolveRole(name, def, ctx));
|
|
2061
|
+
const pastel = regDef.pastel ?? ctx.config.pastel;
|
|
2062
|
+
let finalTone;
|
|
1101
2063
|
let satFactor;
|
|
1102
2064
|
if (isRoot) {
|
|
1103
|
-
const root = resolveRootColor(
|
|
1104
|
-
|
|
2065
|
+
const root = resolveRootColor(regDef, isHighContrast);
|
|
2066
|
+
finalTone = mapToneForScheme(root.authorTone, mode, isDark, isHighContrast, ctx.config);
|
|
1105
2067
|
satFactor = root.satFactor;
|
|
1106
2068
|
} else {
|
|
1107
|
-
const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue);
|
|
1108
|
-
|
|
1109
|
-
satFactor = dep.satFactor;
|
|
1110
|
-
}
|
|
1111
|
-
let finalL;
|
|
1112
|
-
let finalSat;
|
|
1113
|
-
if (isDark && isRoot) {
|
|
1114
|
-
finalL = mapLightnessDark(lightL, mode, isHighContrast);
|
|
1115
|
-
finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
|
|
1116
|
-
} else if (isDark && !isRoot) {
|
|
1117
|
-
finalL = lightL;
|
|
1118
|
-
finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
|
|
1119
|
-
} else if (isRoot) {
|
|
1120
|
-
finalL = mapLightnessLight(lightL, mode, isHighContrast);
|
|
1121
|
-
finalSat = satFactor * ctx.saturation / 100;
|
|
1122
|
-
} else {
|
|
1123
|
-
finalL = lightL;
|
|
1124
|
-
finalSat = satFactor * ctx.saturation / 100;
|
|
2069
|
+
const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue, polarity, pastel);
|
|
2070
|
+
finalTone = dep.tone;
|
|
2071
|
+
satFactor = dep.satFactor;
|
|
1125
2072
|
}
|
|
2073
|
+
const baseSat = satFactor * ctx.saturation / 100;
|
|
2074
|
+
const finalSat = isDark ? mapSaturationDark(baseSat, mode, ctx.config) : baseSat;
|
|
2075
|
+
const toneFraction = clamp(finalTone / 100, 0, 1);
|
|
1126
2076
|
return {
|
|
1127
2077
|
h: effectiveHue,
|
|
1128
2078
|
s: clamp(finalSat, 0, 1),
|
|
1129
|
-
|
|
1130
|
-
alpha: regDef.opacity ?? 1
|
|
2079
|
+
t: toneFraction,
|
|
2080
|
+
alpha: regDef.opacity ?? 1,
|
|
2081
|
+
pastel
|
|
1131
2082
|
};
|
|
1132
2083
|
}
|
|
1133
2084
|
function resolveShadowForScheme(def, ctx, isDark, isHighContrast) {
|
|
1134
|
-
const bgVariant = getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast);
|
|
2085
|
+
const bgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast));
|
|
1135
2086
|
let fgVariant;
|
|
1136
|
-
if (def.fg) fgVariant = getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast);
|
|
2087
|
+
if (def.fg) fgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast));
|
|
1137
2088
|
const intensity = isHighContrast ? pairHC(def.intensity) : pairNormal(def.intensity);
|
|
1138
|
-
const tuning = resolveShadowTuning(def.tuning);
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
result.alpha = tuning.alphaMax * Math.pow(normalized, exponent);
|
|
1144
|
-
}
|
|
1145
|
-
return result;
|
|
2089
|
+
const tuning = resolveShadowTuning(def.tuning, ctx.config.shadowTuning);
|
|
2090
|
+
return {
|
|
2091
|
+
...toToneVariant(computeShadow(bgVariant, fgVariant, intensity, tuning)),
|
|
2092
|
+
pastel: def.pastel ?? ctx.config.pastel
|
|
2093
|
+
};
|
|
1146
2094
|
}
|
|
1147
|
-
function
|
|
1148
|
-
return okhslToLinearSrgb(v.h, v.s, v.l);
|
|
2095
|
+
function okhslVariantToLinearRgb(v, pastel) {
|
|
2096
|
+
return okhslToLinearSrgb(v.h, v.s, v.l, pastel);
|
|
1149
2097
|
}
|
|
1150
2098
|
/**
|
|
1151
2099
|
* Resolve hue for OKHSL mixing, handling achromatic colors.
|
|
@@ -1168,77 +2116,92 @@ function linearSrgbLerp(base, target, t) {
|
|
|
1168
2116
|
base[2] + (target[2] - base[2]) * t
|
|
1169
2117
|
];
|
|
1170
2118
|
}
|
|
1171
|
-
function
|
|
2119
|
+
function linearRgbToToneVariant(rgb, pastel) {
|
|
1172
2120
|
const [h, s, l] = srgbToOkhsl([
|
|
1173
2121
|
Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[0]))),
|
|
1174
2122
|
Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[1]))),
|
|
1175
2123
|
Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[2])))
|
|
1176
|
-
]);
|
|
1177
|
-
return {
|
|
2124
|
+
], pastel);
|
|
2125
|
+
return toToneVariant({
|
|
1178
2126
|
h,
|
|
1179
2127
|
s,
|
|
1180
2128
|
l,
|
|
1181
2129
|
alpha: 1
|
|
1182
|
-
};
|
|
2130
|
+
});
|
|
1183
2131
|
}
|
|
1184
|
-
function resolveMixForScheme(def, ctx, isDark, isHighContrast) {
|
|
2132
|
+
function resolveMixForScheme(name, def, ctx, isDark, isHighContrast) {
|
|
1185
2133
|
const baseResolved = ctx.resolved.get(def.base);
|
|
1186
2134
|
const targetResolved = ctx.resolved.get(def.target);
|
|
1187
|
-
const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
|
|
1188
|
-
const targetVariant = getSchemeVariant(targetResolved, isDark, isHighContrast);
|
|
2135
|
+
const baseVariant = toOkhslVariant(getSchemeVariant(baseResolved, isDark, isHighContrast));
|
|
2136
|
+
const targetVariant = toOkhslVariant(getSchemeVariant(targetResolved, isDark, isHighContrast));
|
|
1189
2137
|
let t = clamp(isHighContrast ? pairHC(def.value) : pairNormal(def.value), 0, 100) / 100;
|
|
1190
2138
|
const blend = def.blend ?? "opaque";
|
|
1191
2139
|
const space = def.space ?? "okhsl";
|
|
1192
|
-
const
|
|
1193
|
-
const
|
|
2140
|
+
const polarity = roleToPolarity(resolveRole(name, def, ctx));
|
|
2141
|
+
const pastel = def.pastel ?? ctx.config.pastel;
|
|
2142
|
+
const baseLinear = okhslVariantToLinearRgb(baseVariant, baseVariant.pastel ?? ctx.config.pastel);
|
|
2143
|
+
const targetLinear = okhslVariantToLinearRgb(targetVariant, targetVariant.pastel ?? ctx.config.pastel);
|
|
1194
2144
|
if (def.contrast !== void 0) {
|
|
1195
|
-
const
|
|
2145
|
+
const resolvedContrast = resolveContrastSpec(def.contrast, isHighContrast, polarity);
|
|
2146
|
+
const metric = resolvedContrast.metric;
|
|
1196
2147
|
let luminanceAt;
|
|
1197
|
-
if (blend === "transparent") luminanceAt = (v) =>
|
|
1198
|
-
else if (space === "srgb") luminanceAt = (v) => gamutClampedLuminance(linearSrgbLerp(baseLinear, targetLinear, v));
|
|
2148
|
+
if (blend === "transparent" || space === "srgb") luminanceAt = (v) => metricLuminance(metric, linearSrgbLerp(baseLinear, targetLinear, v));
|
|
1199
2149
|
else luminanceAt = (v) => {
|
|
1200
|
-
return
|
|
2150
|
+
return metricLuminance(metric, okhslToLinearSrgb(mixHue(baseVariant, targetVariant, v), baseVariant.s + (targetVariant.s - baseVariant.s) * v, baseVariant.l + (targetVariant.l - baseVariant.l) * v, pastel));
|
|
1201
2151
|
};
|
|
1202
2152
|
t = findValueForMixContrast({
|
|
1203
2153
|
preferredValue: t,
|
|
1204
2154
|
baseLinearRgb: baseLinear,
|
|
1205
2155
|
targetLinearRgb: targetLinear,
|
|
1206
|
-
contrast:
|
|
1207
|
-
luminanceAtValue: luminanceAt
|
|
2156
|
+
contrast: resolvedContrast,
|
|
2157
|
+
luminanceAtValue: luminanceAt,
|
|
2158
|
+
flip: ctx.config.autoFlip
|
|
1208
2159
|
}).value;
|
|
1209
2160
|
}
|
|
1210
2161
|
if (blend === "transparent") return {
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
2162
|
+
...toToneVariant({
|
|
2163
|
+
h: targetVariant.h,
|
|
2164
|
+
s: targetVariant.s,
|
|
2165
|
+
l: targetVariant.l,
|
|
2166
|
+
alpha: clamp(t, 0, 1)
|
|
2167
|
+
}),
|
|
2168
|
+
pastel
|
|
2169
|
+
};
|
|
2170
|
+
if (space === "srgb") return {
|
|
2171
|
+
...linearRgbToToneVariant(linearSrgbLerp(baseLinear, targetLinear, t), pastel),
|
|
2172
|
+
pastel
|
|
1215
2173
|
};
|
|
1216
|
-
if (space === "srgb") return linearRgbToVariant(linearSrgbLerp(baseLinear, targetLinear, t));
|
|
1217
2174
|
return {
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
2175
|
+
...toToneVariant({
|
|
2176
|
+
h: mixHue(baseVariant, targetVariant, t),
|
|
2177
|
+
s: clamp(baseVariant.s + (targetVariant.s - baseVariant.s) * t, 0, 1),
|
|
2178
|
+
l: clamp(baseVariant.l + (targetVariant.l - baseVariant.l) * t, 0, 1),
|
|
2179
|
+
alpha: 1
|
|
2180
|
+
}),
|
|
2181
|
+
pastel
|
|
1222
2182
|
};
|
|
1223
2183
|
}
|
|
1224
|
-
function
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
}
|
|
1237
|
-
const lightMap = /* @__PURE__ */ new Map();
|
|
2184
|
+
function defMode(def) {
|
|
2185
|
+
if (isShadowDef(def) || isMixDef(def)) return void 0;
|
|
2186
|
+
return def.mode ?? "auto";
|
|
2187
|
+
}
|
|
2188
|
+
/**
|
|
2189
|
+
* Run a single resolve pass over all local names. Pass 1 lazily creates
|
|
2190
|
+
* each `ResolvedColor` (all four slots seeded with the just-resolved
|
|
2191
|
+
* variant) the first time it sees a name; later passes update the
|
|
2192
|
+
* `target` slot on the existing record.
|
|
2193
|
+
*/
|
|
2194
|
+
function runPass(order, defs, ctx, isDark, isHighContrast, target) {
|
|
2195
|
+
const out = /* @__PURE__ */ new Map();
|
|
1238
2196
|
for (const name of order) {
|
|
1239
|
-
const variant = resolveColorForScheme(name, defs[name], ctx,
|
|
1240
|
-
|
|
1241
|
-
ctx.resolved.
|
|
2197
|
+
const variant = resolveColorForScheme(name, defs[name], ctx, isDark, isHighContrast);
|
|
2198
|
+
out.set(name, variant);
|
|
2199
|
+
const existing = ctx.resolved.get(name);
|
|
2200
|
+
if (existing) ctx.resolved.set(name, {
|
|
2201
|
+
...existing,
|
|
2202
|
+
[target]: variant
|
|
2203
|
+
});
|
|
2204
|
+
else ctx.resolved.set(name, {
|
|
1242
2205
|
name,
|
|
1243
2206
|
light: variant,
|
|
1244
2207
|
dark: variant,
|
|
@@ -1247,49 +2210,92 @@ function resolveAllColors(hue, saturation, defs) {
|
|
|
1247
2210
|
mode: defMode(defs[name])
|
|
1248
2211
|
});
|
|
1249
2212
|
}
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
lightHCMap.set(name, variant);
|
|
1258
|
-
ctx.resolved.set(name, {
|
|
1259
|
-
...ctx.resolved.get(name),
|
|
1260
|
-
lightContrast: variant
|
|
1261
|
-
});
|
|
1262
|
-
}
|
|
1263
|
-
const darkMap = /* @__PURE__ */ new Map();
|
|
1264
|
-
for (const name of order) ctx.resolved.set(name, {
|
|
1265
|
-
name,
|
|
1266
|
-
light: lightMap.get(name),
|
|
1267
|
-
dark: lightMap.get(name),
|
|
1268
|
-
lightContrast: lightHCMap.get(name),
|
|
1269
|
-
darkContrast: lightHCMap.get(name),
|
|
1270
|
-
mode: defMode(defs[name])
|
|
1271
|
-
});
|
|
2213
|
+
return out;
|
|
2214
|
+
}
|
|
2215
|
+
/**
|
|
2216
|
+
* Re-seed a single variant slot with a previously-resolved map so the
|
|
2217
|
+
* upcoming pass reads sensible fallbacks via `getSchemeVariant`.
|
|
2218
|
+
*/
|
|
2219
|
+
function seedField(order, ctx, field, source) {
|
|
1272
2220
|
for (const name of order) {
|
|
1273
|
-
const
|
|
1274
|
-
darkMap.set(name, variant);
|
|
2221
|
+
const existing = ctx.resolved.get(name);
|
|
1275
2222
|
ctx.resolved.set(name, {
|
|
1276
|
-
...
|
|
1277
|
-
|
|
2223
|
+
...existing,
|
|
2224
|
+
[field]: source.get(name)
|
|
1278
2225
|
});
|
|
1279
2226
|
}
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* After the four passes, surface chromatic contrast drift (§10): a color
|
|
2230
|
+
* resolved with a `base` + `contrast` may land slightly under the contrast
|
|
2231
|
+
* its tone implies because chromatic luminance drifts from the gray tone.
|
|
2232
|
+
*/
|
|
2233
|
+
function verifyContrastDrift(order, defs, result, config) {
|
|
2234
|
+
const roles = /* @__PURE__ */ new Map();
|
|
1285
2235
|
for (const name of order) {
|
|
1286
|
-
const
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
2236
|
+
const def = defs[name];
|
|
2237
|
+
if (isShadowDef(def) || isMixDef(def)) continue;
|
|
2238
|
+
const regDef = def;
|
|
2239
|
+
if (regDef.contrast === void 0 || !regDef.base) continue;
|
|
2240
|
+
const color = result.get(name);
|
|
2241
|
+
const base = result.get(regDef.base);
|
|
2242
|
+
if (!color || !base) continue;
|
|
2243
|
+
const polarity = roleToPolarity(resolveRoleInMap(name, def, defs, config.inferRole, roles));
|
|
2244
|
+
for (const s of [
|
|
2245
|
+
{
|
|
2246
|
+
isDark: false,
|
|
2247
|
+
isHighContrast: false,
|
|
2248
|
+
field: "light"
|
|
2249
|
+
},
|
|
2250
|
+
{
|
|
2251
|
+
isDark: false,
|
|
2252
|
+
isHighContrast: true,
|
|
2253
|
+
field: "lightContrast"
|
|
2254
|
+
},
|
|
2255
|
+
{
|
|
2256
|
+
isDark: true,
|
|
2257
|
+
isHighContrast: false,
|
|
2258
|
+
field: "dark"
|
|
2259
|
+
},
|
|
2260
|
+
{
|
|
2261
|
+
isDark: true,
|
|
2262
|
+
isHighContrast: true,
|
|
2263
|
+
field: "darkContrast"
|
|
2264
|
+
}
|
|
2265
|
+
]) {
|
|
2266
|
+
const spec = resolveContrastSpec(regDef.contrast, s.isHighContrast, polarity);
|
|
2267
|
+
const cVariant = color[s.field];
|
|
2268
|
+
const bVariant = base[s.field];
|
|
2269
|
+
const cOkhsl = toOkhslVariant(cVariant);
|
|
2270
|
+
const bOkhsl = toOkhslVariant(bVariant);
|
|
2271
|
+
const cPastel = cVariant.pastel ?? config.pastel;
|
|
2272
|
+
const bPastel = bVariant.pastel ?? config.pastel;
|
|
2273
|
+
const yC = metricLuminance(spec.metric, okhslToLinearSrgb(cOkhsl.h, cOkhsl.s, cOkhsl.l, cPastel));
|
|
2274
|
+
const yB = metricLuminance(spec.metric, okhslToLinearSrgb(bOkhsl.h, bOkhsl.s, bOkhsl.l, bPastel));
|
|
2275
|
+
warnContrastDrift(name, s.isDark, s.isHighContrast, spec, yC, yB);
|
|
2276
|
+
}
|
|
1292
2277
|
}
|
|
2278
|
+
}
|
|
2279
|
+
function resolveAllColors(hue, saturation, defs, config, externalBases) {
|
|
2280
|
+
validateColorDefs(defs, externalBases);
|
|
2281
|
+
const order = topoSort(defs);
|
|
2282
|
+
const ctx = {
|
|
2283
|
+
hue,
|
|
2284
|
+
saturation,
|
|
2285
|
+
defs,
|
|
2286
|
+
resolved: /* @__PURE__ */ new Map(),
|
|
2287
|
+
config,
|
|
2288
|
+
roles: /* @__PURE__ */ new Map()
|
|
2289
|
+
};
|
|
2290
|
+
if (externalBases) for (const [name, color] of externalBases) ctx.resolved.set(name, color);
|
|
2291
|
+
const lightMap = runPass(order, defs, ctx, false, false, "light");
|
|
2292
|
+
seedField(order, ctx, "lightContrast", lightMap);
|
|
2293
|
+
const lightHCMap = runPass(order, defs, ctx, false, true, "lightContrast");
|
|
2294
|
+
seedField(order, ctx, "dark", lightMap);
|
|
2295
|
+
seedField(order, ctx, "darkContrast", lightHCMap);
|
|
2296
|
+
const darkMap = runPass(order, defs, ctx, true, false, "dark");
|
|
2297
|
+
seedField(order, ctx, "darkContrast", darkMap);
|
|
2298
|
+
const darkHCMap = runPass(order, defs, ctx, true, true, "darkContrast");
|
|
1293
2299
|
const result = /* @__PURE__ */ new Map();
|
|
1294
2300
|
for (const name of order) result.set(name, {
|
|
1295
2301
|
name,
|
|
@@ -1299,8 +2305,126 @@ function resolveAllColors(hue, saturation, defs) {
|
|
|
1299
2305
|
darkContrast: darkHCMap.get(name),
|
|
1300
2306
|
mode: defMode(defs[name])
|
|
1301
2307
|
});
|
|
2308
|
+
verifyContrastDrift(order, defs, result, config);
|
|
1302
2309
|
return result;
|
|
1303
2310
|
}
|
|
2311
|
+
|
|
2312
|
+
//#endregion
|
|
2313
|
+
//#region src/channels.ts
|
|
2314
|
+
/**
|
|
2315
|
+
* Hue channel planning for `splitHue` exports.
|
|
2316
|
+
*
|
|
2317
|
+
* Builds per-color hue var references and scheme-independent `--*-hue`
|
|
2318
|
+
* declarations for oklch CSS / Tasty output when every color is pastel.
|
|
2319
|
+
*/
|
|
2320
|
+
const ACHROMATIC_EPSILON = 1e-6;
|
|
2321
|
+
function cssProp(prefix, name, suffix) {
|
|
2322
|
+
return `--${prefix}${name}${suffix}`;
|
|
2323
|
+
}
|
|
2324
|
+
function isAchromatic(v) {
|
|
2325
|
+
return v.s <= ACHROMATIC_EPSILON;
|
|
2326
|
+
}
|
|
2327
|
+
function themeHuePlan(name, def, variant, ctx) {
|
|
2328
|
+
if (def === void 0 || isShadowDef(def) || isMixDef(def) || isAchromatic(variant)) return {
|
|
2329
|
+
hueVar: "",
|
|
2330
|
+
inline: true,
|
|
2331
|
+
declarations: []
|
|
2332
|
+
};
|
|
2333
|
+
const regDef = def;
|
|
2334
|
+
const baseHueVar = `var(--${ctx.baseName}-hue)`;
|
|
2335
|
+
if (regDef.hue === void 0) return {
|
|
2336
|
+
hueVar: baseHueVar,
|
|
2337
|
+
inline: false,
|
|
2338
|
+
declarations: []
|
|
2339
|
+
};
|
|
2340
|
+
const parsed = parseRelativeOrAbsolute(regDef.hue);
|
|
2341
|
+
const prop = cssProp(ctx.prefix, name, "-hue");
|
|
2342
|
+
if (parsed.relative) {
|
|
2343
|
+
const sign = parsed.value >= 0 ? "+" : "-";
|
|
2344
|
+
const magnitude = Math.abs(parsed.value);
|
|
2345
|
+
const value = `calc(var(--${ctx.baseName}-hue) ${sign} ${magnitude})`;
|
|
2346
|
+
return {
|
|
2347
|
+
hueVar: `var(${prop})`,
|
|
2348
|
+
inline: false,
|
|
2349
|
+
declarations: [{
|
|
2350
|
+
prop,
|
|
2351
|
+
value
|
|
2352
|
+
}]
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
const absHue = (parsed.value % 360 + 360) % 360;
|
|
2356
|
+
return {
|
|
2357
|
+
hueVar: `var(${prop})`,
|
|
2358
|
+
inline: false,
|
|
2359
|
+
declarations: [{
|
|
2360
|
+
prop,
|
|
2361
|
+
value: String(absHue)
|
|
2362
|
+
}]
|
|
2363
|
+
};
|
|
2364
|
+
}
|
|
2365
|
+
function standaloneHuePlan(name, variant, ctx) {
|
|
2366
|
+
if (isAchromatic(variant)) return {
|
|
2367
|
+
hueVar: "",
|
|
2368
|
+
inline: true,
|
|
2369
|
+
declarations: []
|
|
2370
|
+
};
|
|
2371
|
+
const hue = ctx.resolvedHue ?? variant.h;
|
|
2372
|
+
const prop = cssProp(ctx.prefix, name, "-hue");
|
|
2373
|
+
return {
|
|
2374
|
+
hueVar: `var(${prop})`,
|
|
2375
|
+
inline: false,
|
|
2376
|
+
declarations: [{
|
|
2377
|
+
prop,
|
|
2378
|
+
value: String(hue)
|
|
2379
|
+
}]
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
function buildHuePlan(name, def, variant, ctx) {
|
|
2383
|
+
if (ctx.mode === "standalone") return standaloneHuePlan(name, variant, ctx);
|
|
2384
|
+
return themeHuePlan(name, def, variant, ctx);
|
|
2385
|
+
}
|
|
2386
|
+
/** Collect unique hue declarations across all colors (theme + per-color). */
|
|
2387
|
+
function collectHueDeclarations(resolved, ctx) {
|
|
2388
|
+
if (ctx.emitDeclarations === false) return [];
|
|
2389
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2390
|
+
const out = [];
|
|
2391
|
+
const push = (decl) => {
|
|
2392
|
+
if (seen.has(decl.prop)) return;
|
|
2393
|
+
seen.add(decl.prop);
|
|
2394
|
+
out.push(decl);
|
|
2395
|
+
};
|
|
2396
|
+
if (ctx.mode === "theme") push({
|
|
2397
|
+
prop: `--${ctx.baseName}-hue`,
|
|
2398
|
+
value: String(ctx.seedHue)
|
|
2399
|
+
});
|
|
2400
|
+
for (const [name, color] of resolved) {
|
|
2401
|
+
const def = ctx.defs[name];
|
|
2402
|
+
const plan = buildHuePlan(name, def, color.light, ctx);
|
|
2403
|
+
for (const decl of plan.declarations) push(decl);
|
|
2404
|
+
}
|
|
2405
|
+
return out;
|
|
2406
|
+
}
|
|
2407
|
+
function buildHuePlans(resolved, ctx) {
|
|
2408
|
+
const plans = /* @__PURE__ */ new Map();
|
|
2409
|
+
for (const [name, color] of resolved) plans.set(name, buildHuePlan(name, ctx.defs[name], color.light, ctx));
|
|
2410
|
+
return plans;
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
//#endregion
|
|
2414
|
+
//#region src/formatters.ts
|
|
2415
|
+
/**
|
|
2416
|
+
* Output formatting for resolved color maps.
|
|
2417
|
+
*
|
|
2418
|
+
* Owns the CSS-string formatter dispatch table (`okhsl` / `rgb` / `hsl` /
|
|
2419
|
+
* `oklch`) and the token-map shapes Glaze emits:
|
|
2420
|
+
* - `buildTokenMap` — Tasty style-to-state bindings (`#name` keys, state aliases).
|
|
2421
|
+
* - `buildFlatTokenMap` — `{ light, dark, ... }` per-variant maps.
|
|
2422
|
+
* - `buildJsonMap` — `{ name: { light, dark, ... } }` per-color JSON.
|
|
2423
|
+
* - `buildCssMap` — CSS custom property declaration strings per variant.
|
|
2424
|
+
* - `buildDtcgMap` — W3C DTCG (2025.10) token documents, one per scheme.
|
|
2425
|
+
* - `buildDtcgResolver` — W3C DTCG Resolver-Module document (one modifier, a context per scheme).
|
|
2426
|
+
* - `buildTailwindMap` — Tailwind v4 `@theme` block + dark/HC overrides.
|
|
2427
|
+
*/
|
|
1304
2428
|
const formatters = {
|
|
1305
2429
|
okhsl: formatOkhsl,
|
|
1306
2430
|
rgb: formatRgb,
|
|
@@ -1310,78 +2434,960 @@ const formatters = {
|
|
|
1310
2434
|
function fmt(value, decimals) {
|
|
1311
2435
|
return parseFloat(value.toFixed(decimals)).toString();
|
|
1312
2436
|
}
|
|
1313
|
-
function formatVariant(v, format = "
|
|
1314
|
-
const
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
2437
|
+
function formatVariant(v, format = "oklch", pastel = false) {
|
|
2438
|
+
const effectivePastel = v.pastel ?? pastel;
|
|
2439
|
+
let base;
|
|
2440
|
+
if (format === "okhst") base = formatOkhst(v.h, v.s * 100, v.t * 100, effectivePastel);
|
|
2441
|
+
else {
|
|
2442
|
+
const { l } = variantToOkhsl(v);
|
|
2443
|
+
base = formatters[format](v.h, v.s * 100, l * 100, effectivePastel);
|
|
2444
|
+
}
|
|
2445
|
+
if (v.alpha >= 1) return base;
|
|
2446
|
+
const closing = base.lastIndexOf(")");
|
|
2447
|
+
return `${base.slice(0, closing)} / ${fmt(v.alpha, 4)})`;
|
|
2448
|
+
}
|
|
2449
|
+
/**
|
|
2450
|
+
* Format a resolved variant as `oklch(L C <hueVar>)`, splicing a CSS hue var
|
|
2451
|
+
* for `splitHue` exports. Falls back to inline when the plan is inline.
|
|
2452
|
+
*/
|
|
2453
|
+
function formatVariantHue(v, plan, pastel = false) {
|
|
2454
|
+
const effectivePastel = v.pastel ?? pastel;
|
|
2455
|
+
const { l } = variantToOkhsl(v);
|
|
2456
|
+
const [L, C] = okhslToOklch(v.h, v.s, l, effectivePastel);
|
|
2457
|
+
let base;
|
|
2458
|
+
if (plan.inline) if (v.s <= 1e-6) base = `oklch(${fmt(L, 4)} 0 0)`;
|
|
2459
|
+
else base = formatOklch(v.h, v.s * 100, l * 100, effectivePastel);
|
|
2460
|
+
else base = `oklch(${fmt(L, 4)} ${fmt(C, 4)} ${plan.hueVar})`;
|
|
2461
|
+
if (v.alpha >= 1) return base;
|
|
2462
|
+
const closing = base.lastIndexOf(")");
|
|
2463
|
+
return `${base.slice(0, closing)} / ${fmt(v.alpha, 4)})`;
|
|
2464
|
+
}
|
|
2465
|
+
function formatColorValue(v, format, pastel, huePlan) {
|
|
2466
|
+
if (format === "oklch" && huePlan !== void 0) return formatVariantHue(v, huePlan, pastel);
|
|
2467
|
+
return formatVariant(v, format, pastel);
|
|
2468
|
+
}
|
|
2469
|
+
function resolveModes(override) {
|
|
2470
|
+
const cfg = getConfig();
|
|
2471
|
+
return {
|
|
2472
|
+
dark: override?.dark ?? cfg.modes.dark,
|
|
2473
|
+
highContrast: override?.highContrast ?? cfg.modes.highContrast
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
function buildTokenMap(resolved, prefix, states, modes, format = "oklch", pastel = false, channelCtx) {
|
|
2477
|
+
const tokens = {};
|
|
2478
|
+
const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
|
|
2479
|
+
if (huePlans !== void 0 && channelCtx !== void 0) {
|
|
2480
|
+
const emitDecls = channelCtx.emitDeclarations !== false;
|
|
2481
|
+
if (emitDecls && channelCtx.mode === "theme") tokens[`$${channelCtx.baseName}-hue`] = { "": String(channelCtx.seedHue) };
|
|
2482
|
+
for (const [name, color] of resolved) {
|
|
2483
|
+
const plan = huePlans.get(name);
|
|
2484
|
+
if (emitDecls) for (const decl of plan.declarations) {
|
|
2485
|
+
const key = `$${decl.prop.slice(2)}`;
|
|
2486
|
+
if (!(key in tokens)) tokens[key] = { "": decl.value };
|
|
2487
|
+
}
|
|
2488
|
+
const colorKey = `#${prefix}${name}`;
|
|
2489
|
+
tokens[colorKey] = buildTokenEntry(color, states, modes, format, pastel, huePlans.get(name));
|
|
2490
|
+
}
|
|
2491
|
+
return tokens;
|
|
2492
|
+
}
|
|
2493
|
+
for (const [name, color] of resolved) {
|
|
2494
|
+
const key = `#${prefix}${name}`;
|
|
2495
|
+
tokens[key] = buildTokenEntry(color, states, modes, format, pastel);
|
|
2496
|
+
}
|
|
2497
|
+
return tokens;
|
|
2498
|
+
}
|
|
2499
|
+
function buildTokenEntry(color, states, modes, format, pastel, huePlan) {
|
|
2500
|
+
const entry = { "": formatColorValue(color.light, format, pastel, huePlan) };
|
|
2501
|
+
if (modes.dark) entry[states.dark] = formatColorValue(color.dark, format, pastel, huePlan);
|
|
2502
|
+
if (modes.highContrast) entry[states.highContrast] = formatColorValue(color.lightContrast, format, pastel, huePlan);
|
|
2503
|
+
if (modes.dark && modes.highContrast) entry[`${states.dark} & ${states.highContrast}`] = formatColorValue(color.darkContrast, format, pastel, huePlan);
|
|
2504
|
+
return entry;
|
|
2505
|
+
}
|
|
2506
|
+
function buildFlatTokenMap(resolved, prefix, modes, format = "oklch", pastel = false) {
|
|
2507
|
+
const result = { light: {} };
|
|
2508
|
+
if (modes.dark) result.dark = {};
|
|
2509
|
+
if (modes.highContrast) result.lightContrast = {};
|
|
2510
|
+
if (modes.dark && modes.highContrast) result.darkContrast = {};
|
|
2511
|
+
for (const [name, color] of resolved) {
|
|
2512
|
+
const key = `${prefix}${name}`;
|
|
2513
|
+
result.light[key] = formatVariant(color.light, format, pastel);
|
|
2514
|
+
if (modes.dark) result.dark[key] = formatVariant(color.dark, format, pastel);
|
|
2515
|
+
if (modes.highContrast) result.lightContrast[key] = formatVariant(color.lightContrast, format, pastel);
|
|
2516
|
+
if (modes.dark && modes.highContrast) result.darkContrast[key] = formatVariant(color.darkContrast, format, pastel);
|
|
2517
|
+
}
|
|
2518
|
+
return result;
|
|
2519
|
+
}
|
|
2520
|
+
function buildJsonMap(resolved, modes, format = "oklch", pastel = false) {
|
|
2521
|
+
const result = {};
|
|
2522
|
+
for (const [name, color] of resolved) {
|
|
2523
|
+
const entry = { light: formatVariant(color.light, format, pastel) };
|
|
2524
|
+
if (modes.dark) entry.dark = formatVariant(color.dark, format, pastel);
|
|
2525
|
+
if (modes.highContrast) entry.lightContrast = formatVariant(color.lightContrast, format, pastel);
|
|
2526
|
+
if (modes.dark && modes.highContrast) entry.darkContrast = formatVariant(color.darkContrast, format, pastel);
|
|
2527
|
+
result[name] = entry;
|
|
2528
|
+
}
|
|
2529
|
+
return result;
|
|
2530
|
+
}
|
|
2531
|
+
function buildCssMap(resolved, prefix, suffix, format, pastel = false, channelCtx) {
|
|
2532
|
+
const lines = {
|
|
2533
|
+
light: [],
|
|
2534
|
+
dark: [],
|
|
2535
|
+
lightContrast: [],
|
|
2536
|
+
darkContrast: []
|
|
2537
|
+
};
|
|
2538
|
+
const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
|
|
2539
|
+
if (huePlans !== void 0 && channelCtx !== void 0) for (const decl of collectHueDeclarations(resolved, channelCtx)) lines.light.push(`${decl.prop}: ${decl.value};`);
|
|
2540
|
+
for (const [name, color] of resolved) {
|
|
2541
|
+
const prop = `--${prefix}${name}${suffix}`;
|
|
2542
|
+
const plan = huePlans?.get(name);
|
|
2543
|
+
lines.light.push(`${prop}: ${formatColorValue(color.light, format, pastel, plan)};`);
|
|
2544
|
+
lines.dark.push(`${prop}: ${formatColorValue(color.dark, format, pastel, plan)};`);
|
|
2545
|
+
lines.lightContrast.push(`${prop}: ${formatColorValue(color.lightContrast, format, pastel, plan)};`);
|
|
2546
|
+
lines.darkContrast.push(`${prop}: ${formatColorValue(color.darkContrast, format, pastel, plan)};`);
|
|
2547
|
+
}
|
|
2548
|
+
return {
|
|
2549
|
+
light: lines.light.join("\n"),
|
|
2550
|
+
dark: lines.dark.join("\n"),
|
|
2551
|
+
lightContrast: lines.lightContrast.join("\n"),
|
|
2552
|
+
darkContrast: lines.darkContrast.join("\n")
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
function roundTo(value, decimals) {
|
|
2556
|
+
return parseFloat(value.toFixed(decimals));
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Build a DTCG `$value` color object for a resolved variant.
|
|
2560
|
+
*
|
|
2561
|
+
* `srgb` (default) emits gamma sRGB components in 0–1 plus a 6-digit `hex`
|
|
2562
|
+
* hint — the most universally understood form (Figma, Tokens Studio, Style
|
|
2563
|
+
* Dictionary). `oklch` emits `[L, C, H]` components with no hex — Glaze-native
|
|
2564
|
+
* and wide-gamut. `alpha` is included only when below 1.
|
|
2565
|
+
*/
|
|
2566
|
+
function dtcgColorValue(v, colorSpace = "srgb", pastel = false) {
|
|
2567
|
+
const effectivePastel = v.pastel ?? pastel;
|
|
2568
|
+
const { l } = variantToOkhsl(v);
|
|
2569
|
+
const alpha = v.alpha < 1 ? roundTo(v.alpha, 6) : void 0;
|
|
2570
|
+
if (colorSpace === "oklch") {
|
|
2571
|
+
const [L, C, H] = okhslToOklch(v.h, v.s, l, effectivePastel);
|
|
2572
|
+
const value = {
|
|
2573
|
+
colorSpace: "oklch",
|
|
2574
|
+
components: [
|
|
2575
|
+
roundTo(L, 6),
|
|
2576
|
+
roundTo(C, 6),
|
|
2577
|
+
roundTo(H, 4)
|
|
2578
|
+
]
|
|
2579
|
+
};
|
|
2580
|
+
if (alpha !== void 0) value.alpha = alpha;
|
|
2581
|
+
return value;
|
|
2582
|
+
}
|
|
2583
|
+
const [r, g, b] = okhslToSrgb(v.h, v.s, l, effectivePastel);
|
|
2584
|
+
const value = {
|
|
2585
|
+
colorSpace: "srgb",
|
|
2586
|
+
components: [
|
|
2587
|
+
roundTo(r, 6),
|
|
2588
|
+
roundTo(g, 6),
|
|
2589
|
+
roundTo(b, 6)
|
|
2590
|
+
],
|
|
2591
|
+
hex: srgbToHex([
|
|
2592
|
+
r,
|
|
2593
|
+
g,
|
|
2594
|
+
b
|
|
2595
|
+
])
|
|
2596
|
+
};
|
|
2597
|
+
if (alpha !== void 0) value.alpha = alpha;
|
|
2598
|
+
return value;
|
|
2599
|
+
}
|
|
2600
|
+
function dtcgToken(v, colorSpace, pastel) {
|
|
2601
|
+
return {
|
|
2602
|
+
$type: "color",
|
|
2603
|
+
$value: dtcgColorValue(v, colorSpace, pastel)
|
|
2604
|
+
};
|
|
2605
|
+
}
|
|
2606
|
+
/**
|
|
2607
|
+
* Build a `GlazeDtcgResult`: one spec-conformant DTCG token document per
|
|
2608
|
+
* scheme variant, gated by `modes`. Light is always present.
|
|
2609
|
+
*/
|
|
2610
|
+
function buildDtcgMap(resolved, prefix, modes, colorSpace = "srgb", pastel = false) {
|
|
2611
|
+
const light = {};
|
|
2612
|
+
const dark = modes.dark ? {} : void 0;
|
|
2613
|
+
const lightContrast = modes.highContrast ? {} : void 0;
|
|
2614
|
+
const darkContrast = modes.dark && modes.highContrast ? {} : void 0;
|
|
2615
|
+
for (const [name, color] of resolved) {
|
|
2616
|
+
const key = `${prefix}${name}`;
|
|
2617
|
+
light[key] = dtcgToken(color.light, colorSpace, pastel);
|
|
2618
|
+
if (dark) dark[key] = dtcgToken(color.dark, colorSpace, pastel);
|
|
2619
|
+
if (lightContrast) lightContrast[key] = dtcgToken(color.lightContrast, colorSpace, pastel);
|
|
2620
|
+
if (darkContrast) darkContrast[key] = dtcgToken(color.darkContrast, colorSpace, pastel);
|
|
2621
|
+
}
|
|
2622
|
+
return {
|
|
2623
|
+
light,
|
|
2624
|
+
dark,
|
|
2625
|
+
lightContrast,
|
|
2626
|
+
darkContrast
|
|
2627
|
+
};
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* Default context names emitted on the `scheme` modifier — the Glaze variant
|
|
2631
|
+
* keys, so the resolver document mirrors `GlazeDtcgResult` exactly.
|
|
2632
|
+
*/
|
|
2633
|
+
const DEFAULT_DTCG_CONTEXT_NAMES = {
|
|
2634
|
+
light: "light",
|
|
2635
|
+
dark: "dark",
|
|
2636
|
+
lightContrast: "lightContrast",
|
|
2637
|
+
darkContrast: "darkContrast"
|
|
2638
|
+
};
|
|
2639
|
+
/**
|
|
2640
|
+
* Wrap a per-scheme `GlazeDtcgResult` into a single W3C DTCG Resolver-Module
|
|
2641
|
+
* document. The light document becomes `sets[setName].sources[0]` (the default
|
|
2642
|
+
* context); each other present variant becomes a `contexts[ctx]` override
|
|
2643
|
+
* array on a single `modifiers[modifierName]`. Absent variants (per the
|
|
2644
|
+
* `modes` already applied to `result`) are omitted — light is always present
|
|
2645
|
+
* and is the modifier `default`. Only the resolver-specific options are read;
|
|
2646
|
+
* `modes` / `colorSpace` were already consumed by the `buildDtcgMap` call that
|
|
2647
|
+
* produced `result`.
|
|
2648
|
+
*/
|
|
2649
|
+
function buildDtcgResolver(result, options) {
|
|
2650
|
+
const setName = options?.setName ?? "base";
|
|
2651
|
+
const modifierName = options?.modifierName ?? "scheme";
|
|
2652
|
+
const ctx = {
|
|
2653
|
+
...DEFAULT_DTCG_CONTEXT_NAMES,
|
|
2654
|
+
...options?.contextNames
|
|
2655
|
+
};
|
|
2656
|
+
const contexts = { [ctx.light]: [] };
|
|
2657
|
+
if (result.dark) contexts[ctx.dark] = [result.dark];
|
|
2658
|
+
if (result.lightContrast) contexts[ctx.lightContrast] = [result.lightContrast];
|
|
2659
|
+
if (result.darkContrast) contexts[ctx.darkContrast] = [result.darkContrast];
|
|
2660
|
+
return {
|
|
2661
|
+
version: options?.version ?? "2025.10",
|
|
2662
|
+
sets: { [setName]: { sources: [result.light] } },
|
|
2663
|
+
modifiers: { [modifierName]: {
|
|
2664
|
+
default: ctx.light,
|
|
2665
|
+
contexts
|
|
2666
|
+
} },
|
|
2667
|
+
resolutionOrder: [{ $ref: `#/sets/${setName}` }, { $ref: `#/modifiers/${modifierName}` }]
|
|
2668
|
+
};
|
|
2669
|
+
}
|
|
2670
|
+
function tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel) {
|
|
2671
|
+
const lines = {
|
|
2672
|
+
light: [],
|
|
2673
|
+
dark: [],
|
|
2674
|
+
lightContrast: [],
|
|
2675
|
+
darkContrast: []
|
|
2676
|
+
};
|
|
2677
|
+
for (const [name, color] of resolved) {
|
|
2678
|
+
const prop = `--${cssPrefix}${themePrefix}${name}`;
|
|
2679
|
+
lines.light.push(`${prop}: ${formatVariant(color.light, format, pastel)};`);
|
|
2680
|
+
lines.dark.push(`${prop}: ${formatVariant(color.dark, format, pastel)};`);
|
|
2681
|
+
lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format, pastel)};`);
|
|
2682
|
+
lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format, pastel)};`);
|
|
2683
|
+
}
|
|
2684
|
+
return lines;
|
|
2685
|
+
}
|
|
2686
|
+
function indentBlock(text, pad) {
|
|
2687
|
+
return text.split("\n").map((line) => line.length === 0 ? line : pad + line).join("\n");
|
|
2688
|
+
}
|
|
2689
|
+
function emitRule(selector, body) {
|
|
2690
|
+
return `${selector} {\n${indentBlock(body, " ")}\n}`;
|
|
2691
|
+
}
|
|
2692
|
+
/**
|
|
2693
|
+
* Emit a CSS block for a set of declarations scoped by one or more selectors
|
|
2694
|
+
* / at-rules. Class-like selectors concatenate (`.dark.high-contrast`);
|
|
2695
|
+
* at-rules (`@media …`) nest `:root` (or the chained selector) inside.
|
|
2696
|
+
*/
|
|
2697
|
+
function emitScoped(scopes, declarations) {
|
|
2698
|
+
if (declarations.length === 0) return void 0;
|
|
2699
|
+
const atRules = [];
|
|
2700
|
+
let selectorChain = "";
|
|
2701
|
+
for (const scope of scopes) if (scope.startsWith("@")) atRules.push(scope);
|
|
2702
|
+
else selectorChain += scope;
|
|
2703
|
+
let css = emitRule(selectorChain || ":root", declarations.join("\n"));
|
|
2704
|
+
for (const rule of atRules) css = emitRule(rule, css);
|
|
2705
|
+
return css;
|
|
2706
|
+
}
|
|
2707
|
+
/**
|
|
2708
|
+
* Render accumulated per-scheme declaration lines as a Tailwind v4 CSS string:
|
|
2709
|
+
* an `@theme` block (light baseline) plus dark / high-contrast overrides under
|
|
2710
|
+
* the configured selectors. Empty blocks are skipped.
|
|
2711
|
+
*/
|
|
2712
|
+
function emitTailwindCss(lines, modes, darkSelector, highContrastSelector) {
|
|
2713
|
+
const blocks = [];
|
|
2714
|
+
if (lines.light.length > 0) blocks.push(emitRule("@theme", lines.light.join("\n")));
|
|
2715
|
+
if (modes.dark) {
|
|
2716
|
+
const dark = emitScoped([darkSelector], lines.dark);
|
|
2717
|
+
if (dark) blocks.push(dark);
|
|
2718
|
+
}
|
|
2719
|
+
if (modes.highContrast) {
|
|
2720
|
+
const hc = emitScoped([highContrastSelector], lines.lightContrast);
|
|
2721
|
+
if (hc) blocks.push(hc);
|
|
2722
|
+
}
|
|
2723
|
+
if (modes.dark && modes.highContrast) {
|
|
2724
|
+
const dhc = emitScoped([darkSelector, highContrastSelector], lines.darkContrast);
|
|
2725
|
+
if (dhc) blocks.push(dhc);
|
|
2726
|
+
}
|
|
2727
|
+
return blocks.join("\n\n");
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Build per-scheme declaration lines for a single theme (used by
|
|
2731
|
+
* `theme.tailwind()` and as the palette `buildOne` step).
|
|
2732
|
+
*/
|
|
2733
|
+
function buildTailwindLines(resolved, themePrefix, cssPrefix, format, pastel) {
|
|
2734
|
+
return tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel);
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* Build a complete Tailwind v4 CSS string for a single theme.
|
|
2738
|
+
*/
|
|
2739
|
+
function buildTailwindMap(resolved, themePrefix, cssPrefix, modes, format, darkSelector, highContrastSelector, pastel = false) {
|
|
2740
|
+
return emitTailwindCss(tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel), modes, darkSelector, highContrastSelector);
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
//#endregion
|
|
2744
|
+
//#region src/color-token.ts
|
|
2745
|
+
/**
|
|
2746
|
+
* Standalone single-color tokens (`glaze.color()` / `glaze.colorFrom()`).
|
|
2747
|
+
*
|
|
2748
|
+
* Owns the value-shorthand parser (hex, `rgb()` / `hsl()` / `okhsl()` /
|
|
2749
|
+
* `okhst()` / `oklch()`, `{ r, g, b }`, `{ h, s, l }`, `{ h, s, t }`,
|
|
2750
|
+
* `{ l, c, h }`), the structured-input validator, the two factory paths
|
|
2751
|
+
* (value vs structured), and the JSON-safe export / rehydration round-trip.
|
|
2752
|
+
*
|
|
2753
|
+
* Tokens store a sparse local config override only. Resolve merges the
|
|
2754
|
+
* live global config with that local override (invalidated on
|
|
2755
|
+
* `configure()`). Authoring `.export(override?)` freezes
|
|
2756
|
+
* `getConfig() ∪ local ∪ override` at call time.
|
|
2757
|
+
*/
|
|
2758
|
+
/** Internal name of the user-facing standalone color in the synthesized def map. */
|
|
2759
|
+
const STANDALONE_VALUE = "value";
|
|
2760
|
+
/** Internal name of the hidden static-anchor seed used for relative tone / contrast. */
|
|
2761
|
+
const STANDALONE_SEED = "seed";
|
|
2762
|
+
/** Internal name of an externally-resolved `GlazeColorToken` injected as a base reference. */
|
|
2763
|
+
const STANDALONE_BASE = "externalBase";
|
|
2764
|
+
/** Reserved internal names that user-supplied `name` must not collide with. */
|
|
2765
|
+
const RESERVED_STANDALONE_NAMES = new Set([
|
|
2766
|
+
STANDALONE_VALUE,
|
|
2767
|
+
STANDALONE_SEED,
|
|
2768
|
+
STANDALONE_BASE
|
|
2769
|
+
]);
|
|
2770
|
+
/**
|
|
2771
|
+
* Value-form local override: `lightTone` defaults to `false` (preserve
|
|
2772
|
+
* input tone). User override fields win.
|
|
2773
|
+
*/
|
|
2774
|
+
function sparseValueFormLocal(userOverride) {
|
|
2775
|
+
return {
|
|
2776
|
+
...userOverride,
|
|
2777
|
+
lightTone: userOverride?.lightTone !== void 0 ? userOverride.lightTone : false
|
|
2778
|
+
};
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* Matches the CSS color functions Glaze itself emits (`rgb()`, `hsl()`,
|
|
2782
|
+
* `okhsl()`, `oklch()`) plus their legacy alpha aliases (`rgba()`, `hsla()`).
|
|
2783
|
+
*
|
|
2784
|
+
* Only bare numeric components are supported. Named colors (`red`),
|
|
2785
|
+
* relative-color syntax (`from <color> ...`), and angle units other
|
|
2786
|
+
* than bare degrees (`deg` is the only suffix tolerated by `parseFloat`)
|
|
2787
|
+
* are out of scope.
|
|
2788
|
+
*/
|
|
2789
|
+
const COLOR_FN_RE = /^(rgba?|hsla?|okhsl|okhst|oklch)\(\s*([^)]*)\s*\)$/i;
|
|
2790
|
+
function parseNumberOrPercent(raw, percentScale) {
|
|
2791
|
+
if (raw.endsWith("%")) return parseFloat(raw) / 100 * percentScale;
|
|
2792
|
+
return parseFloat(raw);
|
|
2793
|
+
}
|
|
2794
|
+
/**
|
|
2795
|
+
* Split the body of a CSS color function into its components and detect
|
|
2796
|
+
* whether an alpha channel was present.
|
|
2797
|
+
*
|
|
2798
|
+
* Handles both modern slash syntax (`R G B / A` or `R, G, B / A`) and
|
|
2799
|
+
* legacy comma syntax (`R, G, B, A`). The alpha value itself is discarded
|
|
2800
|
+
* by the caller — standalone Glaze colors have no opacity field.
|
|
2801
|
+
*/
|
|
2802
|
+
function splitColorBody(body) {
|
|
2803
|
+
const slashIdx = body.indexOf("/");
|
|
2804
|
+
if (slashIdx !== -1) return {
|
|
2805
|
+
components: body.slice(0, slashIdx).trim().split(/[\s,]+/).filter(Boolean),
|
|
2806
|
+
hadAlpha: body.slice(slashIdx + 1).trim().length > 0
|
|
2807
|
+
};
|
|
2808
|
+
const components = body.split(/[\s,]+/).filter(Boolean);
|
|
2809
|
+
if (components.length === 4) {
|
|
2810
|
+
components.pop();
|
|
2811
|
+
return {
|
|
2812
|
+
components,
|
|
2813
|
+
hadAlpha: true
|
|
2814
|
+
};
|
|
2815
|
+
}
|
|
2816
|
+
return {
|
|
2817
|
+
components,
|
|
2818
|
+
hadAlpha: false
|
|
2819
|
+
};
|
|
2820
|
+
}
|
|
2821
|
+
function warnDroppedAlpha(input) {
|
|
2822
|
+
console.warn(`glaze: alpha component dropped from "${input}" (standalone color has no opacity field).`);
|
|
2823
|
+
}
|
|
2824
|
+
function parseColorString(input) {
|
|
2825
|
+
if (input.startsWith("#")) {
|
|
2826
|
+
const parsed = parseHexAlpha(input);
|
|
2827
|
+
if (!parsed) throw new Error(`glaze: invalid hex color "${input}".`);
|
|
2828
|
+
if (parsed.alpha !== void 0) warnDroppedAlpha(input);
|
|
2829
|
+
const [h, s, l] = srgbToOkhsl(parsed.rgb);
|
|
2830
|
+
return {
|
|
2831
|
+
h,
|
|
2832
|
+
s,
|
|
2833
|
+
l
|
|
2834
|
+
};
|
|
2835
|
+
}
|
|
2836
|
+
const m = input.match(COLOR_FN_RE);
|
|
2837
|
+
if (!m) throw new Error(`glaze: unsupported color string "${input}".`);
|
|
2838
|
+
const fn = m[1].toLowerCase();
|
|
2839
|
+
const { components, hadAlpha } = splitColorBody(m[2].trim());
|
|
2840
|
+
if (hadAlpha) warnDroppedAlpha(input);
|
|
2841
|
+
if (components.length !== 3) throw new Error(`glaze: expected 3 components in "${input}".`);
|
|
2842
|
+
switch (fn) {
|
|
2843
|
+
case "rgb":
|
|
2844
|
+
case "rgba": {
|
|
2845
|
+
const [h, s, l] = srgbToOkhsl([
|
|
2846
|
+
parseNumberOrPercent(components[0], 255) / 255,
|
|
2847
|
+
parseNumberOrPercent(components[1], 255) / 255,
|
|
2848
|
+
parseNumberOrPercent(components[2], 255) / 255
|
|
2849
|
+
]);
|
|
2850
|
+
return {
|
|
2851
|
+
h,
|
|
2852
|
+
s,
|
|
2853
|
+
l
|
|
2854
|
+
};
|
|
2855
|
+
}
|
|
2856
|
+
case "hsl":
|
|
2857
|
+
case "hsla": {
|
|
2858
|
+
const [oh, os, ol] = srgbToOkhsl(hslToSrgb(parseFloat(components[0]), parseNumberOrPercent(components[1], 1), parseNumberOrPercent(components[2], 1)));
|
|
2859
|
+
return {
|
|
2860
|
+
h: oh,
|
|
2861
|
+
s: os,
|
|
2862
|
+
l: ol
|
|
2863
|
+
};
|
|
2864
|
+
}
|
|
2865
|
+
case "okhsl": return {
|
|
2866
|
+
h: parseFloat(components[0]),
|
|
2867
|
+
s: parseNumberOrPercent(components[1], 1),
|
|
2868
|
+
l: parseNumberOrPercent(components[2], 1)
|
|
2869
|
+
};
|
|
2870
|
+
case "okhst": return okhstToOkhsl({
|
|
2871
|
+
h: parseFloat(components[0]),
|
|
2872
|
+
s: parseNumberOrPercent(components[1], 1),
|
|
2873
|
+
t: parseNumberOrPercent(components[2], 1)
|
|
2874
|
+
});
|
|
2875
|
+
case "oklch": {
|
|
2876
|
+
const L = parseNumberOrPercent(components[0], 1);
|
|
2877
|
+
const C = parseNumberOrPercent(components[1], .4);
|
|
2878
|
+
const hRad = parseFloat(components[2]) * Math.PI / 180;
|
|
2879
|
+
const [h, s, l] = oklabToOkhsl([
|
|
2880
|
+
L,
|
|
2881
|
+
C * Math.cos(hRad),
|
|
2882
|
+
C * Math.sin(hRad)
|
|
2883
|
+
]);
|
|
2884
|
+
return {
|
|
2885
|
+
h,
|
|
2886
|
+
s,
|
|
2887
|
+
l
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
throw new Error(`glaze: unsupported color function "${fn}".`);
|
|
2892
|
+
}
|
|
2893
|
+
/**
|
|
2894
|
+
* Validate a user-supplied `OkhslColor`. Catches the common 0-100 vs 0-1
|
|
2895
|
+
* confusion (the structured form uses 0-100, OKHSL objects use 0-1).
|
|
2896
|
+
*/
|
|
2897
|
+
function validateOkhslColor(value) {
|
|
2898
|
+
const { h, s, l } = value;
|
|
2899
|
+
if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l)) throw new Error("glaze.color: OkhslColor h/s/l must be finite numbers.");
|
|
2900
|
+
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, tone } (which uses 0–100)?");
|
|
2901
|
+
}
|
|
2902
|
+
/** Validate a user-supplied `{ r, g, b }` object in 0–255. */
|
|
2903
|
+
function validateRgbColor(value) {
|
|
2904
|
+
for (const key of [
|
|
2905
|
+
"r",
|
|
2906
|
+
"g",
|
|
2907
|
+
"b"
|
|
2908
|
+
]) {
|
|
2909
|
+
const n = value[key];
|
|
2910
|
+
if (!Number.isFinite(n) || n < 0 || n > 255) throw new Error(`glaze.color: RgbColor ${key} must be a finite number in 0–255 (got ${n}).`);
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
/** Validate a user-supplied `{ l, c, h }` OKLCh object. */
|
|
2914
|
+
function validateOklchColor(value) {
|
|
2915
|
+
const { l, c, h } = value;
|
|
2916
|
+
if (!Number.isFinite(l) || !Number.isFinite(c) || !Number.isFinite(h)) throw new Error("glaze.color: OklchColor l/c/h must be finite numbers.");
|
|
2917
|
+
if (l > 1.5 || c > 1.5) throw new Error("glaze.color: OklchColor l/c must be in 0–1 range (matching oklch() strings).");
|
|
2918
|
+
}
|
|
2919
|
+
function oklchComponentsToOkhsl(l, c, hDeg) {
|
|
2920
|
+
const hRad = hDeg * Math.PI / 180;
|
|
2921
|
+
const [h, s, outL] = oklabToOkhsl([
|
|
2922
|
+
l,
|
|
2923
|
+
c * Math.cos(hRad),
|
|
2924
|
+
c * Math.sin(hRad)
|
|
2925
|
+
]);
|
|
2926
|
+
return {
|
|
2927
|
+
h,
|
|
2928
|
+
s,
|
|
2929
|
+
l: outL
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
function isRgbColorObject(value) {
|
|
2933
|
+
return "r" in value && "g" in value && "b" in value;
|
|
2934
|
+
}
|
|
2935
|
+
function isOklchColorObject(value) {
|
|
2936
|
+
return "c" in value && "l" in value && "h" in value;
|
|
2937
|
+
}
|
|
2938
|
+
function isOkhstColorObject(value) {
|
|
2939
|
+
return "t" in value && "h" in value && "s" in value;
|
|
2940
|
+
}
|
|
2941
|
+
/** Validate a user-supplied `{ h, s, t }` OKHST object (s/t in 0–1). */
|
|
2942
|
+
function validateOkhstColor(value) {
|
|
2943
|
+
const { h, s, t } = value;
|
|
2944
|
+
if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(t)) throw new Error("glaze.color: OkhstColor h/s/t must be finite numbers.");
|
|
2945
|
+
if (s > 1.5 || t > 1.5) throw new Error("glaze.color: OkhstColor s/t must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
|
|
1318
2946
|
}
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
2947
|
+
/**
|
|
2948
|
+
* Validate a user-supplied `opacity` override on `glaze.color()`.
|
|
2949
|
+
* Must be a finite number in `0..=1`.
|
|
2950
|
+
*/
|
|
2951
|
+
function validateStandaloneOpacity(value) {
|
|
2952
|
+
if (!Number.isFinite(value) || value < 0 || value > 1) throw new Error(`glaze.color: opacity must be a finite number in 0–1 (got ${value}).`);
|
|
1324
2953
|
}
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
2954
|
+
/**
|
|
2955
|
+
* Validate a structured `GlazeColorInput`. Range-checks the `hue` /
|
|
2956
|
+
* `saturation` / `tone` numerics (and any HC-pair second value)
|
|
2957
|
+
* before the resolver sees them so out-of-range or non-finite inputs
|
|
2958
|
+
* fail with a helpful, top-level error rather than producing a
|
|
2959
|
+
* NaN-laden token. `opacity` is checked here too so all input
|
|
2960
|
+
* validation lives in one place.
|
|
2961
|
+
*/
|
|
2962
|
+
function validateStructuredInput(input) {
|
|
2963
|
+
if (!Number.isFinite(input.hue)) throw new Error(`glaze.color: structured hue must be a finite number (got ${input.hue}).`);
|
|
2964
|
+
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}).`);
|
|
2965
|
+
const checkTone = (value, label) => {
|
|
2966
|
+
if (value === "max" || value === "min") return;
|
|
2967
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) throw new Error(`glaze.color: structured ${label} must be a finite number in 0–100 or 'max'/'min' (got ${String(value)}).`);
|
|
2968
|
+
};
|
|
2969
|
+
if (Array.isArray(input.tone)) {
|
|
2970
|
+
checkTone(input.tone[0], "tone[normal]");
|
|
2971
|
+
checkTone(input.tone[1], "tone[hc]");
|
|
2972
|
+
} else checkTone(input.tone, "tone");
|
|
2973
|
+
if (input.saturationFactor !== void 0) {
|
|
2974
|
+
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}).`);
|
|
1334
2975
|
}
|
|
1335
|
-
|
|
2976
|
+
if (input.opacity !== void 0) validateStandaloneOpacity(input.opacity);
|
|
1336
2977
|
}
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
if (modes.highContrast) result.lightContrast[key] = formatVariant(color.lightContrast, format);
|
|
1347
|
-
if (modes.dark && modes.highContrast) result.darkContrast[key] = formatVariant(color.darkContrast, format);
|
|
2978
|
+
/**
|
|
2979
|
+
* Validate a user-supplied `name` override. Rejects empty / whitespace-only
|
|
2980
|
+
* strings and names colliding with `glaze`'s reserved internal sentinels.
|
|
2981
|
+
*/
|
|
2982
|
+
function validateStandaloneName(name) {
|
|
2983
|
+
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.");
|
|
2984
|
+
if (RESERVED_STANDALONE_NAMES.has(name)) {
|
|
2985
|
+
const reserved = [...RESERVED_STANDALONE_NAMES].map((n) => `"${n}"`).join(", ");
|
|
2986
|
+
throw new Error(`glaze.color: name "${name}" is reserved (used internally). Reserved names are: ${reserved}. Pick a different name.`);
|
|
1348
2987
|
}
|
|
1349
|
-
return result;
|
|
1350
2988
|
}
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
2989
|
+
/**
|
|
2990
|
+
* Extract an OKHSL color from any `GlazeColorValue` form. Also used by
|
|
2991
|
+
* `glaze.shadow()` so all shadow inputs (hex, color functions, OKHSL,
|
|
2992
|
+
* literal objects) go through one parser.
|
|
2993
|
+
*/
|
|
2994
|
+
function extractOkhslFromValue(value) {
|
|
2995
|
+
if (typeof value === "string") return parseColorString(value);
|
|
2996
|
+
if (Array.isArray(value)) throw new Error("glaze.color: RGB tuple [r, g, b] is no longer supported — use { r, g, b } instead.");
|
|
2997
|
+
if (isRgbColorObject(value)) {
|
|
2998
|
+
validateRgbColor(value);
|
|
2999
|
+
const [h, s, l] = srgbToOkhsl([
|
|
3000
|
+
value.r / 255,
|
|
3001
|
+
value.g / 255,
|
|
3002
|
+
value.b / 255
|
|
3003
|
+
]);
|
|
3004
|
+
return {
|
|
3005
|
+
h,
|
|
3006
|
+
s,
|
|
3007
|
+
l
|
|
3008
|
+
};
|
|
1359
3009
|
}
|
|
1360
|
-
|
|
3010
|
+
if (isOklchColorObject(value)) {
|
|
3011
|
+
validateOklchColor(value);
|
|
3012
|
+
return oklchComponentsToOkhsl(value.l, value.c, value.h);
|
|
3013
|
+
}
|
|
3014
|
+
if (isOkhstColorObject(value)) {
|
|
3015
|
+
validateOkhstColor(value);
|
|
3016
|
+
return okhstToOkhsl(value);
|
|
3017
|
+
}
|
|
3018
|
+
validateOkhslColor(value);
|
|
3019
|
+
return value;
|
|
1361
3020
|
}
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
3021
|
+
/**
|
|
3022
|
+
* Build the `ColorMap` for a value-shorthand `glaze.color()` call.
|
|
3023
|
+
*
|
|
3024
|
+
* The user-facing color (`STANDALONE_VALUE`) defaults to `mode: 'auto'`
|
|
3025
|
+
* across every value-shorthand form.
|
|
3026
|
+
*
|
|
3027
|
+
* When the user requests `contrast` or relative `tone`, a hidden
|
|
3028
|
+
* `STANDALONE_SEED` def is synthesized at `mode: 'static'`. That keeps
|
|
3029
|
+
* the seed pinned to the literal user-provided color across all four
|
|
3030
|
+
* variants, so the contrast solver always anchors against it.
|
|
3031
|
+
*/
|
|
3032
|
+
function buildStandaloneValueDefs(main, options) {
|
|
3033
|
+
const seedHue = typeof options?.hue === "number" ? options.hue : main.h;
|
|
3034
|
+
const seedSaturation = options?.saturation ?? main.s * 100;
|
|
3035
|
+
const relativeHue = typeof options?.hue === "string" ? options.hue : void 0;
|
|
3036
|
+
const toneOption = options?.tone;
|
|
3037
|
+
const hasExternalBase = options?.base !== void 0;
|
|
3038
|
+
const needsSeedAnchor = !hasExternalBase && (options?.contrast !== void 0 || toneOption !== void 0 && !isAbsoluteTone(toneOption));
|
|
3039
|
+
if (options?.opacity !== void 0) validateStandaloneOpacity(options.opacity);
|
|
3040
|
+
const userName = options?.name;
|
|
3041
|
+
if (userName !== void 0) validateStandaloneName(userName);
|
|
3042
|
+
const primary = userName ?? STANDALONE_VALUE;
|
|
3043
|
+
const seedTone = toTone(main.l);
|
|
3044
|
+
const valueDef = {
|
|
3045
|
+
hue: relativeHue,
|
|
3046
|
+
saturation: options?.saturationFactor,
|
|
3047
|
+
tone: toneOption ?? seedTone,
|
|
3048
|
+
contrast: options?.contrast,
|
|
3049
|
+
mode: options?.mode ?? "auto",
|
|
3050
|
+
autoFlip: options?.autoFlip,
|
|
3051
|
+
opacity: options?.opacity,
|
|
3052
|
+
pastel: options?.pastel,
|
|
3053
|
+
role: options?.role,
|
|
3054
|
+
base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
|
|
1368
3055
|
};
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
3056
|
+
const defs = { [primary]: valueDef };
|
|
3057
|
+
if (needsSeedAnchor) defs[STANDALONE_SEED] = {
|
|
3058
|
+
hue: main.h,
|
|
3059
|
+
saturation: 1,
|
|
3060
|
+
tone: seedTone,
|
|
3061
|
+
mode: "static"
|
|
3062
|
+
};
|
|
3063
|
+
return {
|
|
3064
|
+
seedHue,
|
|
3065
|
+
seedSaturation,
|
|
3066
|
+
defs,
|
|
3067
|
+
primary
|
|
3068
|
+
};
|
|
3069
|
+
}
|
|
3070
|
+
function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, configOverride, baseToken, buildExport) {
|
|
3071
|
+
let cache = null;
|
|
3072
|
+
function getEffectiveConfig() {
|
|
3073
|
+
const version = getConfigVersion();
|
|
3074
|
+
if (cache && cache.version === version) return cache.effectiveConfig;
|
|
3075
|
+
const effectiveConfig = mergeConfig(getConfig(), configOverride);
|
|
3076
|
+
cache = {
|
|
3077
|
+
map: null,
|
|
3078
|
+
version,
|
|
3079
|
+
effectiveConfig
|
|
3080
|
+
};
|
|
3081
|
+
return effectiveConfig;
|
|
1375
3082
|
}
|
|
3083
|
+
const resolveOnce = () => {
|
|
3084
|
+
const version = getConfigVersion();
|
|
3085
|
+
if (cache && cache.version === version && cache.map) return cache.map;
|
|
3086
|
+
const effectiveConfig = getEffectiveConfig();
|
|
3087
|
+
const map = resolveAllColors(seedHue, seedSaturation, defs, effectiveConfig, baseToken ? new Map([[STANDALONE_BASE, baseToken.resolve()]]) : void 0);
|
|
3088
|
+
cache = {
|
|
3089
|
+
map,
|
|
3090
|
+
version,
|
|
3091
|
+
effectiveConfig
|
|
3092
|
+
};
|
|
3093
|
+
return map;
|
|
3094
|
+
};
|
|
3095
|
+
const resolveStates = (options) => {
|
|
3096
|
+
const cfg = getConfig();
|
|
3097
|
+
return {
|
|
3098
|
+
dark: options?.states?.dark ?? cfg.states.dark,
|
|
3099
|
+
highContrast: options?.states?.highContrast ?? cfg.states.highContrast
|
|
3100
|
+
};
|
|
3101
|
+
};
|
|
3102
|
+
const tokenLike = (options) => {
|
|
3103
|
+
return buildTokenMap(resolveOnce(), "", resolveStates(options), resolveModes(options?.modes), options?.format ?? "oklch", getEffectiveConfig().pastel)[`#${primary}`];
|
|
3104
|
+
};
|
|
1376
3105
|
return {
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
3106
|
+
resolve() {
|
|
3107
|
+
return resolveOnce().get(primary);
|
|
3108
|
+
},
|
|
3109
|
+
token: tokenLike,
|
|
3110
|
+
tasty: tokenLike,
|
|
3111
|
+
json(options) {
|
|
3112
|
+
const format = options?.format ?? "oklch";
|
|
3113
|
+
assertNativeFormat(format, "json");
|
|
3114
|
+
return buildJsonMap(resolveOnce(), resolveModes(options?.modes), format, getEffectiveConfig().pastel)[primary];
|
|
3115
|
+
},
|
|
3116
|
+
css(options) {
|
|
3117
|
+
const format = options.format ?? "oklch";
|
|
3118
|
+
assertNativeFormat(format, "css");
|
|
3119
|
+
const resolved = resolveOnce().get(primary);
|
|
3120
|
+
const renamed = new Map([[options.name, resolved]]);
|
|
3121
|
+
let channelCtx;
|
|
3122
|
+
if (options.splitHue && format === "oklch") {
|
|
3123
|
+
assertAllPastel(renamed, resolveModes());
|
|
3124
|
+
channelCtx = {
|
|
3125
|
+
seedHue,
|
|
3126
|
+
baseName: options.name,
|
|
3127
|
+
prefix: "",
|
|
3128
|
+
defs: { [options.name]: defs[primary] },
|
|
3129
|
+
mode: "standalone",
|
|
3130
|
+
resolvedHue: resolved.light.h
|
|
3131
|
+
};
|
|
3132
|
+
}
|
|
3133
|
+
return buildCssMap(renamed, "", options.suffix ?? "-color", format, getEffectiveConfig().pastel, channelCtx);
|
|
3134
|
+
},
|
|
3135
|
+
dtcg(options) {
|
|
3136
|
+
const modes = resolveModes(options?.modes);
|
|
3137
|
+
const doc = buildDtcgMap(resolveOnce(), "", modes, options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
|
|
3138
|
+
const result = { light: doc.light[primary] };
|
|
3139
|
+
if (doc.dark) result.dark = doc.dark[primary];
|
|
3140
|
+
if (doc.lightContrast) result.lightContrast = doc.lightContrast[primary];
|
|
3141
|
+
if (doc.darkContrast) result.darkContrast = doc.darkContrast[primary];
|
|
3142
|
+
return result;
|
|
3143
|
+
},
|
|
3144
|
+
dtcgResolver(options) {
|
|
3145
|
+
const doc = buildDtcgMap(resolveOnce(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
|
|
3146
|
+
const name = options.name;
|
|
3147
|
+
const result = { light: { [name]: doc.light[primary] } };
|
|
3148
|
+
if (doc.dark) result.dark = { [name]: doc.dark[primary] };
|
|
3149
|
+
if (doc.lightContrast) result.lightContrast = { [name]: doc.lightContrast[primary] };
|
|
3150
|
+
if (doc.darkContrast) result.darkContrast = { [name]: doc.darkContrast[primary] };
|
|
3151
|
+
return buildDtcgResolver(result, options);
|
|
3152
|
+
},
|
|
3153
|
+
tailwind(options) {
|
|
3154
|
+
const format = options.format ?? "oklch";
|
|
3155
|
+
assertNativeFormat(format, "tailwind");
|
|
3156
|
+
return buildTailwindMap(new Map([[options.name, resolveOnce().get(primary)]]), "", options.namespace ?? "color-", resolveModes(options?.modes), format, options.darkSelector ?? ".dark", options.highContrastSelector ?? ".high-contrast", getEffectiveConfig().pastel);
|
|
3157
|
+
},
|
|
3158
|
+
export(override) {
|
|
3159
|
+
return buildExport(override);
|
|
3160
|
+
}
|
|
3161
|
+
};
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* When a value/`from` color links to a base that was created via the
|
|
3165
|
+
* structured form (with explicit `hue`/`saturation`/`tone`), resolve
|
|
3166
|
+
* that base with `lightTone: false` for the linking math so the
|
|
3167
|
+
* contrast/tone anchor matches the input tone — not the
|
|
3168
|
+
* windowed output. The original base token's `.resolve()` is unaffected.
|
|
3169
|
+
*/
|
|
3170
|
+
function toLinkingBase(base) {
|
|
3171
|
+
if (!base) return void 0;
|
|
3172
|
+
const exp = base.export();
|
|
3173
|
+
if (exp.form !== "structured") return base;
|
|
3174
|
+
const linkingConfig = {
|
|
3175
|
+
...exp.config ?? {},
|
|
3176
|
+
lightTone: false
|
|
3177
|
+
};
|
|
3178
|
+
return colorFromExport({
|
|
3179
|
+
...exp,
|
|
3180
|
+
config: linkingConfig
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3183
|
+
/**
|
|
3184
|
+
* Resolve `base` (which may be a token reference or a raw color value)
|
|
3185
|
+
* into a `GlazeColorToken`. Raw values are auto-wrapped via
|
|
3186
|
+
* `createColorTokenFromValue` so they pick up the same auto-invert
|
|
3187
|
+
* defaults as an explicit wrap. Returns `undefined` when no base is provided.
|
|
3188
|
+
*/
|
|
3189
|
+
function resolveBaseToken(base) {
|
|
3190
|
+
if (base === void 0) return void 0;
|
|
3191
|
+
if (isGlazeColorToken(base)) return base;
|
|
3192
|
+
return createColorTokenFromValue(base, void 0, void 0);
|
|
3193
|
+
}
|
|
3194
|
+
/**
|
|
3195
|
+
* Discriminate a `GlazeColorToken` from a raw `GlazeColorValue`.
|
|
3196
|
+
*/
|
|
3197
|
+
function isGlazeColorToken(candidate) {
|
|
3198
|
+
return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) && "resolve" in candidate && typeof candidate.resolve === "function";
|
|
3199
|
+
}
|
|
3200
|
+
function createColorToken(input, configOverride) {
|
|
3201
|
+
validateStructuredInput(input);
|
|
3202
|
+
const userName = input.name;
|
|
3203
|
+
if (userName !== void 0) validateStandaloneName(userName);
|
|
3204
|
+
const primary = userName ?? STANDALONE_VALUE;
|
|
3205
|
+
const baseToken = resolveBaseToken(input.base);
|
|
3206
|
+
const hasExternalBase = baseToken !== void 0;
|
|
3207
|
+
const needsSeedAnchor = !hasExternalBase && input.contrast !== void 0;
|
|
3208
|
+
const defs = { [primary]: {
|
|
3209
|
+
tone: input.tone,
|
|
3210
|
+
saturation: input.saturationFactor,
|
|
3211
|
+
mode: input.mode ?? "auto",
|
|
3212
|
+
autoFlip: input.autoFlip,
|
|
3213
|
+
contrast: input.contrast,
|
|
3214
|
+
opacity: input.opacity,
|
|
3215
|
+
pastel: input.pastel,
|
|
3216
|
+
role: input.role,
|
|
3217
|
+
base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
|
|
3218
|
+
} };
|
|
3219
|
+
if (needsSeedAnchor) {
|
|
3220
|
+
const seedTone = pairNormal(input.tone);
|
|
3221
|
+
defs[STANDALONE_SEED] = {
|
|
3222
|
+
tone: seedTone === "max" ? 100 : seedTone === "min" ? 0 : seedTone,
|
|
3223
|
+
saturation: 1,
|
|
3224
|
+
mode: "static"
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
const localOverride = configOverride;
|
|
3228
|
+
return createColorTokenFromDefs(input.hue, input.saturation, defs, primary, localOverride, baseToken, (exportArg) => ({
|
|
3229
|
+
kind: "color",
|
|
3230
|
+
version: GLAZE_EXPORT_VERSION,
|
|
3231
|
+
form: "structured",
|
|
3232
|
+
input: buildStructuredInputExport(input, exportArg),
|
|
3233
|
+
config: freezeConfigForExport(localOverride, exportArg)
|
|
3234
|
+
}));
|
|
3235
|
+
}
|
|
3236
|
+
function createColorTokenFromValue(value, options, configOverride) {
|
|
3237
|
+
const main = extractOkhslFromValue(value);
|
|
3238
|
+
const linkingBase = toLinkingBase(resolveBaseToken(options?.base));
|
|
3239
|
+
const { seedHue, seedSaturation, defs, primary } = buildStandaloneValueDefs(main, options);
|
|
3240
|
+
const localOverride = sparseValueFormLocal(configOverride);
|
|
3241
|
+
return createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, localOverride, linkingBase, (exportArg) => ({
|
|
3242
|
+
kind: "color",
|
|
3243
|
+
version: GLAZE_EXPORT_VERSION,
|
|
3244
|
+
form: "value",
|
|
3245
|
+
input: value,
|
|
3246
|
+
...options !== void 0 ? { overrides: buildOverridesExport(options, exportArg) } : {},
|
|
3247
|
+
config: freezeConfigForExport(localOverride, exportArg)
|
|
3248
|
+
}));
|
|
3249
|
+
}
|
|
3250
|
+
/**
|
|
3251
|
+
* Build a JSON-safe snapshot of `GlazeColorOverrides`. `base` is
|
|
3252
|
+
* recursively serialized when it was originally a token; raw values are
|
|
3253
|
+
* preserved as-is so `glaze.colorFrom(...)` round-trips them.
|
|
3254
|
+
*/
|
|
3255
|
+
function buildOverridesExport(options, exportArg) {
|
|
3256
|
+
const out = {};
|
|
3257
|
+
if (options.hue !== void 0) out.hue = options.hue;
|
|
3258
|
+
if (options.saturation !== void 0) out.saturation = options.saturation;
|
|
3259
|
+
if (options.tone !== void 0) out.tone = options.tone;
|
|
3260
|
+
if (options.saturationFactor !== void 0) out.saturationFactor = options.saturationFactor;
|
|
3261
|
+
if (options.mode !== void 0) out.mode = options.mode;
|
|
3262
|
+
if (options.autoFlip !== void 0) out.autoFlip = options.autoFlip;
|
|
3263
|
+
if (options.contrast !== void 0) out.contrast = options.contrast;
|
|
3264
|
+
if (options.opacity !== void 0) out.opacity = options.opacity;
|
|
3265
|
+
if (options.name !== void 0) out.name = options.name;
|
|
3266
|
+
if (options.pastel !== void 0) out.pastel = options.pastel;
|
|
3267
|
+
if (options.role !== void 0) out.role = options.role;
|
|
3268
|
+
if (options.base !== void 0) out.base = isGlazeColorToken(options.base) ? options.base.export(exportArg) : options.base;
|
|
3269
|
+
return out;
|
|
3270
|
+
}
|
|
3271
|
+
function buildStructuredInputExport(input, exportArg) {
|
|
3272
|
+
const out = {
|
|
3273
|
+
hue: input.hue,
|
|
3274
|
+
saturation: input.saturation,
|
|
3275
|
+
tone: input.tone
|
|
1381
3276
|
};
|
|
3277
|
+
if (input.saturationFactor !== void 0) out.saturationFactor = input.saturationFactor;
|
|
3278
|
+
if (input.mode !== void 0) out.mode = input.mode;
|
|
3279
|
+
if (input.autoFlip !== void 0) out.autoFlip = input.autoFlip;
|
|
3280
|
+
if (input.opacity !== void 0) out.opacity = input.opacity;
|
|
3281
|
+
if (input.contrast !== void 0) out.contrast = input.contrast;
|
|
3282
|
+
if (input.name !== void 0) out.name = input.name;
|
|
3283
|
+
if (input.pastel !== void 0) out.pastel = input.pastel;
|
|
3284
|
+
if (input.role !== void 0) out.role = input.role;
|
|
3285
|
+
if (input.base !== void 0) out.base = isGlazeColorToken(input.base) ? input.base.export(exportArg) : input.base;
|
|
3286
|
+
return out;
|
|
1382
3287
|
}
|
|
1383
|
-
|
|
3288
|
+
/**
|
|
3289
|
+
* Discriminate a `GlazeColorTokenExport` from a raw `GlazeColorValue`.
|
|
3290
|
+
*/
|
|
3291
|
+
function isExportedToken(candidate) {
|
|
3292
|
+
return isColorTokenExport(candidate);
|
|
3293
|
+
}
|
|
3294
|
+
function rehydrateOverrides(data) {
|
|
3295
|
+
const out = {};
|
|
3296
|
+
if (data.hue !== void 0) out.hue = data.hue;
|
|
3297
|
+
if (data.saturation !== void 0) out.saturation = data.saturation;
|
|
3298
|
+
if (data.tone !== void 0) out.tone = data.tone;
|
|
3299
|
+
if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
|
|
3300
|
+
if (data.mode !== void 0) out.mode = data.mode;
|
|
3301
|
+
if (data.autoFlip !== void 0) out.autoFlip = data.autoFlip;
|
|
3302
|
+
if (data.contrast !== void 0) out.contrast = data.contrast;
|
|
3303
|
+
if (data.opacity !== void 0) out.opacity = data.opacity;
|
|
3304
|
+
if (data.name !== void 0) out.name = data.name;
|
|
3305
|
+
if (data.pastel !== void 0) out.pastel = data.pastel;
|
|
3306
|
+
if (data.role !== void 0) out.role = data.role;
|
|
3307
|
+
if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
|
|
3308
|
+
return out;
|
|
3309
|
+
}
|
|
3310
|
+
function rehydrateStructuredInput(data) {
|
|
3311
|
+
const out = {
|
|
3312
|
+
hue: data.hue,
|
|
3313
|
+
saturation: data.saturation,
|
|
3314
|
+
tone: data.tone
|
|
3315
|
+
};
|
|
3316
|
+
if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
|
|
3317
|
+
if (data.mode !== void 0) out.mode = data.mode;
|
|
3318
|
+
if (data.autoFlip !== void 0) out.autoFlip = data.autoFlip;
|
|
3319
|
+
if (data.opacity !== void 0) out.opacity = data.opacity;
|
|
3320
|
+
if (data.contrast !== void 0) out.contrast = data.contrast;
|
|
3321
|
+
if (data.name !== void 0) out.name = data.name;
|
|
3322
|
+
if (data.pastel !== void 0) out.pastel = data.pastel;
|
|
3323
|
+
if (data.role !== void 0) out.role = data.role;
|
|
3324
|
+
if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
|
|
3325
|
+
return out;
|
|
3326
|
+
}
|
|
3327
|
+
/**
|
|
3328
|
+
* Rehydrate a token from its `.export()` snapshot. Recursively rebuilds
|
|
3329
|
+
* any base dependency. Inverse of `GlazeColorToken.export()`.
|
|
3330
|
+
*
|
|
3331
|
+
* The stored `config` field is the freeze from export time — passed as
|
|
3332
|
+
* the instance local override so the rehydrated token stays pinned
|
|
3333
|
+
* against later `glaze.configure()` calls.
|
|
3334
|
+
*/
|
|
3335
|
+
function colorFromExport(data) {
|
|
3336
|
+
if (data === null || typeof data !== "object") throw new Error(`glaze.colorFrom: expected an object from token.export(), got ${data === null ? "null" : typeof data}.`);
|
|
3337
|
+
assertExportKind(data, "color", "glaze.colorFrom");
|
|
3338
|
+
assertExportVersion(data, "glaze.colorFrom");
|
|
3339
|
+
if (data.form !== "value" && data.form !== "structured") throw new Error(`glaze.colorFrom: invalid "form" field — expected "value" or "structured" (got ${JSON.stringify(data.form)}).`);
|
|
3340
|
+
if (data.input === void 0) throw new Error(`glaze.colorFrom: missing "input" field — expected the original ${data.form === "value" ? "GlazeColorValue" : "GlazeColorInput"}.`);
|
|
3341
|
+
if (data.form === "value") {
|
|
3342
|
+
const value = data.input;
|
|
3343
|
+
return createColorTokenFromValue(value, data.overrides ? rehydrateOverrides(data.overrides) : void 0, data.config);
|
|
3344
|
+
}
|
|
3345
|
+
return createColorToken(rehydrateStructuredInput(data.input), data.config);
|
|
3346
|
+
}
|
|
3347
|
+
|
|
3348
|
+
//#endregion
|
|
3349
|
+
//#region src/theme.ts
|
|
3350
|
+
function createTheme(hue, saturation, initialColors, configOverride) {
|
|
1384
3351
|
let colorDefs = initialColors ? { ...initialColors } : {};
|
|
3352
|
+
let cache = null;
|
|
3353
|
+
function getEffectiveConfig() {
|
|
3354
|
+
const version = getConfigVersion();
|
|
3355
|
+
if (cache && cache.version === version) return cache.effectiveConfig;
|
|
3356
|
+
const effectiveConfig = mergeConfig(getConfig(), configOverride);
|
|
3357
|
+
cache = {
|
|
3358
|
+
map: null,
|
|
3359
|
+
version,
|
|
3360
|
+
effectiveConfig
|
|
3361
|
+
};
|
|
3362
|
+
return effectiveConfig;
|
|
3363
|
+
}
|
|
3364
|
+
function resolveCached() {
|
|
3365
|
+
const version = getConfigVersion();
|
|
3366
|
+
if (cache && cache.version === version && cache.map) return cache.map;
|
|
3367
|
+
const effectiveConfig = getEffectiveConfig();
|
|
3368
|
+
const map = resolveAllColors(hue, saturation, colorDefs, effectiveConfig);
|
|
3369
|
+
cache = {
|
|
3370
|
+
map,
|
|
3371
|
+
version,
|
|
3372
|
+
effectiveConfig
|
|
3373
|
+
};
|
|
3374
|
+
return map;
|
|
3375
|
+
}
|
|
3376
|
+
function invalidate() {
|
|
3377
|
+
cache = null;
|
|
3378
|
+
}
|
|
3379
|
+
function channelCtxFor(options, formatDefault, prefix) {
|
|
3380
|
+
const format = options?.format ?? formatDefault;
|
|
3381
|
+
if (!options?.splitHue || format !== "oklch") return void 0;
|
|
3382
|
+
assertAllPastel(resolveCached(), resolveModes(options?.modes));
|
|
3383
|
+
return {
|
|
3384
|
+
seedHue: hue,
|
|
3385
|
+
baseName: options.name ?? "theme",
|
|
3386
|
+
prefix,
|
|
3387
|
+
defs: colorDefs,
|
|
3388
|
+
mode: "theme"
|
|
3389
|
+
};
|
|
3390
|
+
}
|
|
1385
3391
|
return {
|
|
1386
3392
|
get hue() {
|
|
1387
3393
|
return hue;
|
|
@@ -1389,19 +3395,25 @@ function createTheme(hue, saturation, initialColors) {
|
|
|
1389
3395
|
get saturation() {
|
|
1390
3396
|
return saturation;
|
|
1391
3397
|
},
|
|
3398
|
+
getConfig() {
|
|
3399
|
+
return getEffectiveConfig();
|
|
3400
|
+
},
|
|
1392
3401
|
colors(defs) {
|
|
1393
3402
|
colorDefs = {
|
|
1394
3403
|
...colorDefs,
|
|
1395
3404
|
...defs
|
|
1396
3405
|
};
|
|
3406
|
+
invalidate();
|
|
1397
3407
|
},
|
|
1398
3408
|
color(name, def) {
|
|
1399
3409
|
if (def === void 0) return colorDefs[name];
|
|
1400
3410
|
colorDefs[name] = def;
|
|
3411
|
+
invalidate();
|
|
1401
3412
|
},
|
|
1402
3413
|
remove(names) {
|
|
1403
3414
|
const list = Array.isArray(names) ? names : [names];
|
|
1404
3415
|
for (const name of list) delete colorDefs[name];
|
|
3416
|
+
invalidate();
|
|
1405
3417
|
},
|
|
1406
3418
|
has(name) {
|
|
1407
3419
|
return name in colorDefs;
|
|
@@ -1411,12 +3423,16 @@ function createTheme(hue, saturation, initialColors) {
|
|
|
1411
3423
|
},
|
|
1412
3424
|
reset() {
|
|
1413
3425
|
colorDefs = {};
|
|
3426
|
+
invalidate();
|
|
1414
3427
|
},
|
|
1415
|
-
export() {
|
|
3428
|
+
export(override) {
|
|
1416
3429
|
return {
|
|
3430
|
+
kind: "theme",
|
|
3431
|
+
version: GLAZE_EXPORT_VERSION,
|
|
1417
3432
|
hue,
|
|
1418
3433
|
saturation,
|
|
1419
|
-
colors:
|
|
3434
|
+
colors: structuredClone(colorDefs),
|
|
3435
|
+
config: freezeConfigForExport(configOverride, override)
|
|
1420
3436
|
};
|
|
1421
3437
|
},
|
|
1422
3438
|
extend(options) {
|
|
@@ -1427,28 +3443,61 @@ function createTheme(hue, saturation, initialColors) {
|
|
|
1427
3443
|
return createTheme(newHue, newSat, options.colors ? {
|
|
1428
3444
|
...inheritedColors,
|
|
1429
3445
|
...options.colors
|
|
1430
|
-
} : { ...inheritedColors }
|
|
3446
|
+
} : { ...inheritedColors }, configOverride || options.config ? {
|
|
3447
|
+
...configOverride ?? {},
|
|
3448
|
+
...options.config ?? {}
|
|
3449
|
+
} : void 0);
|
|
1431
3450
|
},
|
|
1432
3451
|
resolve() {
|
|
1433
|
-
return
|
|
3452
|
+
return new Map(resolveCached());
|
|
1434
3453
|
},
|
|
1435
3454
|
tokens(options) {
|
|
1436
|
-
|
|
3455
|
+
const format = options?.format ?? "oklch";
|
|
3456
|
+
assertNativeFormat(format, "tokens");
|
|
3457
|
+
const modes = resolveModes(options?.modes);
|
|
3458
|
+
return buildFlatTokenMap(resolveCached(), "", modes, format, getEffectiveConfig().pastel);
|
|
1437
3459
|
},
|
|
1438
3460
|
tasty(options) {
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
3461
|
+
const cfg = getEffectiveConfig();
|
|
3462
|
+
const states = {
|
|
3463
|
+
dark: options?.states?.dark ?? cfg.states.dark,
|
|
3464
|
+
highContrast: options?.states?.highContrast ?? cfg.states.highContrast
|
|
3465
|
+
};
|
|
3466
|
+
const modes = resolveModes(options?.modes);
|
|
3467
|
+
const format = options?.format ?? "oklch";
|
|
3468
|
+
const channelCtx = channelCtxFor(options, "oklch", "");
|
|
3469
|
+
return buildTokenMap(resolveCached(), "", states, modes, format, cfg.pastel, channelCtx);
|
|
1443
3470
|
},
|
|
1444
3471
|
json(options) {
|
|
1445
|
-
|
|
3472
|
+
const format = options?.format ?? "oklch";
|
|
3473
|
+
assertNativeFormat(format, "json");
|
|
3474
|
+
const modes = resolveModes(options?.modes);
|
|
3475
|
+
return buildJsonMap(resolveCached(), modes, format, getEffectiveConfig().pastel);
|
|
1446
3476
|
},
|
|
1447
3477
|
css(options) {
|
|
1448
|
-
|
|
3478
|
+
const format = options?.format ?? "oklch";
|
|
3479
|
+
assertNativeFormat(format, "css");
|
|
3480
|
+
const channelCtx = channelCtxFor(options, "oklch", "");
|
|
3481
|
+
return buildCssMap(resolveCached(), "", options?.suffix ?? "-color", format, getEffectiveConfig().pastel, channelCtx);
|
|
3482
|
+
},
|
|
3483
|
+
dtcg(options) {
|
|
3484
|
+
const modes = resolveModes(options?.modes);
|
|
3485
|
+
return buildDtcgMap(resolveCached(), "", modes, options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
|
|
3486
|
+
},
|
|
3487
|
+
dtcgResolver(options) {
|
|
3488
|
+
return buildDtcgResolver(buildDtcgMap(resolveCached(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", getEffectiveConfig().pastel), options);
|
|
3489
|
+
},
|
|
3490
|
+
tailwind(options) {
|
|
3491
|
+
const format = options?.format ?? "oklch";
|
|
3492
|
+
assertNativeFormat(format, "tailwind");
|
|
3493
|
+
const modes = resolveModes(options?.modes);
|
|
3494
|
+
return buildTailwindMap(resolveCached(), "", options?.namespace ?? "color-", modes, format, options?.darkSelector ?? ".dark", options?.highContrastSelector ?? ".high-contrast", getEffectiveConfig().pastel);
|
|
1449
3495
|
}
|
|
1450
3496
|
};
|
|
1451
3497
|
}
|
|
3498
|
+
|
|
3499
|
+
//#endregion
|
|
3500
|
+
//#region src/palette.ts
|
|
1452
3501
|
function resolvePrefix(options, themeName, defaultPrefix = false) {
|
|
1453
3502
|
const prefix = options?.prefix ?? defaultPrefix;
|
|
1454
3503
|
if (prefix === true) return `${themeName}-`;
|
|
@@ -1488,185 +3537,306 @@ function filterCollisions(resolved, prefix, seen, themeName, isPrimary) {
|
|
|
1488
3537
|
}
|
|
1489
3538
|
return filtered;
|
|
1490
3539
|
}
|
|
3540
|
+
function colorMapFromTheme(theme) {
|
|
3541
|
+
const defs = {};
|
|
3542
|
+
for (const name of theme.list()) {
|
|
3543
|
+
const def = theme.color(name);
|
|
3544
|
+
if (def !== void 0) defs[name] = def;
|
|
3545
|
+
}
|
|
3546
|
+
return defs;
|
|
3547
|
+
}
|
|
3548
|
+
function channelCtxForTheme(theme, themeName, passPrefix, themedPrefix, splitHue, format, modes, filtered) {
|
|
3549
|
+
if (!splitHue || format !== "oklch") return void 0;
|
|
3550
|
+
assertAllPastel(filtered, modes);
|
|
3551
|
+
return {
|
|
3552
|
+
seedHue: theme.hue,
|
|
3553
|
+
baseName: themeName,
|
|
3554
|
+
prefix: themedPrefix,
|
|
3555
|
+
defs: colorMapFromTheme(theme),
|
|
3556
|
+
mode: "theme",
|
|
3557
|
+
emitDeclarations: passPrefix === themedPrefix
|
|
3558
|
+
};
|
|
3559
|
+
}
|
|
3560
|
+
/**
|
|
3561
|
+
* Shared per-theme driver for `tokens` / `tasty` / `css`. `json` skips
|
|
3562
|
+
* this because it doesn't do collision filtering or primary duplication.
|
|
3563
|
+
*/
|
|
3564
|
+
function buildPaletteOutput(themes, paletteOptions, options, buildOne, merge, empty) {
|
|
3565
|
+
const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
|
|
3566
|
+
if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
|
|
3567
|
+
const acc = empty();
|
|
3568
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3569
|
+
for (const [themeName, theme] of Object.entries(themes)) {
|
|
3570
|
+
const resolved = theme.resolve();
|
|
3571
|
+
const pastel = theme.getConfig().pastel;
|
|
3572
|
+
const prefix = resolvePrefix(options, themeName, true);
|
|
3573
|
+
merge(acc, buildOne(filterCollisions(resolved, prefix, seen, themeName), prefix, pastel, themeName, theme));
|
|
3574
|
+
if (themeName === effectivePrimary) merge(acc, buildOne(filterCollisions(resolved, "", seen, themeName, true), "", pastel, themeName, theme));
|
|
3575
|
+
}
|
|
3576
|
+
return acc;
|
|
3577
|
+
}
|
|
3578
|
+
/** Rebuild a theme from a `theme.export()` snapshot. */
|
|
3579
|
+
function createThemeFromExport(data, factory = "glaze.themeFrom") {
|
|
3580
|
+
if (data === null || typeof data !== "object") throw new Error(`${factory}: expected an object from theme.export(), got ${data === null ? "null" : typeof data}.`);
|
|
3581
|
+
assertExportKind(data, "theme", factory);
|
|
3582
|
+
assertExportVersion(data, factory);
|
|
3583
|
+
if (typeof data.hue !== "number" || typeof data.saturation !== "number") throw new Error(`${factory}: expected numeric "hue" and "saturation" fields.`);
|
|
3584
|
+
return createTheme(data.hue, data.saturation, data.colors, data.config);
|
|
3585
|
+
}
|
|
3586
|
+
/**
|
|
3587
|
+
* Rebuild a palette from a `palette.export()` snapshot.
|
|
3588
|
+
*/
|
|
3589
|
+
function createPaletteFromExport(data) {
|
|
3590
|
+
if (data === null || typeof data !== "object") throw new Error(`glaze.paletteFrom: expected an object from palette.export(), got ${data === null ? "null" : typeof data}.`);
|
|
3591
|
+
assertExportKind(data, "palette", "glaze.paletteFrom");
|
|
3592
|
+
assertExportVersion(data, "glaze.paletteFrom");
|
|
3593
|
+
if (data.themes === null || typeof data.themes !== "object") throw new Error(`glaze.paletteFrom: expected a "themes" object map of theme exports.`);
|
|
3594
|
+
const rebuilt = {};
|
|
3595
|
+
for (const [name, themeExport] of Object.entries(data.themes)) rebuilt[name] = createThemeFromExport(themeExport, `glaze.paletteFrom (theme "${name}")`);
|
|
3596
|
+
return createPalette(rebuilt, { primary: data.primary });
|
|
3597
|
+
}
|
|
1491
3598
|
function createPalette(themes, paletteOptions) {
|
|
1492
3599
|
validatePrimaryTheme(paletteOptions?.primary, themes);
|
|
3600
|
+
const buildDtcgResult = (options) => {
|
|
3601
|
+
const modes = resolveModes(options?.modes);
|
|
3602
|
+
const colorSpace = options?.colorSpace ?? "srgb";
|
|
3603
|
+
return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, _themeName, _theme) => buildDtcgMap(filtered, prefix, modes, colorSpace, pastel), (acc, part) => {
|
|
3604
|
+
Object.assign(acc.light, part.light);
|
|
3605
|
+
if (part.dark) acc.dark = Object.assign(acc.dark ?? {}, part.dark);
|
|
3606
|
+
if (part.lightContrast) acc.lightContrast = Object.assign(acc.lightContrast ?? {}, part.lightContrast);
|
|
3607
|
+
if (part.darkContrast) acc.darkContrast = Object.assign(acc.darkContrast ?? {}, part.darkContrast);
|
|
3608
|
+
}, () => ({ light: {} }));
|
|
3609
|
+
};
|
|
1493
3610
|
return {
|
|
3611
|
+
list() {
|
|
3612
|
+
return Object.keys(themes);
|
|
3613
|
+
},
|
|
3614
|
+
get primary() {
|
|
3615
|
+
return paletteOptions?.primary;
|
|
3616
|
+
},
|
|
3617
|
+
theme(name) {
|
|
3618
|
+
return themes[name];
|
|
3619
|
+
},
|
|
3620
|
+
themes() {
|
|
3621
|
+
return { ...themes };
|
|
3622
|
+
},
|
|
3623
|
+
export(override) {
|
|
3624
|
+
const themesExport = {};
|
|
3625
|
+
for (const [name, theme] of Object.entries(themes)) themesExport[name] = theme.export(override);
|
|
3626
|
+
const out = {
|
|
3627
|
+
kind: "palette",
|
|
3628
|
+
version: GLAZE_EXPORT_VERSION,
|
|
3629
|
+
themes: themesExport
|
|
3630
|
+
};
|
|
3631
|
+
if (paletteOptions?.primary !== void 0) out.primary = paletteOptions.primary;
|
|
3632
|
+
return out;
|
|
3633
|
+
},
|
|
1494
3634
|
tokens(options) {
|
|
1495
|
-
const
|
|
1496
|
-
|
|
3635
|
+
const format = options?.format ?? "oklch";
|
|
3636
|
+
assertNativeFormat(format, "tokens");
|
|
1497
3637
|
const modes = resolveModes(options?.modes);
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
const prefix = resolvePrefix(options, themeName, true);
|
|
1503
|
-
const tokens = buildFlatTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, modes, options?.format);
|
|
1504
|
-
for (const variant of Object.keys(tokens)) {
|
|
1505
|
-
if (!allTokens[variant]) allTokens[variant] = {};
|
|
1506
|
-
Object.assign(allTokens[variant], tokens[variant]);
|
|
1507
|
-
}
|
|
1508
|
-
if (themeName === effectivePrimary) {
|
|
1509
|
-
const unprefixed = buildFlatTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", modes, options?.format);
|
|
1510
|
-
for (const variant of Object.keys(unprefixed)) Object.assign(allTokens[variant], unprefixed[variant]);
|
|
3638
|
+
return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel) => buildFlatTokenMap(filtered, prefix, modes, format, pastel), (acc, part) => {
|
|
3639
|
+
for (const variant of Object.keys(part)) {
|
|
3640
|
+
if (!acc[variant]) acc[variant] = {};
|
|
3641
|
+
Object.assign(acc[variant], part[variant]);
|
|
1511
3642
|
}
|
|
1512
|
-
}
|
|
1513
|
-
return allTokens;
|
|
3643
|
+
}, () => ({}));
|
|
1514
3644
|
},
|
|
1515
3645
|
tasty(options) {
|
|
1516
|
-
const
|
|
1517
|
-
if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
|
|
3646
|
+
const cfg = getConfig();
|
|
1518
3647
|
const states = {
|
|
1519
|
-
dark: options?.states?.dark ??
|
|
1520
|
-
highContrast: options?.states?.highContrast ??
|
|
3648
|
+
dark: options?.states?.dark ?? cfg.states.dark,
|
|
3649
|
+
highContrast: options?.states?.highContrast ?? cfg.states.highContrast
|
|
1521
3650
|
};
|
|
1522
3651
|
const modes = resolveModes(options?.modes);
|
|
1523
|
-
const
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
const prefix = resolvePrefix(options, themeName, true);
|
|
1528
|
-
const tokens = buildTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, states, modes, options?.format);
|
|
1529
|
-
Object.assign(allTokens, tokens);
|
|
1530
|
-
if (themeName === effectivePrimary) {
|
|
1531
|
-
const unprefixed = buildTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", states, modes, options?.format);
|
|
1532
|
-
Object.assign(allTokens, unprefixed);
|
|
1533
|
-
}
|
|
1534
|
-
}
|
|
1535
|
-
return allTokens;
|
|
3652
|
+
const format = options?.format ?? "oklch";
|
|
3653
|
+
return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, themeName, theme) => {
|
|
3654
|
+
return buildTokenMap(filtered, prefix, states, modes, format, pastel, channelCtxForTheme(theme, themeName, prefix, resolvePrefix(options, themeName, true), options?.splitHue, format, modes, filtered));
|
|
3655
|
+
}, (acc, part) => Object.assign(acc, part), () => ({}));
|
|
1536
3656
|
},
|
|
1537
3657
|
json(options) {
|
|
3658
|
+
const format = options?.format ?? "oklch";
|
|
3659
|
+
assertNativeFormat(format, "json");
|
|
1538
3660
|
const modes = resolveModes(options?.modes);
|
|
1539
3661
|
const result = {};
|
|
1540
|
-
for (const [themeName, theme] of Object.entries(themes)) result[themeName] = buildJsonMap(theme.resolve(), modes,
|
|
3662
|
+
for (const [themeName, theme] of Object.entries(themes)) result[themeName] = buildJsonMap(theme.resolve(), modes, format, theme.getConfig().pastel);
|
|
1541
3663
|
return result;
|
|
1542
3664
|
},
|
|
1543
3665
|
css(options) {
|
|
1544
|
-
const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
|
|
1545
|
-
if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
|
|
1546
3666
|
const suffix = options?.suffix ?? "-color";
|
|
1547
|
-
const format = options?.format ?? "
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
};
|
|
1554
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1555
|
-
for (const [themeName, theme] of Object.entries(themes)) {
|
|
1556
|
-
const resolved = theme.resolve();
|
|
1557
|
-
const prefix = resolvePrefix(options, themeName, true);
|
|
1558
|
-
const css = buildCssMap(filterCollisions(resolved, prefix, seen, themeName), prefix, suffix, format);
|
|
3667
|
+
const format = options?.format ?? "oklch";
|
|
3668
|
+
assertNativeFormat(format, "css");
|
|
3669
|
+
const modes = resolveModes();
|
|
3670
|
+
const lines = buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, themeName, theme) => {
|
|
3671
|
+
return buildCssMap(filtered, prefix, suffix, format, pastel, channelCtxForTheme(theme, themeName, prefix, resolvePrefix(options, themeName, true), options?.splitHue, format, modes, filtered));
|
|
3672
|
+
}, (acc, part) => {
|
|
1559
3673
|
for (const key of [
|
|
1560
3674
|
"light",
|
|
1561
3675
|
"dark",
|
|
1562
3676
|
"lightContrast",
|
|
1563
3677
|
"darkContrast"
|
|
1564
|
-
]) if (
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
"darkContrast"
|
|
1572
|
-
]) if (unprefixed[key]) allLines[key].push(unprefixed[key]);
|
|
1573
|
-
}
|
|
1574
|
-
}
|
|
3678
|
+
]) if (part[key]) acc[key].push(part[key]);
|
|
3679
|
+
}, () => ({
|
|
3680
|
+
light: [],
|
|
3681
|
+
dark: [],
|
|
3682
|
+
lightContrast: [],
|
|
3683
|
+
darkContrast: []
|
|
3684
|
+
}));
|
|
1575
3685
|
return {
|
|
1576
|
-
light:
|
|
1577
|
-
dark:
|
|
1578
|
-
lightContrast:
|
|
1579
|
-
darkContrast:
|
|
3686
|
+
light: lines.light.join("\n"),
|
|
3687
|
+
dark: lines.dark.join("\n"),
|
|
3688
|
+
lightContrast: lines.lightContrast.join("\n"),
|
|
3689
|
+
darkContrast: lines.darkContrast.join("\n")
|
|
1580
3690
|
};
|
|
1581
|
-
}
|
|
1582
|
-
};
|
|
1583
|
-
}
|
|
1584
|
-
function createColorToken(input) {
|
|
1585
|
-
const defs = { __color__: {
|
|
1586
|
-
lightness: input.lightness,
|
|
1587
|
-
saturation: input.saturationFactor,
|
|
1588
|
-
mode: input.mode
|
|
1589
|
-
} };
|
|
1590
|
-
return {
|
|
1591
|
-
resolve() {
|
|
1592
|
-
return resolveAllColors(input.hue, input.saturation, defs).get("__color__");
|
|
1593
3691
|
},
|
|
1594
|
-
|
|
1595
|
-
return
|
|
1596
|
-
dark: options?.states?.dark ?? globalConfig.states.dark,
|
|
1597
|
-
highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
|
|
1598
|
-
}, resolveModes(options?.modes), options?.format)["#__color__"];
|
|
3692
|
+
dtcg(options) {
|
|
3693
|
+
return buildDtcgResult(options);
|
|
1599
3694
|
},
|
|
1600
|
-
|
|
1601
|
-
return
|
|
1602
|
-
dark: options?.states?.dark ?? globalConfig.states.dark,
|
|
1603
|
-
highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
|
|
1604
|
-
}, resolveModes(options?.modes), options?.format)["#__color__"];
|
|
3695
|
+
dtcgResolver(options) {
|
|
3696
|
+
return buildDtcgResolver(buildDtcgResult(options), options);
|
|
1605
3697
|
},
|
|
1606
|
-
|
|
1607
|
-
|
|
3698
|
+
tailwind(options) {
|
|
3699
|
+
const modes = resolveModes(options?.modes);
|
|
3700
|
+
const cssPrefix = options?.namespace ?? "color-";
|
|
3701
|
+
const format = options?.format ?? "oklch";
|
|
3702
|
+
assertNativeFormat(format, "tailwind");
|
|
3703
|
+
const darkSelector = options?.darkSelector ?? ".dark";
|
|
3704
|
+
const highContrastSelector = options?.highContrastSelector ?? ".high-contrast";
|
|
3705
|
+
return emitTailwindCss(buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, _themeName, _theme) => buildTailwindLines(filtered, prefix, cssPrefix, format, pastel), (acc, part) => {
|
|
3706
|
+
for (const variant of [
|
|
3707
|
+
"light",
|
|
3708
|
+
"dark",
|
|
3709
|
+
"lightContrast",
|
|
3710
|
+
"darkContrast"
|
|
3711
|
+
]) acc[variant].push(...part[variant]);
|
|
3712
|
+
}, () => ({
|
|
3713
|
+
light: [],
|
|
3714
|
+
dark: [],
|
|
3715
|
+
lightContrast: [],
|
|
3716
|
+
darkContrast: []
|
|
3717
|
+
})), modes, darkSelector, highContrastSelector);
|
|
1608
3718
|
}
|
|
1609
3719
|
};
|
|
1610
3720
|
}
|
|
3721
|
+
|
|
3722
|
+
//#endregion
|
|
3723
|
+
//#region src/glaze.ts
|
|
3724
|
+
/**
|
|
3725
|
+
* Glaze — OKHST color theme generator.
|
|
3726
|
+
*
|
|
3727
|
+
* Public API entry. Wires `glaze()` and its attached static methods to
|
|
3728
|
+
* the focused modules in this folder:
|
|
3729
|
+
* - `theme.ts` — single-theme factory
|
|
3730
|
+
* - `palette.ts` — multi-theme composition
|
|
3731
|
+
* - `color-token.ts` — standalone single-color tokens (`glaze.color`)
|
|
3732
|
+
* - `shadow.ts` — standalone shadow factory (`glaze.shadow`)
|
|
3733
|
+
* - `formatters.ts` — variant → string (`glaze.format`)
|
|
3734
|
+
* - `config.ts` — global config singleton
|
|
3735
|
+
* - `serialize.ts` — authoring export type guards / version checks
|
|
3736
|
+
*/
|
|
1611
3737
|
/**
|
|
1612
3738
|
* Create a single-hue glaze theme.
|
|
1613
3739
|
*
|
|
3740
|
+
* An optional `config` override can be supplied to customize the resolve
|
|
3741
|
+
* behavior for this theme (tone windows, etc.). The
|
|
3742
|
+
* override is **merged over the live global config at resolve time** —
|
|
3743
|
+
* the theme still reacts to later `configure()` calls for fields it
|
|
3744
|
+
* didn't override.
|
|
3745
|
+
*
|
|
1614
3746
|
* @example
|
|
1615
3747
|
* ```ts
|
|
1616
|
-
* const primary = glaze({ hue: 280, saturation: 80 });
|
|
1617
|
-
* // or shorthand:
|
|
1618
3748
|
* const primary = glaze(280, 80);
|
|
3749
|
+
* // or shorthand:
|
|
3750
|
+
* const primary = glaze({ hue: 280, saturation: 80 });
|
|
3751
|
+
* // with config override:
|
|
3752
|
+
* const raw = glaze(280, 80, { lightTone: false });
|
|
1619
3753
|
* ```
|
|
1620
3754
|
*/
|
|
1621
|
-
function glaze(hueOrOptions, saturation) {
|
|
1622
|
-
if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100);
|
|
1623
|
-
return createTheme(hueOrOptions.hue, hueOrOptions.saturation);
|
|
3755
|
+
function glaze(hueOrOptions, saturation, config) {
|
|
3756
|
+
if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100, void 0, config);
|
|
3757
|
+
return createTheme(hueOrOptions.hue, hueOrOptions.saturation, void 0, config);
|
|
1624
3758
|
}
|
|
1625
|
-
/**
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
glaze.configure = function configure(config) {
|
|
1629
|
-
globalConfig = {
|
|
1630
|
-
lightLightness: config.lightLightness ?? globalConfig.lightLightness,
|
|
1631
|
-
darkLightness: config.darkLightness ?? globalConfig.darkLightness,
|
|
1632
|
-
darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
|
|
1633
|
-
darkCurve: config.darkCurve ?? globalConfig.darkCurve,
|
|
1634
|
-
states: {
|
|
1635
|
-
dark: config.states?.dark ?? globalConfig.states.dark,
|
|
1636
|
-
highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
|
|
1637
|
-
},
|
|
1638
|
-
modes: {
|
|
1639
|
-
dark: config.modes?.dark ?? globalConfig.modes.dark,
|
|
1640
|
-
highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
|
|
1641
|
-
},
|
|
1642
|
-
shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning
|
|
1643
|
-
};
|
|
3759
|
+
/** Configure global glaze settings. */
|
|
3760
|
+
glaze.configure = function configure$1(config) {
|
|
3761
|
+
configure(config);
|
|
1644
3762
|
};
|
|
1645
|
-
/**
|
|
1646
|
-
* Compose multiple themes into a palette.
|
|
1647
|
-
*/
|
|
3763
|
+
/** Compose multiple themes into a palette. */
|
|
1648
3764
|
glaze.palette = function palette(themes, options) {
|
|
1649
3765
|
return createPalette(themes, options);
|
|
1650
3766
|
};
|
|
1651
3767
|
/**
|
|
1652
|
-
* Create a theme from a serialized export.
|
|
3768
|
+
* Create a theme from a serialized `theme.export()` snapshot.
|
|
3769
|
+
* Prefer this over the legacy `glaze.from` alias.
|
|
1653
3770
|
*/
|
|
1654
|
-
glaze.
|
|
1655
|
-
return
|
|
3771
|
+
glaze.themeFrom = function themeFrom(data) {
|
|
3772
|
+
return createThemeFromExport(data);
|
|
1656
3773
|
};
|
|
3774
|
+
/** Compat alias for `glaze.themeFrom`. */
|
|
3775
|
+
glaze.from = glaze.themeFrom;
|
|
1657
3776
|
/**
|
|
1658
3777
|
* Create a standalone single-color token.
|
|
3778
|
+
*
|
|
3779
|
+
* **arg1 — the color** (four accepted shapes, discriminated by structure):
|
|
3780
|
+
*
|
|
3781
|
+
* | Shape | Example | Notes |
|
|
3782
|
+
* |---|---|---|
|
|
3783
|
+
* | Bare string | `'#26fcb2'`, `'rgb(38 252 178)'` | Hex or CSS color function (incl. `okhst()`) |
|
|
3784
|
+
* | Value object | `{ h: 152, s: 0.95, l: 0.74 }` | OKHSL, OKHST (`{h,s,t}`), `{r,g,b}`, `{l,c,h}` |
|
|
3785
|
+
* | `{ from, ...overrides }` | `{ from: '#fff', base: bg, contrast: 'AA' }` | Value + color overrides |
|
|
3786
|
+
* | Structured | `{ hue: 152, saturation: 95, tone: 74 }` | Full theme-style token |
|
|
3787
|
+
*
|
|
3788
|
+
* **arg2 — config override** (optional, all shapes):
|
|
3789
|
+
* Overrides the resolve-relevant global config fields for this token.
|
|
3790
|
+
* Fields that are omitted fall through to the live global config at
|
|
3791
|
+
* resolve time. Pass `false` for a tone window to disable clamping
|
|
3792
|
+
* entirely. `pastel` is instance-only (not set via `configure()`).
|
|
3793
|
+
*
|
|
3794
|
+
* ```ts
|
|
3795
|
+
* // Bare string — no overrides
|
|
3796
|
+
* glaze.color('#26fcb2')
|
|
3797
|
+
*
|
|
3798
|
+
* // From form — value + color overrides
|
|
3799
|
+
* glaze.color({ from: '#fff', base: bg, contrast: 'AA' })
|
|
3800
|
+
*
|
|
3801
|
+
* // Structured form — full theme-style token
|
|
3802
|
+
* glaze.color({ hue: 152, saturation: 95, tone: 74 })
|
|
3803
|
+
*
|
|
3804
|
+
* // Config override on any form
|
|
3805
|
+
* glaze.color('#26fcb2', { darkTone: false, autoFlip: false })
|
|
3806
|
+
* glaze.color({ from: '#fff', base: bg })
|
|
3807
|
+
* ```
|
|
3808
|
+
*
|
|
3809
|
+
* Defaults: every form defaults to `mode: 'auto'`. Value-shorthand forms
|
|
3810
|
+
* (bare strings and value objects) preserve light tone exactly
|
|
3811
|
+
* (`lightTone: false` locally). Structured form falls through to the live
|
|
3812
|
+
* global tone windows for omitted fields.
|
|
3813
|
+
*
|
|
3814
|
+
* Relative `tone: '+N'` and `contrast` anchor to the literal seed by
|
|
3815
|
+
* default; when `base` is set they anchor to the base's resolved variant
|
|
3816
|
+
* per scheme. Relative `hue: '+N'` always anchors to the seed, not the base.
|
|
1659
3817
|
*/
|
|
1660
|
-
glaze.color = function color(input) {
|
|
1661
|
-
return
|
|
3818
|
+
glaze.color = function color(input, config) {
|
|
3819
|
+
if (typeof input === "string") return createColorTokenFromValue(input, void 0, config);
|
|
3820
|
+
const obj = input;
|
|
3821
|
+
if ("from" in obj) {
|
|
3822
|
+
const { from, ...overrides } = input;
|
|
3823
|
+
return createColorTokenFromValue(from, overrides, config);
|
|
3824
|
+
}
|
|
3825
|
+
if ("hue" in obj) return createColorToken(input, config);
|
|
3826
|
+
return createColorTokenFromValue(input, void 0, config);
|
|
1662
3827
|
};
|
|
1663
3828
|
/**
|
|
1664
3829
|
* Compute a shadow color from a bg/fg pair and intensity.
|
|
3830
|
+
*
|
|
3831
|
+
* Both `bg` and `fg` accept any `GlazeColorValue` form: hex (`#rgb` /
|
|
3832
|
+
* `#rrggbb` / `#rrggbbaa`), `rgb()` / `hsl()` / `okhsl()` / `oklch()`
|
|
3833
|
+
* strings, or `{ r, g, b }` / `{ h, s, l }` / `{ l, c, h }` objects.
|
|
1665
3834
|
*/
|
|
1666
3835
|
glaze.shadow = function shadow(input) {
|
|
1667
|
-
const bg =
|
|
1668
|
-
const fg = input.fg ?
|
|
1669
|
-
const
|
|
3836
|
+
const bg = extractOkhslFromValue(input.bg);
|
|
3837
|
+
const fg = input.fg ? extractOkhslFromValue(input.fg) : void 0;
|
|
3838
|
+
const cfg = getConfig();
|
|
3839
|
+
const tuning = resolveShadowTuning(input.tuning, cfg.shadowTuning);
|
|
1670
3840
|
const result = computeShadow({
|
|
1671
3841
|
...bg,
|
|
1672
3842
|
alpha: 1
|
|
@@ -1674,32 +3844,22 @@ glaze.shadow = function shadow(input) {
|
|
|
1674
3844
|
...fg,
|
|
1675
3845
|
alpha: 1
|
|
1676
3846
|
} : void 0, input.intensity, tuning);
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
result.
|
|
1681
|
-
}
|
|
1682
|
-
return
|
|
3847
|
+
const { h, s, t } = okhslToOkhst({
|
|
3848
|
+
h: result.h,
|
|
3849
|
+
s: result.s,
|
|
3850
|
+
l: result.l
|
|
3851
|
+
});
|
|
3852
|
+
return {
|
|
3853
|
+
h,
|
|
3854
|
+
s,
|
|
3855
|
+
t,
|
|
3856
|
+
alpha: result.alpha
|
|
3857
|
+
};
|
|
1683
3858
|
};
|
|
1684
|
-
/**
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
glaze.format = function format(variant, colorFormat) {
|
|
1688
|
-
return formatVariant(variant, colorFormat);
|
|
3859
|
+
/** Format a resolved color variant as a CSS string. */
|
|
3860
|
+
glaze.format = function format(variant, colorFormat, pastel) {
|
|
3861
|
+
return formatVariant(variant, colorFormat, pastel);
|
|
1689
3862
|
};
|
|
1690
|
-
function parseOkhslInput(input) {
|
|
1691
|
-
if (typeof input === "string") {
|
|
1692
|
-
const rgb = parseHex(input);
|
|
1693
|
-
if (!rgb) throw new Error(`glaze: invalid hex color "${input}".`);
|
|
1694
|
-
const [h, s, l] = srgbToOkhsl(rgb);
|
|
1695
|
-
return {
|
|
1696
|
-
h,
|
|
1697
|
-
s,
|
|
1698
|
-
l
|
|
1699
|
-
};
|
|
1700
|
-
}
|
|
1701
|
-
return input;
|
|
1702
|
-
}
|
|
1703
3863
|
/**
|
|
1704
3864
|
* Create a theme from a hex color string.
|
|
1705
3865
|
* Extracts hue and saturation from the color.
|
|
@@ -1723,31 +3883,46 @@ glaze.fromRgb = function fromRgb(r, g, b) {
|
|
|
1723
3883
|
return createTheme(h, s * 100);
|
|
1724
3884
|
};
|
|
1725
3885
|
/**
|
|
1726
|
-
*
|
|
3886
|
+
* Rehydrate a `glaze.color()` token from a `.export()` snapshot.
|
|
3887
|
+
*
|
|
3888
|
+
* The snapshot is a plain JSON-safe object containing the original
|
|
3889
|
+
* input value, overrides (with any `base` token recursively serialized),
|
|
3890
|
+
* and the effective config freeze from export time. The reconstructed
|
|
3891
|
+
* token pins that freeze as its local override.
|
|
3892
|
+
*
|
|
3893
|
+
* @example
|
|
3894
|
+
* ```ts
|
|
3895
|
+
* const text = glaze.color({ from: '#1a1a1a', contrast: 'AA' });
|
|
3896
|
+
* const data = text.export(); // JSON-safe
|
|
3897
|
+
* localStorage.setItem('text', JSON.stringify(data));
|
|
3898
|
+
* // ...later...
|
|
3899
|
+
* const restored = glaze.colorFrom(JSON.parse(localStorage.getItem('text')!));
|
|
3900
|
+
* ```
|
|
1727
3901
|
*/
|
|
1728
|
-
glaze.
|
|
1729
|
-
return
|
|
3902
|
+
glaze.colorFrom = function colorFrom(data) {
|
|
3903
|
+
return colorFromExport(data);
|
|
1730
3904
|
};
|
|
1731
3905
|
/**
|
|
1732
|
-
*
|
|
3906
|
+
* Rehydrate a palette from a `palette.export()` snapshot.
|
|
1733
3907
|
*/
|
|
1734
|
-
glaze.
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
3908
|
+
glaze.paletteFrom = function paletteFrom(data) {
|
|
3909
|
+
return createPaletteFromExport(data);
|
|
3910
|
+
};
|
|
3911
|
+
/** Type guard for theme authoring snapshots. */
|
|
3912
|
+
glaze.isThemeExport = isThemeExport;
|
|
3913
|
+
/** Type guard for color-token authoring snapshots. */
|
|
3914
|
+
glaze.isColorTokenExport = isColorTokenExport;
|
|
3915
|
+
/** Type guard for palette authoring snapshots. */
|
|
3916
|
+
glaze.isPaletteExport = isPaletteExport;
|
|
3917
|
+
/** Get the current global configuration (for testing/debugging). */
|
|
3918
|
+
glaze.getConfig = function getConfig() {
|
|
3919
|
+
return snapshotConfig();
|
|
3920
|
+
};
|
|
3921
|
+
/** Reset global configuration to defaults. */
|
|
3922
|
+
glaze.resetConfig = function resetConfig$1() {
|
|
3923
|
+
resetConfig();
|
|
1749
3924
|
};
|
|
1750
3925
|
|
|
1751
3926
|
//#endregion
|
|
1752
|
-
export { contrastRatioFromLuminance,
|
|
3927
|
+
export { APCA_HC_ENHANCEMENT, APCA_MAX_LC, APCA_PRESETS, GLAZE_EXPORT_VERSION, REF_EPS, apcaContrast, assertAllPastel, assertNativeFormat, contrastRatioFromLuminance, cuspLightness, findToneForContrast, findValueForMixContrast, formatHsl, formatOkhsl, formatOkhst, formatOklch, formatRgb, fromTone, gamutClampedLuminance, glaze, hslToSrgb, inferRoleFromName, isColorTokenExport, isPaletteExport, isThemeExport, normalizeRole, okhslToLinearSrgb, okhslToOkhst, okhslToOklab, okhslToOklch, okhslToSrgb, okhstToOkhsl, oklabToOkhsl, oppositeRole, parseHex, parseHexAlpha, relativeLuminanceFromLinearRgb, resolveApcaTarget, resolveContrastForMode, resolveMinContrast, roleToPolarity, srgbToHex, srgbToOkhsl, toTone, toneFromY, variantToOkhsl, yFromTone };
|
|
1753
3928
|
//# sourceMappingURL=index.mjs.map
|