Debian Codegraph @

node/colorjs.io/dist/color.cjs

raw
1 'use strict';
2
3 Object.defineProperty(exports, '__esModule', { value: true });
4
5 /** @import { Matrix3x3, Vector3 } from "./types.js" */
6
7 /**
8 * A is m x n. B is n x p. product is m x p.
9 *
10 * Array arguments are treated like vectors:
11 * - A becomes 1 x n
12 * - B becomes n x 1
13 *
14 * Returns Matrix m x p or equivalent array or number
15 *
16 * @overload
17 * @param {number[]} A Vector 1 x n
18 * @param {number[]} B Vector n x 1
19 * @returns {number} Scalar number
20 *
21 * @overload
22 * @param {number[][]} A Matrix m x n
23 * @param {number[]} B Vector n x 1
24 * @returns {number[]} Array with length m
25 *
26 * @overload
27 * @param {number[]} A Vector 1 x n
28 * @param {number[][]} B Matrix n x p
29 * @returns {number[]} Array with length p
30 *
31 * @overload
32 * @param {number[][]} A Matrix m x n
33 * @param {number[][]} B Matrix n x p
34 * @returns {number[][]} Matrix m x p
35 *
36 * @param {number[] | number[][]} A Matrix m x n or a vector
37 * @param {number[] | number[][]} B Matrix n x p or a vector
38 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
39 */
40 function multiplyMatrices (A, B) {
41 let m = A.length;
42 /** @type {number[][]} */
43 let AM;
44 /** @type {number[][]} */
45 let BM;
46 let aVec = false;
47 let bVec = false;
48
49 if (!Array.isArray(A[0])) {
50 // A is vector, convert to [[a, b, c, ...]]
51 AM = [/** @type {number[]} */ (A)];
52 m = AM.length;
53 aVec = true;
54 }
55 else {
56 AM = /** @type {number[][]} */ (A);
57 }
58
59 if (!Array.isArray(B[0])) {
60 // B is vector, convert to [[a], [b], [c], ...]]
61 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
62 bVec = true;
63 }
64 else {
65 BM = /** @type {number[][]} */ (B);
66 }
67
68 let p = BM[0].length;
69 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
70 /** @type {number[] | number[][]} */
71 let product = AM.map(row =>
72 BM_cols.map(col => {
73 let ret = 0;
74
75 if (!Array.isArray(row)) {
76 for (let c of col) {
77 ret += row * c;
78 }
79
80 return ret;
81 }
82
83 for (let i = 0; i < row.length; i++) {
84 ret += row[i] * (col[i] || 0);
85 }
86
87 return ret;
88 }));
89
90 if (m === 1 && aVec) {
91 product = product[0]; // Avoid [[a, b, c, ...]]
92 }
93 if (p === 1 && bVec) {
94 if (m === 1 && aVec) {
95 return product[0]; // Avoid [[a]], return a number
96 }
97 else {
98 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
99 }
100 }
101
102 return product;
103 }
104
105 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
106 //
107 // The MIT License (MIT)
108 // Copyright (c) 2024 Matt DesLauriers
109
110 // Permission is hereby granted, free of charge, to any person obtaining a copy
111 // of this software and associated documentation files (the "Software"), to deal
112 // in the Software without restriction, including without limitation the rights
113 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
114 // copies of the Software, and to permit persons to whom the Software is
115 // furnished to do so, subject to the following conditions:
116
117 // The above copyright notice and this permission notice shall be included in all
118 // copies or substantial portions of the Software.
119
120 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
121 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
122 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
123 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
124 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
125 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
126 // OR OTHER DEALINGS IN THE SOFTWARE.
127
128 /**
129 * Returns the dot product of two vectors each with a length of 3.
130 *
131 * @param {Vector3} a
132 * @param {Vector3} b
133 * @returns {number}
134 */
135 function dot3 (a, b) {
136 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
137 }
138
139 /**
140 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
141 * vector to transform in place.
142 *
143 * @param {Vector3} input
144 * @param {Matrix3x3} matrix
145 * @param {Vector3} [out]
146 * @returns {Vector3}
147 */
148 function multiply_v3_m3x3 (input, matrix, out = [0, 0, 0]) {
149 const x = dot3(input, matrix[0]);
150 const y = dot3(input, matrix[1]);
151 const z = dot3(input, matrix[2]);
152 out[0] = x;
153 out[1] = y;
154 out[2] = z;
155 return out;
156 }
157
158 /**
159 * Various utility functions
160 */
161
162
163 /**
164 * Check if a value is a string (including a String object)
165 * @param {any} str - Value to check
166 * @returns {str is string}
167 */
168 function isString (str) {
169 return type(str) === "string";
170 }
171
172 /**
173 * Determine the internal JavaScript [[Class]] of an object.
174 * @param {any} o - Value to check
175 * @returns {string}
176 */
177 function type (o) {
178 let str = Object.prototype.toString.call(o);
179
180 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
181 }
182
183 /**
184 * @param {number} n
185 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
186 * @returns {string}
187 */
188 function serializeNumber (n, { precision = 16, unit }) {
189 if (isNone(n)) {
190 return "none";
191 }
192
193 n = +toPrecision(n, precision);
194
195 return n + (unit ?? "");
196 }
197
198 /**
199 * Check if a value corresponds to a none argument
200 * @param {any} n - Value to check
201 * @returns {n is null}
202 */
203 function isNone (n) {
204 return n === null;
205 }
206
207 /**
208 * Replace none values with 0
209 * @param {number | null} n
210 * @returns {number}
211 */
212 function skipNone (n) {
213 return isNone(n) ? 0 : n;
214 }
215
216 /**
217 * Round a number to a certain number of significant digits
218 * @param {number} n - The number to round
219 * @param {number} precision - Number of significant digits
220 */
221 function toPrecision (n, precision) {
222 if (n === 0) {
223 return 0;
224 }
225 let integer = ~~n;
226 let digits = 0;
227 if (integer && precision) {
228 digits = ~~Math.log10(Math.abs(integer)) + 1;
229 }
230 const multiplier = 10.0 ** (precision - digits);
231 return Math.floor(n * multiplier + 0.5) / multiplier;
232 }
233
234 /**
235 * Interpolate between two values, either of which may be a `none` value.
236 * A `none` endpoint is treated as having the other endpoint's value;
237 * if both are `none`, the result is `none` as well.
238 * @param {number | null} start
239 * @param {number | null} end
240 * @param {number} p
241 * @returns {number | null}
242 */
243 function interpolate (start, end, p) {
244 if (isNone(start) || isNaN(start)) {
245 return end;
246 }
247
248 if (isNone(end) || isNaN(end)) {
249 return start;
250 }
251
252 return start + (end - start) * p;
253 }
254
255 /**
256 * @param {number} start
257 * @param {number} end
258 * @param {number} value
259 */
260 function interpolateInv (start, end, value) {
261 return (value - start) / (end - start);
262 }
263
264 /**
265 * @param {[number, number]} from
266 * @param {[number, number]} to
267 * @param {number} value
268 */
269 function mapRange (from, to, value) {
270 if (
271 !from ||
272 !to ||
273 from === to ||
274 (from[0] === to[0] && from[1] === to[1]) ||
275 isNaN(value) ||
276 value === null
277 ) {
278 // Ranges missing or the same
279 return value;
280 }
281
282 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
283 }
284
285 /**
286 * Clamp value between the minimum and maximum
287 * @param {number} min minimum value to return
288 * @param {number} val the value to return if it is between min and max
289 * @param {number} max maximum value to return
290 */
291 function clamp (min, val, max) {
292 return Math.max(Math.min(max, val), min);
293 }
294
295 /**
296 * Copy sign of one value to another.
297 * @param {number} to - Number to copy sign to
298 * @param {number} from - Number to copy sign from
299 */
300 function copySign (to, from) {
301 return Math.sign(to) === Math.sign(from) ? to : -to;
302 }
303
304 /**
305 * Perform pow on a signed number and copy sign to result
306 * @param {number} base The base number
307 * @param {number} exp The exponent
308 */
309 function spow (base, exp) {
310 return copySign(Math.abs(base) ** exp, base);
311 }
312
313 /**
314 * Perform a divide, but return zero if the denominator is zero
315 * @param {number} n The numerator
316 * @param {number} d The denominator
317 */
318 function zdiv (n, d) {
319 return d === 0 ? 0 : n / d;
320 }
321
322 /**
323 * Perform a bisect on a sorted list and locate the insertion point for
324 * a value in arr to maintain sorted order.
325 * @param {number[]} arr - array of sorted numbers
326 * @param {number} value - value to find insertion point for
327 * @param {number} lo - used to specify a the low end of a subset of the list
328 * @param {number} hi - used to specify a the high end of a subset of the list
329 */
330 function bisectLeft (arr, value, lo = 0, hi = arr.length) {
331 while (lo < hi) {
332 const mid = (lo + hi) >> 1;
333 if (arr[mid] < value) {
334 lo = mid + 1;
335 }
336 else {
337 hi = mid;
338 }
339 }
340 return lo;
341 }
342
343 /**
344 * Determines whether an argument is an instance of a constructor, including subclasses.
345 * This is done by first just checking `instanceof`,
346 * and then comparing the string names of the constructors if that fails.
347 * @param {any} arg
348 * @param {C} constructor
349 * @template {new (...args: any) => any} C
350 * @returns {arg is InstanceType<C>}
351 */
352 function isInstance (arg, constructor) {
353 if (arg instanceof constructor) {
354 return true;
355 }
356
357 const targetName = constructor.name;
358
359 while (arg) {
360 const proto = Object.getPrototypeOf(arg);
361 const constructorName = proto?.constructor?.name;
362 if (constructorName === targetName) {
363 return true;
364 }
365 if (!constructorName || constructorName === "Object") {
366 return false;
367 }
368 arg = proto;
369 }
370
371 return false;
372 }
373
374 /**
375 * Generate a matrix of size NxN with the given diagonal values of length N.
376 *
377 * @param {number[]} values
378 * @returns {number[][]}
379 */
380 function diag (values) {
381 const n = values.length;
382 const matrix = [];
383 for (let i = 0; i < n; i++) {
384 matrix[i] = [];
385 for (let j = 0; j < n; j++) {
386 matrix[i][j] = i === j ? values[i] : 0;
387 }
388 }
389 return matrix;
390 }
391
392 /**
393 * Calculate the LU decomposition of an NxN matrix.
394 *
395 * P is returned as PA = UL or A = P'UL which follows Matlab and Octave opposed to Scipy which returns P as
396 * A = PUL or P'A = UL. For matrix inverse, we need P such that PA = UL and it is faster not having to invert
397 * P, even if we can invert it fairly fast as it is just a shuffled identity matrix.
398 *
399 * P is returned as a permutation matrix unless pIndices is true, in which case P would be returned as
400 * a vector containing the indexes such that A[P,:] = L*U.
401 *
402 * Reference:
403 * - https://www.statlect.com/matrix-algebra/Gaussian-elimination
404 * - https://www.sciencedirect.com/topics/mathematics/partial-pivoting
405 *
406 * @overload
407 * @param {number[][]} matrix
408 * @param {{ pIndices?: false | undefined }} [options]
409 * @returns {[number[][], number[][], number[][]]}
410 */
411 /**
412 * @overload
413 * @param {number[][]} matrix
414 * @param {{ pIndices?: true }} [options]
415 * @returns {[number[], number[][], number[][]]}
416 */
417 /**
418 * @param {number[][]} matrix
419 * @param {{ pIndices?: boolean | undefined }} [options]
420 * @returns {[number[] | number[][], number[][], number[][]]}
421 */
422 function lu (matrix, { pIndices = false } = {}) {
423 let p1, p2, l, u;
424
425 const n = matrix.length;
426
427 // Initialize the triangle matrices along with the permutation matrix.
428 if (pIndices) {
429 p1 = Array.from({ length: n }, (_, index) => index);
430 l = diag(new Array(n).fill(1));
431 }
432 else {
433 p2 = diag(new Array(n).fill(1));
434 l = structuredClone(p2);
435 }
436 u = structuredClone(matrix);
437
438 // Create upper and lower triangle in 'u' and 'l'. 'p' tracks the permutation (relative position of rows)
439 for (let i = 0; i < n - 1; i++) {
440 // Partial pivoting: identify the row with the maximal value in the column
441 let j = i;
442 let maximum = Math.abs(u[i][i]);
443 for (let k = i + 1; k < n; k++) {
444 const a = Math.abs(u[k][i]);
445 if (a > maximum) {
446 j = k;
447 maximum = a;
448 }
449 }
450
451 // Partial pivoting: Swap rows
452 if (j != i) {
453 // Exchange current upper triangle row with row with maximal value at pivot
454 // Update permutation matrix as well
455 [u[i], u[j]] = [u[j], u[i]];
456 if (pIndices) {
457 [p1[i], p1[j]] = [p1[j], p1[i]];
458 }
459 else {
460 [p2[i], p2[j]] = [p2[j], p2[i]];
461 }
462
463 // Only swap columns up to the pivot for the lower triangle,
464 // if on first row, there is nothing to swap
465 if (i) {
466 for (let k = 0; k < i; k++) {
467 [l[i][k], l[j][k]] = [l[j][k], l[i][k]];
468 }
469 }
470 }
471
472 // Zero at pivot point, nothing to do
473 else if (!maximum) {
474 continue;
475 }
476
477 // We have a pivot point, let's zero out everything above and below
478 // the 'l' and 'u' diagonal respectively
479 for (let j = i + 1; j < n; j++) {
480 const scalar = u[j][i] / u[i][i];
481 for (let k = i; k < n; k++) {
482 u[j][k] += -u[i][k] * scalar;
483 l[j][k] += l[i][k] * scalar;
484 }
485 }
486 }
487
488 if (pIndices) {
489 return [p1, l, u];
490 }
491 return [p2, l, u];
492 }
493
494 /**
495 * Forward substitution for solution of ax = b where a and b are matricies.
496 *
497 * @param {number[][]} a
498 * @param {number[][]} b
499 * @param {number} n
500 * @returns {number[][]}
501 */
502 function forwardSubMatrix (a, b, n) {
503 for (let i = 0; i < n; i++) {
504 const v = b[i];
505 for (let j = 0; j < i; j++) {
506 for (let k = 0; k < n; k++) {
507 v[k] -= a[i][j] * b[j][k];
508 }
509 }
510 for (let j = 0; j < n; j++) {
511 v[j] /= a[i][i];
512 }
513 }
514 return b;
515 }
516
517 /**
518 * Back substitution for solution of ax = b where a and b are matricies.
519 *
520 * @param {number[][]} a
521 * @param {number[][]} b
522 * @param {number} n
523 * @returns {number[][]}
524 */
525 function backSubMatrix (a, b, n) {
526 for (let i = n - 1; i > -1; i--) {
527 const v = b[i];
528 for (let j = i + 1; j < n; j++) {
529 for (var k = 0; k < n; k++) {
530 v[k] -= a[i][j] * b[j][k];
531 }
532 }
533 for (let j = 0; j < n; j++) {
534 b[i][j] /= a[i][i];
535 }
536 }
537 return b;
538 }
539
540 /**
541 * Forward substitution for solution of ax = b where a is a matrix and b is a vector.
542 *
543 * @param {number[][]} a
544 * @param {number[]} b
545 * @param {number} n
546 * @returns {number[]}
547 */
548 function forwardSubVector (a, b, n) {
549 for (let i = 0; i < n; i++) {
550 let v = b[i];
551 for (let j = 0; j < i; j++) {
552 v -= a[i][j] * b[j];
553 }
554 b[i] = v / a[i][i];
555 }
556 return b;
557 }
558
559 /**
560 * Back substitution for solution of ax = b where a is a matrix and b is a vector.
561 *
562 * @param {number[][]} a
563 * @param {number[]} b
564 * @param {number} n
565 * @returns {number[]}
566 */
567 function backSubVector (a, b, n) {
568 for (let i = n - 1; i > -1; i--) {
569 let v = b[i];
570 for (let j = i + 1; j < n; j++) {
571 v -= a[i][j] * b[j];
572 }
573 b[i] = v / a[i][i];
574 }
575 return b;
576 }
577
578 /**
579 * Invert a NxN matrix.
580 *
581 * @param {number[][]} matrix
582 * @returns {number[][]}
583 */
584 function inv (matrix) {
585 // Calculate the LU decomposition.
586 const [p, l, u] = lu(matrix);
587 const n = l.length;
588
589 // Floating point math can produce very small, non-zero determinants for singular matrices.
590 // This seems to happen in Numpy as well.
591 // Don't bother calculating sign as we only care about how close to zero we are.
592 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
593 throw new Error("Matrix is singular");
594 }
595
596 // Solve for the identity matrix (will give us inverse)
597 // Permutation matrix is the identity matrix, even if shuffled.
598 return backSubMatrix(u, forwardSubMatrix(l, p, n), n);
599 }
600
601 /**
602 * Solve a NxN matrix representing a system of equations.
603 *
604 * @param {number[][]} matrix
605 * @param {number[]} vector
606 * @returns {number[]}
607 */
608 function solve (matrix, vector) {
609 // Calculate the LU decomposition.
610 const [p, l, u] = lu(matrix, { pIndices: true });
611 const n = l.length;
612
613 // If determinant is zero, we can't solve.
614 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
615 throw new Error("Matrix is singular");
616 }
617
618 return backSubVector(
619 u,
620 forwardSubVector(
621 l,
622 p.map(i => vector[i]),
623 n,
624 ),
625 n,
626 );
627 }
628
629 var util = /*#__PURE__*/Object.freeze({
630 __proto__: null,
631 bisectLeft: bisectLeft,
632 clamp: clamp,
633 copySign: copySign,
634 diag: diag,
635 interpolate: interpolate,
636 interpolateInv: interpolateInv,
637 inv: inv,
638 isInstance: isInstance,
639 isNone: isNone,
640 isString: isString,
641 lu: lu,
642 mapRange: mapRange,
643 multiplyMatrices: multiplyMatrices,
644 multiply_v3_m3x3: multiply_v3_m3x3,
645 serializeNumber: serializeNumber,
646 skipNone: skipNone,
647 solve: solve,
648 spow: spow,
649 toPrecision: toPrecision,
650 type: type,
651 zdiv: zdiv
652 });
653
654 /**
655 * A class for adding deep extensibility to any piece of JS code
656 */
657 class Hooks {
658 add (name, callback, first) {
659 if (typeof arguments[0] != "string") {
660 // Multiple hooks
661 for (var name in arguments[0]) {
662 this.add(name, arguments[0][name], arguments[1]);
663 }
664
665 return;
666 }
667
668 (Array.isArray(name) ? name : [name]).forEach(function (name) {
669 this[name] = this[name] || [];
670
671 if (callback) {
672 this[name][first ? "unshift" : "push"](callback);
673 }
674 }, this);
675 }
676
677 run (name, env) {
678 this[name] = this[name] || [];
679 this[name].forEach(function (callback) {
680 callback.call(env && env.context ? env.context : env, env);
681 });
682 }
683 }
684
685 /**
686 * The instance of {@link Hooks} used throughout Color.js
687 */
688 const hooks = new Hooks();
689
690 // Global defaults one may want to configure
691 var defaults = {
692 gamut_mapping: "css",
693 precision: 5,
694 deltaE: "76", // Default deltaE method
695 verbose: globalThis?.process?.env?.NODE_ENV?.toLowerCase() !== "test",
696 warn: function warn (msg) {
697 if (this.verbose) {
698 globalThis?.console?.warn?.(msg);
699 }
700 },
701 };
702
703 class Type {
704 // Class properties - declared here so that type inference works
705 type;
706 coordMeta;
707 coordRange;
708 /** @type {[number, number]} */
709 range;
710
711 /**
712 * @param {any} type
713 * @param {import("./types.js").CoordMeta} coordMeta
714 */
715 constructor (type, coordMeta) {
716 if (typeof type === "object") {
717 this.coordMeta = type;
718 }
719
720 if (coordMeta) {
721 this.coordMeta = coordMeta;
722 this.coordRange = coordMeta.range ?? coordMeta.refRange;
723 }
724
725 if (typeof type === "string") {
726 let params = type
727 .trim()
728 .match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
729
730 if (!params) {
731 throw new TypeError(`Cannot parse ${type} as a type definition.`);
732 }
733
734 this.type = params.groups.type;
735 let { min, max } = params.groups;
736
737 if (min || max) {
738 this.range = [+min, +max];
739 }
740 }
741 }
742
743 /** @returns {[number, number]} */
744 get computedRange () {
745 if (this.range) {
746 return this.range;
747 }
748 if (this.type === "<percentage>") {
749 return this.percentageRange();
750 }
751 else if (this.type === "<angle>") {
752 return [0, 360];
753 }
754 return null;
755 }
756
757 get unit () {
758 if (this.type === "<percentage>") {
759 return "%";
760 }
761 else if (this.type === "<angle>") {
762 return "deg";
763 }
764
765 return "";
766 }
767
768 /**
769 * Map a number to the internal representation
770 * @param {number} number
771 */
772 resolve (number) {
773 if (this.type === "<angle>") {
774 return number;
775 }
776
777 let fromRange = this.computedRange;
778 let toRange = this.coordRange;
779
780 if (this.type === "<percentage>") {
781 toRange ??= this.percentageRange();
782 }
783
784 return mapRange(fromRange, toRange, number);
785 }
786
787 /**
788 * Serialize a number from the internal representation to a string
789 * @param {number} number
790 * @param {number} [precision]
791 */
792 serialize (number, precision) {
793 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
794
795 let unit = this.unit;
796
797 number = mapRange(this.coordRange, toRange, number);
798 return serializeNumber(number, { unit, precision });
799 }
800
801 toString () {
802 let ret = this.type;
803
804 if (this.range) {
805 let [min = "", max = ""] = this.range;
806 ret += `[${min},${max}]`;
807 }
808
809 return ret;
810 }
811
812 /**
813 * Returns a percentage range for values of this type
814 * @param {number} scale
815 * @returns {[number, number]}
816 */
817 percentageRange (scale = 1) {
818 let range;
819 if (
820 (this.coordMeta && this.coordMeta.range) ||
821 (this.coordRange && this.coordRange[0] >= 0)
822 ) {
823 range = [0, 1];
824 }
825 else {
826 range = [-1, 1];
827 }
828 return [range[0] * scale, range[1] * scale];
829 }
830
831 static get (type, coordMeta) {
832 if (isInstance(type, this)) {
833 return type;
834 }
835
836 return new this(type, coordMeta);
837 }
838 }
839
840 /** @import { ColorSpace, Coords } from "./types.js" */
841
842 // Type re-exports
843 /** @typedef {import("./types.js").Format} FormatInterface */
844
845 /**
846 * @internal
847 * Used to index {@link FormatInterface Format} objects and store an instance.
848 * Not meant for external use
849 */
850 const instance = Symbol("instance");
851
852 /**
853 * Remove the first element of an array type
854 * @template {any[]} T
855 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
856 */
857
858 /**
859 * @class Format
860 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
861 * Class to hold a color serialization format
862 */
863 class Format {
864 // Class properties - declared here so that type inference works
865 type;
866 name;
867 spaceCoords;
868 /** @type {Type[][]} */
869 coords;
870 /** @type {string | undefined} */
871 id;
872 /** @type {boolean | undefined} */
873 alpha;
874
875 /**
876 * @param {FormatInterface} format
877 * @param {ColorSpace} space
878 */
879 constructor (format, space = format.space) {
880 format[instance] = this;
881 this.type = "function";
882 this.name = "color";
883
884 Object.assign(this, format);
885
886 this.space = space;
887
888 if (this.type === "custom") {
889 // Nothing else to do here
890 return;
891 }
892
893 this.spaceCoords = Object.values(space.coords);
894
895 if (!this.coords) {
896 // @ts-expect-error Strings are converted to the correct type later
897 this.coords = this.spaceCoords.map(coordMeta => {
898 let ret = ["<number>", "<percentage>"];
899
900 if (coordMeta.type === "angle") {
901 ret.push("<angle>");
902 }
903
904 return ret;
905 });
906 }
907
908 this.coords = this.coords.map(
909 /** @param {string | string[] | Type[]} types */ (types, i) => {
910 let coordMeta = this.spaceCoords[i];
911
912 if (typeof types === "string") {
913 types = types.trim().split(/\s*\|\s*/);
914 }
915
916 return types.map(type => Type.get(type, coordMeta));
917 },
918 );
919 }
920
921 /**
922 * @param {Coords} coords
923 * @param {number} precision
924 * @param {Type[]} types
925 */
926 serializeCoords (coords, precision, types) {
927 types = coords.map((_, i) =>
928 Type.get(types?.[i] ?? this.coords[i][0], this.spaceCoords[i]));
929 return coords.map((c, i) => types[i].serialize(c, precision));
930 }
931
932 /**
933 * Validates the coordinates of a color against a format's coord grammar and
934 * maps the coordinates to the range or refRange of the coordinates.
935 * @param {Coords} coords
936 * @param {[string, string, string]} types
937 */
938 coerceCoords (coords, types) {
939 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
940 let arg = coords[i];
941
942 if (isNone(arg) || isNaN(arg)) {
943 // Nothing to do here
944 return arg;
945 }
946
947 // Find grammar alternative that matches the provided type
948 // Non-strict equals is intentional because we are comparing w/ string objects
949 let providedType = types[i];
950 let type = this.coords[i].find(c => c.type == providedType);
951
952 // Check that each coord conforms to its grammar
953 if (!type) {
954 // Type does not exist in the grammar, throw
955 let coordName = coordMeta.name || id;
956 throw new TypeError(
957 `${providedType ?? /** @type {any} */ (arg)?.raw ?? arg} not allowed for ${coordName} in ${this.name}()`,
958 );
959 }
960
961 arg = type.resolve(arg);
962
963 if (type.range) {
964 // Adjust type to include range
965 types[i] = type.toString();
966 }
967
968 return arg;
969 });
970 }
971
972 /**
973 * @returns {boolean | Required<FormatInterface>["serialize"]}
974 */
975 canSerialize () {
976 return this.type === "function" || /** @type {any} */ (this).serialize;
977 }
978
979 /**
980 * @param {string} str
981 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
982 */
983 parse (str) {
984 return null;
985 }
986
987 /**
988 * @param {Format | FormatInterface} format
989 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
990 * @returns {Format}
991 */
992 static get (format, ...args) {
993 if (!format || isInstance(format, this)) {
994 return /** @type {Format} */ (format);
995 }
996
997 if (format[instance]) {
998 return format[instance];
999 }
1000
1001 return new Format(format, ...args);
1002 }
1003 }
1004
1005 // Type re-exports
1006 /** @typedef {import("./types.js").White} White */
1007
1008 /** @type {Record<string, White>} */
1009 // prettier-ignore
1010 const WHITES = {
1011 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
1012 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
1013 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290],
1014 };
1015
1016 /**
1017 *
1018 * @param {string | White} name
1019 * @returns {White}
1020 */
1021 function getWhite (name) {
1022 if (Array.isArray(name)) {
1023 return name;
1024 }
1025
1026 return WHITES[name];
1027 }
1028
1029 /**
1030 * Adapt XYZ from white point W1 to W2
1031 * @param {White | string} W1
1032 * @param {White | string} W2
1033 * @param {[number, number, number]} XYZ
1034 * @param {{ method?: string | undefined }} options
1035 * @returns {[number, number, number]}
1036 */
1037 function adapt$2 (W1, W2, XYZ, options = {}) {
1038 W1 = getWhite(W1);
1039 W2 = getWhite(W2);
1040
1041 if (!W1 || !W2) {
1042 throw new TypeError(
1043 `Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`,
1044 );
1045 }
1046
1047 if (W1 === W2) {
1048 // Same whitepoints, no conversion needed
1049 return XYZ;
1050 }
1051
1052 let env = { W1, W2, XYZ, options };
1053
1054 hooks.run("chromatic-adaptation-start", env);
1055
1056 if (!env.M) {
1057 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
1058 // prettier-ignore
1059 env.M = [
1060 [ 1.0479297925449969, 0.022946870601609652, -0.05019226628920524 ],
1061 [ 0.02962780877005599, 0.9904344267538799, -0.017073799063418826 ],
1062 [ -0.009243040646204504, 0.015055191490298152, 0.7518742814281371 ],
1063 ];
1064 }
1065 else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
1066 // prettier-ignore
1067 env.M = [
1068 [ 0.955473421488075, -0.02309845494876471, 0.06325924320057072 ],
1069 [ -0.0283697093338637, 1.0099953980813041, 0.021041441191917323 ],
1070 [ 0.012314014864481998, -0.020507649298898964, 1.330365926242124 ],
1071 ];
1072 }
1073 }
1074
1075 hooks.run("chromatic-adaptation-end", env);
1076
1077 if (env.M) {
1078 return multiply_v3_m3x3(env.XYZ, env.M);
1079 }
1080 else {
1081 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
1082 }
1083 }
1084
1085 /** @import { ColorConstructor } from "./types.js" */
1086
1087 // Type re-exports
1088 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
1089 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
1090 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
1091
1092 /**
1093 * Convert a CSS Color string to a color object
1094 * @param {string} str
1095 * @param {ParseOptions} [options]
1096 * @returns {ColorConstructor}
1097 */
1098 function parse (str, options) {
1099 let env = {
1100 str: String(str)?.trim(),
1101 options,
1102 };
1103
1104 hooks.run("parse-start", env);
1105
1106 if (env.color) {
1107 return env.color;
1108 }
1109
1110 env.parsed = parseFunction(env.str);
1111 let ret;
1112 let meta = env.options ? (env.options.parseMeta ?? env.options.meta) : null;
1113
1114 if (env.parsed) {
1115 // Is a functional syntax
1116 let name = env.parsed.name;
1117 let format;
1118 let space;
1119 let coords = env.parsed.args;
1120 let types = coords.map((c, i) => env.parsed.argMeta[i]?.type);
1121
1122 if (name === "color") {
1123 // color() function
1124 let id = coords.shift();
1125 types.shift();
1126 // Check against both <dashed-ident> and <ident> versions
1127 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
1128 let ids = [id, alternateId];
1129 format = ColorSpace.findFormat({ name, id: ids, type: "function" });
1130
1131 if (!format) {
1132 // Not found
1133 let didYouMean;
1134
1135 let registryId = id in ColorSpace.registry ? id : alternateId;
1136 if (registryId in ColorSpace.registry) {
1137 // Used color space id instead of color() id, these are often different
1138 let cssId = ColorSpace.registry[registryId].formats?.color?.id;
1139
1140 if (cssId) {
1141 let altColor = str.replace("color(" + id, "color(" + cssId);
1142 didYouMean = `Did you mean ${altColor}?`;
1143 }
1144 }
1145
1146 throw new TypeError(
1147 `Cannot parse ${env.str}. ` + (didYouMean ?? "Missing a plugin?"),
1148 );
1149 }
1150
1151 space = format.space;
1152
1153 if (format.id.startsWith("--") && !id.startsWith("--")) {
1154 defaults.warn(
1155 `${space.name} is a non-standard space and not currently supported in the CSS spec. ` +
1156 `Use prefixed color(${format.id}) instead of color(${id}).`,
1157 );
1158 }
1159 if (id.startsWith("--") && !format.id.startsWith("--")) {
1160 defaults.warn(
1161 `${space.name} is a standard space and supported in the CSS spec. ` +
1162 `Use color(${format.id}) instead of prefixed color(${id}).`,
1163 );
1164 }
1165 }
1166 else {
1167 format = ColorSpace.findFormat({ name, type: "function" });
1168 space = format.space;
1169 }
1170
1171 if (meta) {
1172 Object.assign(meta, {
1173 format,
1174 formatId: format.name,
1175 types,
1176 commas: env.parsed.commas,
1177 });
1178 }
1179
1180 let alpha = 1;
1181
1182 if (env.parsed.lastAlpha) {
1183 alpha = env.parsed.args.pop();
1184
1185 if (meta) {
1186 meta.alphaType = types.pop();
1187 }
1188 }
1189
1190 let coordCount = format.coords.length;
1191
1192 if (coords.length !== coordCount) {
1193 throw new TypeError(
1194 `Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`,
1195 );
1196 }
1197
1198 coords = format.coerceCoords(coords, types);
1199
1200 ret = { spaceId: space.id, coords, alpha };
1201 }
1202 else {
1203 // Custom, colorspace-specific format
1204 spaceloop: for (let space of ColorSpace.all) {
1205 for (let formatId in space.formats) {
1206 let format = space.formats[formatId];
1207
1208 if (format.type !== "custom") {
1209 continue;
1210 }
1211
1212 if (format.test && !format.test(env.str)) {
1213 continue;
1214 }
1215
1216 // Convert to Format object
1217 let formatObject = space.getFormat(format);
1218
1219 let color = formatObject.parse(env.str);
1220
1221 if (color) {
1222 if (meta) {
1223 Object.assign(meta, { format: formatObject, formatId });
1224 }
1225
1226 ret = color;
1227 break spaceloop;
1228 }
1229 }
1230 }
1231 }
1232
1233 if (!ret) {
1234 // If we're here, we couldn't parse
1235 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
1236 }
1237
1238 // Clamp alpha to [0, 1]
1239 ret.alpha = isNone(ret.alpha)
1240 ? ret.alpha
1241 : ret.alpha === undefined
1242 ? 1
1243 : clamp(0, ret.alpha, 1);
1244
1245 return ret;
1246 }
1247
1248 /**
1249 * Units and multiplication factors for the internally stored numbers
1250 */
1251 const units = {
1252 "%": 0.01,
1253 deg: 1,
1254 grad: 0.9,
1255 rad: 180 / Math.PI,
1256 turn: 360,
1257 };
1258
1259 const regex = {
1260 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
1261 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
1262 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
1263 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
1264
1265 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
1266 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g,
1267 };
1268
1269 /**
1270 * Parse a single function argument
1271 * @param {string} rawArg
1272 * @returns {{value: number, meta: ArgumentMeta}}
1273 */
1274 function parseArgument (rawArg) {
1275 /** @type {Partial<ArgumentMeta>} */
1276 let meta = {};
1277 let unit = rawArg.match(regex.unitValue)?.[0];
1278 /** @type {string | number} */
1279 let value = (meta.raw = rawArg);
1280
1281 if (unit) {
1282 // It’s a dimension token
1283 meta.type = unit === "%" ? "<percentage>" : "<angle>";
1284 meta.unit = unit;
1285 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
1286
1287 value = meta.unitless * units[unit];
1288 }
1289 else if (regex.number.test(value)) {
1290 // It's a number
1291 // Convert numerical args to numbers
1292 value = Number(value);
1293 meta.type = "<number>";
1294 }
1295 else if (value === "none") {
1296 value = null;
1297 }
1298 else if (value === "NaN" || value === "calc(NaN)") {
1299 value = NaN;
1300 meta.type = "<number>";
1301 }
1302 else {
1303 meta.type = "<ident>";
1304 }
1305
1306 return { value: /** @type {number} */ (value), meta: /** @type {ArgumentMeta} */ (meta) };
1307 }
1308
1309 /**
1310 * Parse a CSS function, regardless of its name and arguments
1311 * @param {string} str String to parse
1312 * @return {ParseFunctionReturn | void}
1313 */
1314 function parseFunction (str) {
1315 if (!str) {
1316 return;
1317 }
1318
1319 str = str.trim();
1320
1321 let parts = str.match(regex.function);
1322
1323 if (parts) {
1324 // It is a function, parse args
1325 let args = [];
1326 let argMeta = [];
1327 let lastAlpha = false;
1328 let name = parts[1].toLowerCase();
1329
1330 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
1331 let { value, meta } = parseArgument(rawArg);
1332
1333 if (
1334 // If there's a slash here, it's modern syntax
1335 $0.startsWith("/") ||
1336 // If there's still elements to process after there's already 3 in `args` (and the we're not dealing with "color()"), it's likely to be a legacy color like "hsl(0, 0%, 0%, 0.5)"
1337 (name !== "color" && args.length === 3)
1338 ) {
1339 // It's alpha
1340 lastAlpha = true;
1341 }
1342
1343 args.push(value);
1344 argMeta.push(meta);
1345 return "";
1346 });
1347
1348 return {
1349 name,
1350 args,
1351 argMeta,
1352 lastAlpha,
1353 commas: separators.includes(","),
1354 rawName: parts[1],
1355 rawArgs: parts[2],
1356 };
1357 }
1358 }
1359
1360 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
1361
1362 /**
1363 * Resolves a color reference (object or string) to a plain color object
1364 * @overload
1365 * @param {ColorTypes} color
1366 * @param {GetColorOptions} [options]
1367 * @returns {PlainColorObject}
1368 */
1369 /**
1370 * @overload
1371 * @param {ColorTypes[]} color
1372 * @param {GetColorOptions} [options]
1373 * @returns {PlainColorObject[]}
1374 */
1375 function getColor (color, options) {
1376 if (Array.isArray(color)) {
1377 return color.map(c => getColor(c, options));
1378 }
1379
1380 if (!color) {
1381 throw new TypeError("Empty color reference");
1382 }
1383
1384 if (isString(color)) {
1385 color = parse(color, options);
1386 }
1387
1388 // Object fixup
1389 let space = color.space || color.spaceId;
1390
1391 if (typeof space === "string") {
1392 // Convert string id to color space object
1393 color.space = ColorSpace.get(space);
1394 }
1395
1396 if (color.alpha === undefined) {
1397 color.alpha = 1;
1398 }
1399
1400 return color;
1401 }
1402
1403 /**
1404 * @packageDocumentation
1405 * Defines the class and other types related to creating color spaces.
1406 * For the builtin color spaces, see the `spaces` module.
1407 */
1408
1409 const ε$7 = 0.000075;
1410
1411 /**
1412 * Class to represent a color space
1413 */
1414 class ColorSpace {
1415 constructor (options) {
1416 this.id = options.id;
1417 this.name = options.name;
1418 this.base = options.base ? ColorSpace.get(options.base) : null;
1419 this.aliases = options.aliases;
1420 this.displaySpaces = options.displaySpaces?.map(space => ColorSpace.get(space));
1421
1422 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
1423 this.bases = [];
1424 for (let base = this.base; base; base = base.base) {
1425 this.bases.push(base);
1426 }
1427
1428 if (options.rgbGamut) {
1429 this.rgbGamut = options.rgbGamut;
1430 }
1431
1432 if (options.linearGamut) {
1433 this.linearGamut = options.linearGamut;
1434 }
1435
1436 if (this.base) {
1437 // Keep a subclass's own methods if the options don't override them
1438 if (options.fromBase) {
1439 this.fromBase = options.fromBase;
1440 }
1441
1442 if (options.toBase) {
1443 this.toBase = options.toBase;
1444 }
1445 }
1446
1447 // Coordinate metadata
1448
1449 let coords = options.coords ?? this.base.coords;
1450
1451 for (let name in coords) {
1452 if (!("name" in coords[name])) {
1453 coords[name].name = name;
1454 }
1455 }
1456 this.coords = coords;
1457
1458 // White point
1459
1460 let white = options.white ?? this.base.white ?? "D65";
1461 this.white = getWhite(white);
1462
1463 // Sort out formats
1464
1465 this.formats = options.formats ?? {};
1466
1467 for (let name in this.formats) {
1468 let format = this.formats[name];
1469 format.type ||= "function";
1470 format.name ||= name;
1471 }
1472
1473 if (!this.formats.color?.id) {
1474 this.formats.color = {
1475 ...(this.formats.color ?? {}),
1476 id: options.cssId || this.id,
1477 };
1478 }
1479
1480 // Gamut space
1481
1482 if (options.gamutSpace) {
1483 // Gamut space explicitly specified
1484 this.gamutSpace =
1485 options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
1486 }
1487 else {
1488 // No gamut space specified, calculate a sensible default
1489 if (this.isPolar) {
1490 // Do not check gamut through polar coordinates
1491 this.gamutSpace = this.base;
1492 }
1493 else {
1494 this.gamutSpace = this;
1495 }
1496 }
1497
1498 // Optimize inGamut for unbounded spaces
1499 if (this.gamutSpace.isUnbounded) {
1500 this.inGamut = (coords, options) => {
1501 return true;
1502 };
1503 }
1504
1505 // Matrices used by this color space, exposed so that consumer code
1506 // can reuse them instead of duplicating the data. E.g. `this.M.toXYZ`.
1507 this.M = options.M ?? {};
1508
1509 // Other stuff
1510 this.referred = options.referred;
1511
1512 // Compute ancestors and store them, since they will never change
1513 Object.defineProperty(this, "path", {
1514 value: getPath(this).reverse(),
1515 writable: false,
1516 enumerable: true,
1517 configurable: true,
1518 });
1519
1520 hooks.run("colorspace-init-end", this);
1521 }
1522
1523 inGamut (coords, { epsilon = ε$7 } = {}) {
1524 if (!this.equals(this.gamutSpace)) {
1525 coords = this.to(this.gamutSpace, coords);
1526 return this.gamutSpace.inGamut(coords, { epsilon });
1527 }
1528
1529 let coordMeta = Object.values(this.coords);
1530
1531 return coords.every((c, i) => {
1532 let meta = coordMeta[i];
1533
1534 if (meta.type !== "angle" && meta.range) {
1535 if (isNone(c)) {
1536 // NaN is always in gamut
1537 return true;
1538 }
1539
1540 let [min, max] = meta.range;
1541 return (
1542 (min === undefined || c >= min - epsilon) &&
1543 (max === undefined || c <= max + epsilon)
1544 );
1545 }
1546
1547 return true;
1548 });
1549 }
1550
1551 get isUnbounded () {
1552 return Object.values(this.coords).every(coord => !("range" in coord));
1553 }
1554
1555 get cssId () {
1556 return this.formats?.color?.id || this.id;
1557 }
1558
1559 /**
1560 * The id of this space's hue coordinate, or null if the space is not polar
1561 * @returns {string | null}
1562 */
1563 get hueId () {
1564 for (let id in this.coords) {
1565 if (this.coords[id].type === "angle") {
1566 return id;
1567 }
1568 }
1569
1570 return null;
1571 }
1572
1573 /**
1574 * The index of this space's hue coordinate within its coords array, or -1 if the space is not polar
1575 * @returns {number}
1576 */
1577 get hueIndex () {
1578 return Object.keys(this.coords).findIndex(id => this.coords[id].type === "angle");
1579 }
1580
1581 get isPolar () {
1582 return this.hueId !== null;
1583 }
1584
1585 /**
1586 * Lookup a format in this color space
1587 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
1588 * @returns {Format}
1589 */
1590 getFormat (format) {
1591 if (!format) {
1592 return null;
1593 }
1594
1595 if (format === "default") {
1596 format = Object.values(this.formats)[0];
1597 }
1598 else if (typeof format === "string") {
1599 format = this.formats[format];
1600 }
1601
1602 let ret = Format.get(format, this);
1603
1604 if (ret !== format && format.name in this.formats) {
1605 // Update the format we have on file so we can find it more quickly next time
1606 this.formats[format.name] = ret;
1607 }
1608
1609 return ret;
1610 }
1611
1612 /**
1613 * Check if this color space is the same as another color space reference.
1614 * Allows proxying color space objects and comparing color spaces with ids.
1615 * @param {string | ColorSpace} space ColorSpace object or id to compare to
1616 * @returns {boolean}
1617 */
1618 equals (space) {
1619 if (!space) {
1620 return false;
1621 }
1622
1623 return this === space || this.id === space || this.id === space.id;
1624 }
1625
1626 to (space, coords) {
1627 if (arguments.length === 1) {
1628 const color = getColor(space);
1629 [space, coords] = [color.space, color.coords];
1630 }
1631
1632 space = ColorSpace.get(space);
1633
1634 if (this.equals(space)) {
1635 // Same space, no change needed
1636 return coords;
1637 }
1638
1639 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
1640 coords = coords.map(c => (isNone(c) ? 0 : c));
1641
1642 // Find connection space = lowest common ancestor in the base tree
1643 let myPath = this.path;
1644 let otherPath = space.path;
1645
1646 let connectionSpace, connectionSpaceIndex;
1647
1648 for (let i = 0; i < myPath.length; i++) {
1649 if (myPath[i].equals(otherPath[i])) {
1650 connectionSpace = myPath[i];
1651 connectionSpaceIndex = i;
1652 }
1653 else {
1654 break;
1655 }
1656 }
1657
1658 if (!connectionSpace) {
1659 // This should never happen
1660 throw new Error(
1661 `Cannot convert between color spaces ${this} and ${space}: no connection space was found`,
1662 );
1663 }
1664
1665 // Go up from current space to connection space
1666 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
1667 coords = myPath[i].toBase(coords);
1668 }
1669
1670 // Go down from connection space to target space
1671 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
1672 coords = otherPath[i].fromBase(coords);
1673 }
1674
1675 return coords;
1676 }
1677
1678 from (space, coords) {
1679 if (arguments.length === 1) {
1680 const color = getColor(space);
1681 [space, coords] = [color.space, color.coords];
1682 }
1683
1684 space = ColorSpace.get(space);
1685
1686 return space.to(this, coords);
1687 }
1688
1689 toString () {
1690 return `${this.name} (${this.id})`;
1691 }
1692
1693 getMinCoords () {
1694 let ret = [];
1695
1696 for (let id in this.coords) {
1697 let meta = this.coords[id];
1698 let range = meta.range || meta.refRange;
1699 ret.push(range?.min ?? 0);
1700 }
1701
1702 return ret;
1703 }
1704
1705 static registry = {};
1706
1707 // Returns array of unique color spaces
1708 static get all () {
1709 return [...new Set(Object.values(ColorSpace.registry))];
1710 }
1711
1712 static register (id, space) {
1713 if (arguments.length === 1) {
1714 space = arguments[0];
1715 id = space.id;
1716 }
1717
1718 space = this.get(space);
1719
1720 if (this.registry[id] && this.registry[id] !== space) {
1721 throw new Error(`Duplicate color space registration: '${id}'`);
1722 }
1723 this.registry[id] = space;
1724
1725 // Register aliases when called without an explicit ID.
1726 if (arguments.length === 1 && space.aliases) {
1727 for (let alias of space.aliases) {
1728 this.register(alias, space);
1729 }
1730 }
1731
1732 return space;
1733 }
1734
1735 /**
1736 * Lookup ColorSpace object by name
1737 * @param {ColorSpace | string} name
1738 */
1739 static get (space, ...alternatives) {
1740 if (!space || isInstance(space, this)) {
1741 return space;
1742 }
1743
1744 let argType = type(space);
1745
1746 if (argType === "string") {
1747 // It's a color space id
1748 let ret = ColorSpace.registry[space.toLowerCase()];
1749
1750 if (!ret) {
1751 throw new TypeError(`No color space found with id = "${space}"`);
1752 }
1753
1754 return ret;
1755 }
1756
1757 if (alternatives.length) {
1758 return ColorSpace.get(...alternatives);
1759 }
1760
1761 throw new TypeError(`${space} is not a valid color space`);
1762 }
1763
1764 /**
1765 * Look up all color spaces for a format that matches certain criteria
1766 * @param {object | string} filters
1767 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
1768 * @returns {Format | null}
1769 */
1770 static findFormat (filters, spaces = ColorSpace.all) {
1771 if (!filters) {
1772 return null;
1773 }
1774
1775 if (typeof filters === "string") {
1776 filters = { name: filters };
1777 }
1778
1779 for (let space of spaces) {
1780 for (let [name, format] of Object.entries(space.formats)) {
1781 format.name ??= name;
1782 format.type ??= "function";
1783
1784 let matches =
1785 (!filters.name || format.name === filters.name) &&
1786 (!filters.type || format.type === filters.type);
1787
1788 if (filters.id) {
1789 let ids = format.ids || [format.id];
1790 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
1791 matches &&= filterIds.some(id => ids.includes(id));
1792 }
1793
1794 if (matches) {
1795 let ret = Format.get(format, space);
1796
1797 if (ret !== format) {
1798 space.formats[format.name] = ret;
1799 }
1800
1801 return ret;
1802 }
1803 }
1804 }
1805
1806 return null;
1807 }
1808
1809 /**
1810 * Get metadata about a coordinate of a color space
1811 *
1812 * @static
1813 * @param {Array | string} ref
1814 * @param {ColorSpace | string} [workingSpace]
1815 * @return {Object}
1816 */
1817 static resolveCoord (ref, workingSpace) {
1818 let coordType = type(ref);
1819 let space, coord;
1820
1821 if (coordType === "string") {
1822 if (ref.includes(".")) {
1823 // Absolute coordinate
1824 [space, coord] = ref.split(".");
1825 }
1826 else {
1827 // Relative coordinate
1828 [space, coord] = [, ref];
1829 }
1830 }
1831 else if (Array.isArray(ref)) {
1832 [space, coord] = ref;
1833 }
1834 else {
1835 // Object
1836 space = ref.space;
1837 coord = ref.coordId;
1838 }
1839
1840 space = ColorSpace.get(space);
1841
1842 if (!space) {
1843 space = workingSpace;
1844 }
1845
1846 if (!space) {
1847 throw new TypeError(
1848 `Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`,
1849 );
1850 }
1851
1852 coordType = type(coord);
1853
1854 if (coordType === "number" || (coordType === "string" && coord >= 0)) {
1855 // Resolve numerical coord
1856 let meta = Object.entries(space.coords)[coord];
1857
1858 if (meta) {
1859 return { space, id: meta[0], index: coord, ...meta[1] };
1860 }
1861 }
1862
1863 space = ColorSpace.get(space);
1864
1865 let normalizedCoord = coord.toLowerCase();
1866
1867 let i = 0;
1868 for (let id in space.coords) {
1869 let meta = space.coords[id];
1870
1871 if (
1872 id.toLowerCase() === normalizedCoord ||
1873 meta.name?.toLowerCase() === normalizedCoord
1874 ) {
1875 return { space, id, index: i, ...meta };
1876 }
1877
1878 i++;
1879 }
1880
1881 throw new TypeError(
1882 `No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`,
1883 );
1884 }
1885
1886 static DEFAULT_FORMAT = {
1887 type: "functions",
1888 name: "color",
1889 };
1890 }
1891
1892 function getPath (space) {
1893 let ret = [space];
1894
1895 for (let s = space; (s = s.base);) {
1896 ret.push(s);
1897 }
1898
1899 return ret;
1900 }
1901
1902 var XYZ_D65 = new ColorSpace({
1903 id: "xyz-d65",
1904 name: "XYZ D65",
1905 coords: {
1906 x: {
1907 refRange: [0, 1],
1908 name: "X",
1909 },
1910 y: {
1911 refRange: [0, 1],
1912 name: "Y",
1913 },
1914 z: {
1915 refRange: [0, 1],
1916 name: "Z",
1917 },
1918 },
1919 white: "D65",
1920 formats: {
1921 color: {
1922 ids: ["xyz-d65", "xyz"],
1923 },
1924 },
1925 aliases: ["xyz"],
1926 });
1927
1928 // Type re-exports
1929 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
1930
1931 /** Convenience class for RGB color spaces */
1932 class RGBColorSpace extends ColorSpace {
1933 /**
1934 * Creates a new RGB ColorSpace.
1935 * If coords are not specified, they will use the default RGB coords.
1936 * Instead of `fromBase()` and `toBase()` functions,
1937 * you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()`
1938 * methods use them via `this.M.toXYZ` and `this.M.fromXYZ`.
1939 * @param {RGBOptions} options
1940 */
1941 constructor (options) {
1942 if (!options.coords) {
1943 options.coords = {
1944 r: {
1945 range: [0, 1],
1946 name: "Red",
1947 },
1948 g: {
1949 range: [0, 1],
1950 name: "Green",
1951 },
1952 b: {
1953 range: [0, 1],
1954 name: "Blue",
1955 },
1956 };
1957 }
1958
1959 if (!options.base) {
1960 options.base = XYZ_D65;
1961 }
1962
1963 // Accept matrices either as dedicated options or via the generic `M` object
1964 let toXYZ = options.toXYZ_M ?? options.M?.toXYZ;
1965 let fromXYZ = options.fromXYZ_M ?? options.M?.fromXYZ;
1966
1967 options.referred ??= "display";
1968
1969 super(options);
1970
1971 // Expose the matrices on the color space (via `this.M`) so consumers can reuse them.
1972 if (toXYZ && fromXYZ) {
1973 this.M.toXYZ = toXYZ;
1974 this.M.fromXYZ = fromXYZ;
1975 }
1976 }
1977
1978 toBase (rgb) {
1979 let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ);
1980
1981 if (this.white !== this.base.white) {
1982 // Perform chromatic adaptation
1983 xyz = adapt$2(this.white, this.base.white, xyz);
1984 }
1985
1986 return xyz;
1987 }
1988
1989 fromBase (xyz) {
1990 xyz = adapt$2(this.base.white, this.white, xyz);
1991 return multiply_v3_m3x3(xyz, this.M.fromXYZ);
1992 }
1993 }
1994
1995 var XYZ_D50 = new ColorSpace({
1996 id: "xyz-d50",
1997 name: "XYZ D50",
1998 white: "D50",
1999 base: XYZ_D65,
2000 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
2001 toBase: coords => adapt$2("D50", XYZ_D65.white, coords),
2002 });
2003
2004 // κ * ε = 2^3 = 8
2005 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
2006 const ε3$1 = 24 / 116;
2007 const κ$4 = 24389 / 27; // 29^3/3^3
2008
2009 let white$4 = WHITES.D50;
2010
2011 var lab = new ColorSpace({
2012 id: "lab",
2013 name: "Lab",
2014 coords: {
2015 l: {
2016 refRange: [0, 100],
2017 name: "Lightness",
2018 },
2019 a: {
2020 refRange: [-125, 125],
2021 },
2022 b: {
2023 refRange: [-125, 125],
2024 },
2025 },
2026
2027 // Assuming XYZ is relative to D50, convert to CIE Lab
2028 // from CIE standard, which now defines these as a rational fraction
2029 white: white$4,
2030
2031 base: XYZ_D50,
2032 // Convert D50-adapted XYX to Lab
2033 // CIE 15.3:2004 section 8.2.1.1
2034 fromBase (XYZ) {
2035 // XYZ scaled relative to reference white
2036 let xyz = XYZ.map((value, i) => value / white$4[i]);
2037 let f = xyz.map(value => (value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116));
2038
2039 let L = 116 * f[1] - 16;
2040 let a = 500 * (f[0] - f[1]);
2041 let b = 200 * (f[1] - f[2]);
2042
2043 return [L, a, b];
2044 },
2045 // Convert Lab to D50-adapted XYZ
2046 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
2047 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
2048 toBase (Lab) {
2049 // compute f, starting with the luminance-related term
2050 let [L, a, b] = Lab;
2051 let f = [];
2052 f[1] = (L + 16) / 116;
2053 f[0] = a / 500 + f[1];
2054 f[2] = f[1] - b / 200;
2055
2056 // compute xyz
2057 // prettier-ignore
2058 let xyz = [
2059 f[0] > ε3$1 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$4,
2060 Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$4,
2061 f[2] > ε3$1 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$4,
2062 ];
2063
2064 // Compute XYZ by scaling xyz by reference white
2065 return xyz.map((value, i) => value * white$4[i]);
2066 },
2067
2068 formats: {
2069 lab: {
2070 coords: [
2071 "<percentage> | <number>",
2072 "<number> | <percentage>",
2073 "<number> | <percentage>",
2074 ],
2075 },
2076 },
2077 });
2078
2079 /**
2080 * Constrain an angle to 360 degrees
2081 * @param {number} angle
2082 * @returns {number}
2083 */
2084 function constrain (angle) {
2085 if (typeof angle !== "number") {
2086 return angle;
2087 }
2088
2089 return ((angle % 360) + 360) % 360;
2090 }
2091
2092 /**
2093 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
2094 * @param {[number, number]} angles
2095 * @returns {[number, number]}
2096 */
2097 function adjust (arc, angles) {
2098 let [a1, a2] = angles;
2099
2100 let none1 = isNone(a1);
2101 let none2 = isNone(a2);
2102
2103 if (none1 && none2) {
2104 return [a1, a2];
2105 }
2106 else if (none1) {
2107 a1 = a2;
2108 }
2109 else if (none2) {
2110 a2 = a1;
2111 }
2112
2113 if (arc === "raw") {
2114 return angles;
2115 }
2116
2117 a1 = constrain(a1);
2118 a2 = constrain(a2);
2119
2120 let angleDiff = a2 - a1;
2121
2122 if (arc === "increasing") {
2123 if (angleDiff < 0) {
2124 a2 += 360;
2125 }
2126 }
2127 else if (arc === "decreasing") {
2128 if (angleDiff > 0) {
2129 a1 += 360;
2130 }
2131 }
2132 else if (arc === "longer") {
2133 if (-180 < angleDiff && angleDiff < 180) {
2134 if (angleDiff > 0) {
2135 a1 += 360;
2136 }
2137 else {
2138 a2 += 360;
2139 }
2140 }
2141 }
2142 else if (arc === "shorter") {
2143 if (angleDiff > 180) {
2144 a1 += 360;
2145 }
2146 else if (angleDiff < -180) {
2147 a2 += 360;
2148 }
2149 }
2150
2151 return [a1, a2];
2152 }
2153
2154 var lch = new ColorSpace({
2155 id: "lch",
2156 name: "LCH",
2157 coords: {
2158 l: {
2159 refRange: [0, 100],
2160 name: "Lightness",
2161 },
2162 c: {
2163 refRange: [0, 150],
2164 name: "Chroma",
2165 },
2166 h: {
2167 refRange: [0, 360],
2168 type: "angle",
2169 name: "Hue",
2170 },
2171 },
2172
2173 base: lab,
2174 fromBase (Lab) {
2175 // These methods are used for other polar forms as well, so we can't hardcode the ε
2176 if (this.ε === undefined) {
2177 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
2178 let range = Object.values(this.base.coords)[1].refRange;
2179 let extent = range[1] - range[0];
2180 this.ε = extent / 100000;
2181 }
2182
2183 // Convert to polar form
2184 let [L, a, b] = Lab;
2185 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
2186 let h = isAchromatic ? null : constrain((Math.atan2(b, a) * 180) / Math.PI);
2187 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
2188
2189 return [L, C, h];
2190 },
2191 toBase (lch) {
2192 // Convert from polar form
2193 let [L, C, h] = lch;
2194 let a = null,
2195 b = null;
2196
2197 if (!isNone(h)) {
2198 C = C < 0 ? 0 : C; // Clamp negative Chroma
2199 a = C * Math.cos((h * Math.PI) / 180);
2200 b = C * Math.sin((h * Math.PI) / 180);
2201 }
2202
2203 return [L, a, b];
2204 },
2205
2206 formats: {
2207 lch: {
2208 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"],
2209 },
2210 },
2211 });
2212
2213 // deltaE2000 is a statistically significant improvement
2214 // and is recommended by the CIE and Idealliance
2215 // especially for color differences less than 10 deltaE76
2216 // but is wicked complicated
2217 // and many implementations have small errors!
2218 // DeltaE2000 is also discontinuous; in case this
2219 // matters to you, use deltaECMC instead.
2220
2221 const Gfactor = 25 ** 7;
2222 const π$1 = Math.PI;
2223 const r2d = 180 / π$1;
2224 const d2r$1 = π$1 / 180;
2225
2226 function pow7 (x) {
2227 // Faster than x ** 7 or Math.pow(x, 7)
2228
2229 const x2 = x * x;
2230 const x7 = x2 * x2 * x2 * x;
2231
2232 return x7;
2233 }
2234
2235 /**
2236 * @param {import("../types.js").ColorTypes} color
2237 * @param {import("../types.js").ColorTypes} sample
2238 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
2239 * @returns {number}
2240 */
2241 function deltaE2000 (color, sample, { kL = 1, kC = 1, kH = 1 } = {}) {
2242 [color, sample] = getColor([color, sample]);
2243
2244 // Given this color as the reference
2245 // and the function parameter as the sample,
2246 // calculate deltaE 2000.
2247
2248 // This implementation assumes the parametric
2249 // weighting factors kL, kC and kH
2250 // for the influence of viewing conditions
2251 // are all 1, as sadly seems typical.
2252 // kL should be increased for lightness texture or noise
2253 // and kC increased for chroma noise
2254
2255 let [L1, a1, b1] = lab.from(color);
2256 let C1 = lch.from(lab, [L1, a1, b1])[1];
2257 let [L2, a2, b2] = lab.from(sample);
2258 let C2 = lch.from(lab, [L2, a2, b2])[1];
2259
2260 // Check for negative Chroma,
2261 // which might happen through
2262 // direct user input of LCH values
2263
2264 if (C1 < 0) {
2265 C1 = 0;
2266 }
2267 if (C2 < 0) {
2268 C2 = 0;
2269 }
2270
2271 let Cbar = (C1 + C2) / 2; // mean Chroma
2272
2273 // calculate a-axis asymmetry factor from mean Chroma
2274 // this turns JND ellipses for near-neutral colors back into circles
2275 let C7 = pow7(Cbar);
2276
2277 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
2278
2279 // scale a axes by asymmetry factor
2280 // this by the way is why there is no Lab2000 colorspace
2281 let adash1 = (1 + G) * a1;
2282 let adash2 = (1 + G) * a2;
2283
2284 // calculate new Chroma from scaled a and original b axes
2285 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
2286 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
2287
2288 // calculate new hues, with zero hue for true neutrals
2289 // and in degrees, not radians
2290
2291 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
2292 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
2293
2294 if (h1 < 0) {
2295 h1 += 2 * π$1;
2296 }
2297 if (h2 < 0) {
2298 h2 += 2 * π$1;
2299 }
2300
2301 h1 *= r2d;
2302 h2 *= r2d;
2303
2304 // Lightness and Chroma differences; sign matters
2305 let ΔL = L2 - L1;
2306 let ΔC = Cdash2 - Cdash1;
2307
2308 // Hue difference, getting the sign correct
2309 let hdiff = h2 - h1;
2310 let hsum = h1 + h2;
2311 let habs = Math.abs(hdiff);
2312 let Δh;
2313
2314 if (Cdash1 * Cdash2 === 0) {
2315 Δh = 0;
2316 }
2317 else if (habs <= 180) {
2318 Δh = hdiff;
2319 }
2320 else if (hdiff > 180) {
2321 Δh = hdiff - 360;
2322 }
2323 else if (hdiff < -180) {
2324 Δh = hdiff + 360;
2325 }
2326 else {
2327 defaults.warn("the unthinkable has happened");
2328 }
2329
2330 // weighted Hue difference, more for larger Chroma
2331 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin((Δh * d2r$1) / 2);
2332
2333 // calculate mean Lightness and Chroma
2334 let Ldash = (L1 + L2) / 2;
2335 let Cdash = (Cdash1 + Cdash2) / 2;
2336 let Cdash7 = pow7(Cdash);
2337
2338 // Compensate for non-linearity in the blue region of Lab.
2339 // Four possibilities for hue weighting factor,
2340 // depending on the angles, to get the correct sign
2341 let hdash;
2342 if (Cdash1 * Cdash2 === 0) {
2343 hdash = hsum; // which should be zero
2344 }
2345 else if (habs <= 180) {
2346 hdash = hsum / 2;
2347 }
2348 else if (hsum < 360) {
2349 hdash = (hsum + 360) / 2;
2350 }
2351 else {
2352 hdash = (hsum - 360) / 2;
2353 }
2354
2355 // positional corrections to the lack of uniformity of CIELAB
2356 // These are all trying to make JND ellipsoids more like spheres
2357
2358 // SL Lightness crispening factor
2359 // a background with L=50 is assumed
2360 let lsq = (Ldash - 50) ** 2;
2361 let SL = 1 + (0.015 * lsq) / Math.sqrt(20 + lsq);
2362
2363 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
2364 let SC = 1 + 0.045 * Cdash;
2365
2366 // Cross term T for blue non-linearity
2367 let T = 1;
2368 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
2369 T += 0.24 * Math.cos(2 * hdash * d2r$1);
2370 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
2371 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
2372
2373 // SH Hue factor depends on Chroma,
2374 // as well as adjusted hue angle like deltaE94.
2375 let SH = 1 + 0.015 * Cdash * T;
2376
2377 // RT Hue rotation term compensates for rotation of JND ellipses
2378 // and Munsell constant hue lines
2379 // in the medium-high Chroma blue region
2380 // (Hue 225 to 315)
2381 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
2382 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
2383 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
2384
2385 // Finally calculate the deltaE, term by term as root sume of squares
2386 let dE = (ΔL / (kL * SL)) ** 2;
2387 dE += (ΔC / (kC * SC)) ** 2;
2388 dE += (ΔH / (kH * SH)) ** 2;
2389 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
2390 return Math.sqrt(dE);
2391 // Yay!!!
2392 }
2393
2394 /** @import { Matrix3x3 } from "../types.js" */
2395
2396 /**
2397 * Matrices used by this color space, also available as `Oklab.M`.
2398 * Recalculated for consistent reference white,
2399 * see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
2400 * @type {Record<string, Matrix3x3>}
2401 */
2402 // prettier-ignore
2403 const M$d = {
2404 XYZtoLMS: [
2405 [ 0.8190224379967030, 0.3619062600528904, -0.1288737815209879 ],
2406 [ 0.0329836539323885, 0.9292868615863434, 0.0361446663506424 ],
2407 [ 0.0481771893596242, 0.2642395317527308, 0.6335478284694309 ],
2408 ],
2409 // inverse of XYZtoLMS
2410 LMStoXYZ: [
2411 [ 1.2268798758459243, -0.5578149944602171, 0.2813910456659647 ],
2412 [ -0.0405757452148008, 1.1122868032803170, -0.0717110580655164 ],
2413 [ -0.0763729366746601, -0.4214933324022432, 1.5869240198367816 ],
2414 ],
2415 LMStoLab: [
2416 [ 0.2104542683093140, 0.7936177747023054, -0.0040720430116193 ],
2417 [ 1.9779985324311684, -2.4285922420485799, 0.4505937096174110 ],
2418 [ 0.0259040424655478, 0.7827717124575296, -0.8086757549230774 ],
2419 ],
2420 // LMStoLab inverted
2421 LabtoLMS: [
2422 [ 1.0000000000000000, 0.3963377773761749, 0.2158037573099136 ],
2423 [ 1.0000000000000000, -0.1055613458156586, -0.0638541728258133 ],
2424 [ 1.0000000000000000, -0.0894841775298119, -1.2914855480194092 ],
2425 ],
2426 };
2427
2428 var Oklab = new ColorSpace({
2429 id: "oklab",
2430 name: "Oklab",
2431 coords: {
2432 l: {
2433 refRange: [0, 1],
2434 name: "Lightness",
2435 },
2436 a: {
2437 refRange: [-0.4, 0.4],
2438 },
2439 b: {
2440 refRange: [-0.4, 0.4],
2441 },
2442 },
2443
2444 // Note that XYZ is relative to D65
2445 white: "D65",
2446 base: XYZ_D65,
2447 M: M$d,
2448 fromBase (XYZ) {
2449 // move to LMS cone domain
2450 let LMS = multiply_v3_m3x3(XYZ, M$d.XYZtoLMS);
2451
2452 // non-linearity
2453 LMS[0] = Math.cbrt(LMS[0]);
2454 LMS[1] = Math.cbrt(LMS[1]);
2455 LMS[2] = Math.cbrt(LMS[2]);
2456
2457 return multiply_v3_m3x3(LMS, M$d.LMStoLab, LMS);
2458 },
2459 toBase (OKLab) {
2460 // move to LMS cone domain
2461 let LMSg = multiply_v3_m3x3(OKLab, M$d.LabtoLMS);
2462
2463 // restore linearity
2464 LMSg[0] = LMSg[0] ** 3;
2465 LMSg[1] = LMSg[1] ** 3;
2466 LMSg[2] = LMSg[2] ** 3;
2467
2468 return multiply_v3_m3x3(LMSg, M$d.LMStoXYZ, LMSg);
2469 },
2470
2471 formats: {
2472 oklab: {
2473 coords: [
2474 "<percentage> | <number>",
2475 "<number> | <percentage>",
2476 "<number> | <percentage>",
2477 ],
2478 },
2479 },
2480 });
2481
2482 /**
2483 * More accurate color-difference formulae
2484 * than the simple 1976 Euclidean distance in CIE Lab
2485 * @param {import("../types.js").ColorTypes} color
2486 * @param {import("../types.js").ColorTypes} sample
2487 * @returns {number}
2488 */
2489 function deltaEOK (color, sample) {
2490 [color, sample] = getColor([color, sample]);
2491
2492 // Given this color as the reference
2493 // and a sample,
2494 // calculate deltaEOK, term by term as root sum of squares
2495 let [L1, a1, b1] = Oklab.from(color);
2496 let [L2, a2, b2] = Oklab.from(sample);
2497 let ΔL = L1 - L2;
2498 let Δa = a1 - a2;
2499 let Δb = b1 - b2;
2500 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
2501 }
2502
2503 /** @import { ColorTypes } from "./types.js" */
2504
2505 const ε$5 = 0.000075;
2506
2507 /**
2508 * Check if a color is in gamut of either its own or another color space
2509 * @param {ColorTypes} color
2510 * @param {string | ColorSpace} [space]
2511 * @param {{ epsilon?: number | undefined }} [param2]
2512 * @returns {boolean}
2513 */
2514 function inGamut (color, space, { epsilon = ε$5 } = {}) {
2515 color = getColor(color);
2516
2517 if (!space) {
2518 space = color.space;
2519 }
2520
2521 space = ColorSpace.get(space);
2522 let coords = color.coords;
2523
2524 if (space !== color.space) {
2525 coords = space.from(color);
2526 }
2527
2528 return space.inGamut(coords, { epsilon });
2529 }
2530
2531 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
2532
2533 /**
2534 * Convert to color space and return a new color
2535 * @param {ColorTypes} color
2536 * @param {string | ColorSpace} space
2537 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
2538 * @returns {PlainColorObject}
2539 */
2540 function to (color, space, { inGamut } = {}) {
2541 color = getColor(color);
2542 space = ColorSpace.get(space);
2543
2544 let coords = space.from(color);
2545 let ret = { space, coords, alpha: color.alpha };
2546
2547 if (inGamut) {
2548 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
2549 }
2550
2551 return ret;
2552 }
2553
2554 /** @type {"color"} */
2555 to.returns = "color";
2556
2557 /** @import { ColorTypes, Coords } from "./types.js" */
2558
2559 /**
2560 * Options for {@link getAll}
2561 * @typedef GetAllOptions
2562 * @property {string | ColorSpace | undefined} [space]
2563 * The color space to convert to. Defaults to the color's current space
2564 * @property {number | undefined} [precision]
2565 * The number of significant digits to round the coordinates to
2566 */
2567
2568 /**
2569 * Get the coordinates of a color in any color space
2570 * @overload
2571 * @param {ColorTypes} color
2572 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
2573 * @returns {Coords} The color coordinates in the given color space
2574 */
2575 /**
2576 * @overload
2577 * @param {ColorTypes} color
2578 * @param {GetAllOptions} [options]
2579 * @returns {Coords} The color coordinates in the given color space
2580 */
2581 function getAll (color, options) {
2582 color = getColor(color);
2583
2584 let space = ColorSpace.get(options, options?.space);
2585 let precision = options?.precision;
2586
2587 let coords;
2588 if (!space || color.space.equals(space)) {
2589 // No conversion needed
2590 coords = color.coords.slice();
2591 }
2592 else {
2593 coords = space.from(color);
2594 }
2595
2596 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
2597 }
2598
2599 /** @import { ColorTypes, Ref } from "./types.js" */
2600
2601 /**
2602 * @param {ColorTypes} color
2603 * @param {Ref} prop
2604 * @returns {number}
2605 */
2606 function get (color, prop) {
2607 color = getColor(color);
2608
2609 if (prop === "alpha") {
2610 return color.alpha ?? 1;
2611 }
2612
2613 let { space, index } = ColorSpace.resolveCoord(prop, color.space);
2614 let coords = getAll(color, space);
2615 return coords[index];
2616 }
2617
2618 var OKLCH = new ColorSpace({
2619 id: "oklch",
2620 name: "OkLCh",
2621 coords: {
2622 l: {
2623 refRange: [0, 1],
2624 name: "Lightness",
2625 },
2626 c: {
2627 refRange: [0, 0.4],
2628 name: "Chroma",
2629 },
2630 h: {
2631 refRange: [0, 360],
2632 type: "angle",
2633 name: "Hue",
2634 },
2635 },
2636 white: "D65",
2637
2638 base: Oklab,
2639 fromBase: lch.fromBase,
2640 toBase: lch.toBase,
2641
2642 formats: {
2643 oklch: {
2644 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"],
2645 },
2646 },
2647 });
2648
2649 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
2650
2651 /**
2652 * Set all coordinates of a color at once, in its own color space or another.
2653 * Modifies the color in place.
2654 * @overload
2655 * @param {ColorTypes} color
2656 * @param {Coords} coords Array of coordinates
2657 * @param {number} [alpha]
2658 * @returns {PlainColorObject}
2659 */
2660 /**
2661 * @overload
2662 * @param {ColorTypes} color
2663 * @param {string | ColorSpace} space The color space of the provided coordinates.
2664 * @param {Coords} coords Array of coordinates
2665 * @param {number} [alpha]
2666 * @returns {PlainColorObject}
2667 */
2668 function setAll (color, space, coords, alpha) {
2669 color = getColor(color);
2670
2671 if (Array.isArray(space)) {
2672 // Space is omitted
2673 [space, coords, alpha] = [color.space, space, coords];
2674 }
2675
2676 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
2677 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
2678
2679 if (alpha !== undefined) {
2680 color.alpha = alpha;
2681 }
2682
2683 return color;
2684 }
2685
2686 /** @type {"color"} */
2687 setAll.returns = "color";
2688
2689 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
2690
2691 /**
2692 * Set properties and return current instance
2693 * @overload
2694 * @param {ColorTypes} color
2695 * @param {Ref} prop
2696 * @param {number | ((coord: number) => number)} value
2697 * @returns {PlainColorObject}
2698 */
2699 /**
2700 * @overload
2701 * @param {ColorTypes} color
2702 * @param {Record<string, number | ((coord: number) => number)>} props
2703 * @returns {PlainColorObject}
2704 */
2705 function set (color, prop, value) {
2706 color = getColor(color);
2707
2708 if (arguments.length === 2 && type(arguments[1]) === "object") {
2709 // Argument is an object literal
2710 let object = arguments[1];
2711 for (let p in object) {
2712 set(color, p, object[p]);
2713 }
2714 }
2715 else {
2716 if (typeof value === "function") {
2717 value = value(get(color, prop));
2718 }
2719
2720 if (prop === "alpha") {
2721 color.alpha = value;
2722 }
2723 else {
2724 let { space, index } = ColorSpace.resolveCoord(prop, color.space);
2725 let coords = getAll(color, space);
2726 coords[index] = value;
2727 setAll(color, space, coords);
2728 }
2729 }
2730
2731 return color;
2732 }
2733
2734 /** @type {"color"} */
2735 set.returns = "color";
2736
2737 /** @import { Coords, PlainColorObject } from "./types.js" */
2738
2739 /**
2740 * @param {PlainColorObject} color
2741 * @returns {PlainColorObject}
2742 */
2743 function clone (color) {
2744 return {
2745 space: color.space,
2746 coords: /** @type {Coords} */ (color.coords.slice()),
2747 alpha: color.alpha,
2748 };
2749 }
2750
2751 /** @import { ColorTypes } from "./types.js" */
2752
2753 /**
2754 * Euclidean distance of colors in an arbitrary color space
2755 * @param {ColorTypes} color1
2756 * @param {ColorTypes} color2
2757 * @param {string | ColorSpace} space
2758 * @returns {number}
2759 */
2760 function distance (color1, color2, space = "lab") {
2761 space = ColorSpace.get(space);
2762
2763 // Assume getColor() is called on color in space.from()
2764 let coords1 = space.from(color1);
2765 let coords2 = space.from(color2);
2766
2767 return Math.sqrt(
2768 coords1.reduce((acc, c1, i) => {
2769 let c2 = coords2[i];
2770 if (isNone(c1) || isNone(c2)) {
2771 return acc;
2772 }
2773
2774 return acc + (c2 - c1) ** 2;
2775 }, 0),
2776 );
2777 }
2778
2779 /**
2780 * @param {import("../types.js").ColorTypes} color
2781 * @param {import("../types.js").ColorTypes} sample
2782 * @returns {number}
2783 */
2784 function deltaE76 (color, sample) {
2785 // Assume getColor() is called in the distance function
2786 return distance(color, sample, "lab");
2787 }
2788
2789 // More accurate color-difference formulae
2790 // than the simple 1976 Euclidean distance in Lab
2791
2792 // CMC by the Color Measurement Committee of the
2793 // Bradford Society of Dyeists and Colorsts, 1994.
2794 // Uses LCH rather than Lab,
2795 // with different weights for L, C and H differences
2796 // A nice increase in accuracy for modest increase in complexity
2797 const π = Math.PI;
2798 const d2r = π / 180;
2799
2800 /**
2801 * @param {import("../types.js").ColorTypes} color
2802 * @param {import("../types.js").ColorTypes} sample
2803 * @param {{ l?: number | undefined; c?: number | undefined }} options
2804 * @returns {number}
2805 */
2806 function deltaECMC (color, sample, { l = 2, c = 1 } = {}) {
2807 [color, sample] = getColor([color, sample]);
2808
2809 // Given this color as the reference
2810 // and a sample,
2811 // calculate deltaE CMC.
2812
2813 // This implementation assumes the parametric
2814 // weighting factors l:c are 2:1
2815 // which is typical for non-textile uses.
2816
2817 let [L1, a1, b1] = lab.from(color);
2818 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
2819 let [L2, a2, b2] = lab.from(sample);
2820 let C2 = lch.from(lab, [L2, a2, b2])[1];
2821
2822 // let [L1, a1, b1] = color.getAll(lab);
2823 // let C1 = color.get("lch.c");
2824 // let H1 = color.get("lch.h");
2825 // let [L2, a2, b2] = sample.getAll(lab);
2826 // let C2 = sample.get("lch.c");
2827
2828 // Check for negative Chroma,
2829 // which might happen through
2830 // direct user input of LCH values
2831
2832 if (C1 < 0) {
2833 C1 = 0;
2834 }
2835 if (C2 < 0) {
2836 C2 = 0;
2837 }
2838
2839 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
2840
2841 // Lightness and Chroma differences
2842 // These are (color - sample), unlike deltaE2000
2843 let ΔL = L1 - L2;
2844 let ΔC = C1 - C2;
2845
2846 let Δa = a1 - a2;
2847 let Δb = b1 - b2;
2848
2849 // weighted Hue difference, less for larger Chroma difference
2850
2851 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
2852 // due to roundoff error it is possible that, for zero a and b,
2853 // ΔC > Δa + Δb is 0, resulting in attempting
2854 // to take the square root of a negative number
2855
2856 // trying instead the equation from Industrial Color Physics
2857 // By Georg A. Klein
2858
2859 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
2860 // console.log({ΔH});
2861 // This gives the same result to 12 decimal places
2862 // except it sometimes NaNs when trying to root a negative number
2863
2864 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
2865
2866 // positional corrections to the lack of uniformity of CIELAB
2867 // These are all trying to make JND ellipsoids more like spheres
2868
2869 // SL Lightness crispening factor, depends entirely on L1 not L2
2870 let SL = 0.511; // linear portion of the Y to L transfer function
2871 if (L1 >= 16) {
2872 // cubic portion
2873 SL = (0.040975 * L1) / (1 + 0.01765 * L1);
2874 }
2875
2876 // SC Chroma factor
2877 let SC = (0.0638 * C1) / (1 + 0.0131 * C1) + 0.638;
2878
2879 // Cross term T for blue non-linearity
2880 let T;
2881 if (isNone(H1)) {
2882 H1 = 0;
2883 }
2884
2885 if (H1 >= 164 && H1 <= 345) {
2886 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
2887 }
2888 else {
2889 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
2890 }
2891 // console.log({T});
2892
2893 // SH Hue factor also depends on C1,
2894 let C4 = Math.pow(C1, 4);
2895 let F = Math.sqrt(C4 / (C4 + 1900));
2896 let SH = SC * (F * T + 1 - F);
2897
2898 // Finally calculate the deltaE, term by term as root sume of squares
2899 let dE = (ΔL / (l * SL)) ** 2;
2900 dE += (ΔC / (c * SC)) ** 2;
2901 dE += H2 / SH ** 2;
2902 // dE += (ΔH / SH) ** 2;
2903 return Math.sqrt(dE);
2904 // Yay!!!
2905 }
2906
2907 const Yw$1 = 203; // absolute luminance of media white
2908
2909 var XYZ_Abs_D65 = new ColorSpace({
2910 // Absolute CIE XYZ, with a D65 whitepoint,
2911 // as used in most HDR colorspaces as a starting point.
2912 // SDR spaces are converted per BT.2048
2913 // so that diffuse, media white is 203 cd/m²
2914 id: "xyz-abs-d65",
2915 cssId: "--xyz-abs-d65",
2916 name: "Absolute XYZ D65",
2917 coords: {
2918 x: {
2919 refRange: [0, 9504.7],
2920 name: "Xa",
2921 },
2922 y: {
2923 refRange: [0, 10000],
2924 name: "Ya",
2925 },
2926 z: {
2927 refRange: [0, 10888.3],
2928 name: "Za",
2929 },
2930 },
2931
2932 base: XYZ_D65,
2933 fromBase (XYZ) {
2934 // Make XYZ absolute, not relative to media white
2935 // Maximum luminance in PQ is 10,000 cd/m²
2936 // Relative XYZ has Y=1 for media white
2937 return XYZ.map(v => v * Yw$1);
2938 },
2939 toBase (AbsXYZ) {
2940 // Convert to media-white relative XYZ
2941 return AbsXYZ.map(v => v / Yw$1);
2942 },
2943 });
2944
2945 /** @import { Matrix3x3, Vector3 } from "../types.js" */
2946
2947 const b$1 = 1.15;
2948 const g = 0.66;
2949 const n$1 = 2610 / 2 ** 14;
2950 const ninv$1 = 2 ** 14 / 2610;
2951 const c1$2 = 3424 / 2 ** 12;
2952 const c2$2 = 2413 / 2 ** 7;
2953 const c3$2 = 2392 / 2 ** 7;
2954 const p$1 = (1.7 * 2523) / 2 ** 5;
2955 const pinv = 2 ** 5 / (1.7 * 2523);
2956 const d = -0.56;
2957 const d0 = 1.6295499532821566e-11;
2958
2959 /**
2960 * Matrices used by this color space, also available as `Jzazbz.M`
2961 * @type {Record<string, Matrix3x3>}
2962 */
2963 // prettier-ignore
2964 const M$c = {
2965 XYZtoCone: [
2966 [ 0.41478972, 0.579999, 0.0146480 ],
2967 [ -0.2015100, 1.120649, 0.0531008 ],
2968 [ -0.0166008, 0.264800, 0.6684799 ],
2969 ],
2970 // XYZtoCone inverted
2971 ConetoXYZ: [
2972 [ 1.9242264357876067, -1.0047923125953657, 0.037651404030618 ],
2973 [ 0.35031676209499907, 0.7264811939316552, -0.06538442294808501 ],
2974 [ -0.09098281098284752, -0.3127282905230739, 1.5227665613052603 ],
2975 ],
2976 ConetoIab: [
2977 [ 0.5, 0.5, 0 ],
2978 [ 3.524000, -4.066708, 0.542708 ],
2979 [ 0.199076, 1.096799, -1.295875 ],
2980 ],
2981 // ConetoIab inverted
2982 IabtoCone: [
2983 [ 1, 0.13860504327153927, 0.05804731615611883 ],
2984 [ 1, -0.1386050432715393, -0.058047316156118904 ],
2985 [ 1, -0.09601924202631895, -0.81189189605603900 ],
2986 ],
2987 };
2988
2989 var Jzazbz = new ColorSpace({
2990 id: "jzazbz",
2991 name: "Jzazbz",
2992 coords: {
2993 jz: {
2994 refRange: [0, 1],
2995 name: "Jz",
2996 },
2997 az: {
2998 refRange: [-0.21, 0.21],
2999 },
3000 bz: {
3001 refRange: [-0.21, 0.21],
3002 },
3003 },
3004
3005 base: XYZ_Abs_D65,
3006 M: M$c,
3007 fromBase (XYZ) {
3008 // First make XYZ absolute, not relative to media white
3009 // Maximum luminance in PQ is 10,000 cd/m²
3010 // Relative XYZ has Y=1 for media white
3011 // BT.2048 says media white Y=203 at PQ 58
3012
3013 let [Xa, Ya, Za] = XYZ;
3014
3015 // modify X and Y to minimize blue curvature
3016 let Xm = b$1 * Xa - (b$1 - 1) * Za;
3017 let Ym = g * Ya - (g - 1) * Xa;
3018
3019 // move to LMS cone domain
3020 let LMS = multiply_v3_m3x3([Xm, Ym, Za], M$c.XYZtoCone);
3021
3022 // PQ-encode LMS
3023 let PQLMS = /** @type {Vector3} } */ (
3024 LMS.map(function (val) {
3025 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
3026 let denom = 1 + c3$2 * spow(val / 10000, n$1);
3027
3028 return spow(num / denom, p$1);
3029 })
3030 );
3031
3032 // almost there, calculate Iz az bz
3033 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, M$c.ConetoIab);
3034 // console.log({Iz, az, bz});
3035
3036 let Jz = ((1 + d) * Iz) / (1 + d * Iz) - d0;
3037 return [Jz, az, bz];
3038 },
3039 toBase (Jzazbz) {
3040 let [Jz, az, bz] = Jzazbz;
3041 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
3042
3043 // bring into LMS cone domain
3044 let PQLMS = multiply_v3_m3x3([Iz, az, bz], M$c.IabtoCone);
3045
3046 // convert from PQ-coded to linear-light
3047 let LMS = /** @type {Vector3} } */ (
3048 PQLMS.map(function (val) {
3049 let num = c1$2 - spow(val, pinv);
3050 let denom = c3$2 * spow(val, pinv) - c2$2;
3051 let x = 10000 * spow(num / denom, ninv$1);
3052
3053 return x; // luminance relative to diffuse white, [0, 70 or so].
3054 })
3055 );
3056
3057 // modified abs XYZ
3058 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, M$c.ConetoXYZ);
3059
3060 // un-modify X and Y to get D65 XYZ, relative to media white
3061 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
3062 let Ya = (Ym + (g - 1) * Xa) / g;
3063 return [Xa, Ya, Za];
3064 },
3065
3066 formats: {
3067 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
3068 jzazbz: {
3069 coords: [
3070 "<percentage> | <number>",
3071 "<number> | <percentage>",
3072 "<number> | <percentage>",
3073 ],
3074 },
3075 },
3076 });
3077
3078 var jzczhz = new ColorSpace({
3079 id: "jzczhz",
3080 name: "JzCzHz",
3081 coords: {
3082 jz: {
3083 refRange: [0, 1],
3084 name: "Jz",
3085 },
3086 cz: {
3087 refRange: [0, 0.26],
3088 name: "Chroma",
3089 },
3090 hz: {
3091 refRange: [0, 360],
3092 type: "angle",
3093 name: "Hue",
3094 },
3095 },
3096
3097 base: Jzazbz,
3098 fromBase: lch.fromBase,
3099 toBase: lch.toBase,
3100
3101 formats: {
3102 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
3103 jzczhz: {
3104 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"],
3105 },
3106 },
3107 });
3108
3109 /**
3110 * More accurate color-difference formulae
3111 * than the simple 1976 Euclidean distance in Lab
3112 *
3113 * Uses JzCzHz, which has improved perceptual uniformity
3114 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
3115 * gives good results.
3116 * @param {import("../types.js").ColorTypes} color
3117 * @param {import("../types.js").ColorTypes} sample
3118 * @returns {number}
3119 */
3120 function deltaEJz (color, sample) {
3121 [color, sample] = getColor([color, sample]);
3122
3123 // Given this color as the reference
3124 // and a sample,
3125 // calculate deltaE in JzCzHz.
3126 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
3127 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
3128
3129 // Lightness and Chroma differences
3130 // sign does not matter as they are squared.
3131 let ΔJ = Jz1 - Jz2;
3132 let ΔC = Cz1 - Cz2;
3133
3134 // length of chord for ΔH
3135 if (isNone(Hz1) && isNone(Hz2)) {
3136 // both undefined hues
3137 Hz1 = 0;
3138 Hz2 = 0;
3139 }
3140 else if (isNone(Hz1)) {
3141 // one undefined, set to the defined hue
3142 Hz1 = Hz2;
3143 }
3144 else if (isNone(Hz2)) {
3145 Hz2 = Hz1;
3146 }
3147
3148 let Δh = Hz1 - Hz2;
3149 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin((Δh / 2) * (Math.PI / 180));
3150
3151 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
3152 }
3153
3154 /** @import { Matrix3x3, Vector3 } from "../types.js" */
3155
3156 const c1$1 = 3424 / 4096;
3157 const c2$1 = 2413 / 128;
3158 const c3$1 = 2392 / 128;
3159 const m1 = 2610 / 16384;
3160 const m2 = 2523 / 32;
3161 const im1 = 16384 / 2610;
3162 const im2 = 32 / 2523;
3163
3164 // Reference (rational-form) matrices, kept for documentation but not used directly:
3165 // linear-light Rec.2020 to LMS (with crosstalk) and its inverse
3166 // rational terms from Jan Fröhlich, Encoding High Dynamic Range
3167 // and Wide Color Gamut Imagery, p.97 and ITU-R BT.2124-0 pp.2-3
3168 /*
3169 const Rec2020toLMS = [
3170 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
3171 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
3172 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
3173 ];
3174 const LMStoRec2020 = [
3175 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
3176 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
3177 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
3178 ];
3179 */
3180
3181 /**
3182 * Matrices used by this color space, also available as `ICTCP.M`
3183 * @type {Record<string, Matrix3x3>}
3184 */
3185 // prettier-ignore
3186 const M$b = {
3187 // includes the 4% crosstalk components, from the Dolby "What is ICtCp" paper
3188 XYZtoLMS: [
3189 [ 0.3592832590121217, 0.6976051147779502, -0.0358915932320290 ],
3190 [ -0.1920808463704993, 1.1004767970374321, 0.0753748658519118 ],
3191 [ 0.0070797844607479, 0.0748396662186362, 0.8433265453898765 ],
3192 ],
3193 // includes the Ebner LMS coefficients, the rotation,
3194 // and the scaling to the [-0.5,0.5] range
3195 LMStoIPT: [
3196 [ 2048 / 4096, 2048 / 4096, 0 ],
3197 [ 6610 / 4096, -13613 / 4096, 7003 / 4096 ],
3198 [ 17933 / 4096, -17390 / 4096, -543 / 4096 ],
3199 ],
3200 // inverted matrices, calculated from the above
3201 IPTtoLMS: [
3202 [ 0.9999999999999998, 0.0086090370379328, 0.1110296250030260 ],
3203 [ 0.9999999999999998, -0.0086090370379328, -0.1110296250030259 ],
3204 [ 0.9999999999999998, 0.5600313357106791, -0.3206271749873188 ],
3205 ],
3206 LMStoXYZ: [
3207 [ 2.0701522183894223, -1.3263473389671563, 0.2066510476294053 ],
3208 [ 0.3647385209748072, 0.6805660249472273, -0.0453045459220347 ],
3209 [ -0.0497472075358123, -0.0492609666966131, 1.1880659249923042 ],
3210 ],
3211 };
3212
3213 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
3214 // from Dolby, "WHAT IS ICTCP?"
3215 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
3216 // and
3217 // Dolby, "Perceptual Color Volume
3218 // Measuring the Distinguishable Colors of HDR and WCG Displays"
3219 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
3220 var ictcp = new ColorSpace({
3221 id: "ictcp",
3222 name: "ICTCP",
3223 // From BT.2100-2 page 7:
3224 // During production, signal values are expected to exceed the
3225 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
3226 // signal degradation during cascaded processing. Such values of E′,
3227 // below 0.0 or exceeding 1.0, should not be clipped during production
3228 // and exchange.
3229 // Values below 0.0 should not be clipped in reference displays (even
3230 // though they represent “negative” light) to allow the black level of
3231 // the signal (LB) to be properly set using test signals known as “PLUGE”
3232 coords: {
3233 i: {
3234 refRange: [0, 1], // Constant luminance,
3235 name: "I",
3236 },
3237 ct: {
3238 refRange: [-0.5, 0.5], // Full BT.2020 gamut in range [-0.5, 0.5]
3239 name: "CT",
3240 },
3241 cp: {
3242 refRange: [-0.5, 0.5],
3243 name: "CP",
3244 },
3245 },
3246
3247 base: XYZ_Abs_D65,
3248 M: M$b,
3249 fromBase (XYZ) {
3250 // move to LMS cone domain
3251 let LMS = multiply_v3_m3x3(XYZ, M$b.XYZtoLMS);
3252
3253 return LMStoICtCp(LMS);
3254 },
3255 toBase (ICtCp) {
3256 let LMS = ICtCptoLMS(ICtCp);
3257
3258 return multiply_v3_m3x3(LMS, M$b.LMStoXYZ);
3259 },
3260
3261 formats: {
3262 ictcp: {
3263 coords: [
3264 "<percentage> | <number>",
3265 "<number> | <percentage>",
3266 "<number> | <percentage>",
3267 ],
3268 },
3269 },
3270 });
3271
3272 /**
3273 *
3274 * @param {Vector3} LMS
3275 * @returns {Vector3}
3276 */
3277 function LMStoICtCp (LMS) {
3278 // apply the PQ EOTF
3279 // we can't ever be dividing by zero because of the "1 +" in the denominator
3280 let PQLMS = /** @type {Vector3} */ (
3281 LMS.map(function (val) {
3282 let num = c1$1 + c2$1 * (val / 10000) ** m1;
3283 let denom = 1 + c3$1 * (val / 10000) ** m1;
3284
3285 return (num / denom) ** m2;
3286 })
3287 );
3288
3289 // LMS to IPT, with rotation for Y'C'bC'r compatibility
3290 return multiply_v3_m3x3(PQLMS, M$b.LMStoIPT);
3291 }
3292
3293 /**
3294 *
3295 * @param {Vector3} ICtCp
3296 * @returns {Vector3}
3297 */
3298 function ICtCptoLMS (ICtCp) {
3299 let PQLMS = multiply_v3_m3x3(ICtCp, M$b.IPTtoLMS);
3300
3301 // From BT.2124-0 Annex 2 Conversion 3
3302 let LMS = /** @type {Vector3} */ (
3303 PQLMS.map(function (val) {
3304 let num = Math.max(val ** im2 - c1$1, 0);
3305 let denom = c2$1 - c3$1 * val ** im2;
3306 return 10000 * (num / denom) ** im1;
3307 })
3308 );
3309
3310 return LMS;
3311 }
3312
3313 /**
3314 * Delta E in ICtCp space,
3315 * which the ITU calls Delta E ITP, which is shorter.
3316 * Formulae from ITU Rec. ITU-R BT.2124-0
3317 * @param {import("../types.js").ColorTypes} color
3318 * @param {import("../types.js").ColorTypes} sample
3319 * @returns {number}
3320 */
3321 function deltaEITP (color, sample) {
3322 [color, sample] = getColor([color, sample]);
3323
3324 // Given this color as the reference
3325 // and a sample,
3326 // calculate deltaE in ICtCp
3327 // which is simply the Euclidean distance
3328
3329 let [I1, T1, P1] = ictcp.from(color);
3330 let [I2, T2, P2] = ictcp.from(sample);
3331
3332 // the 0.25 factor is to undo the encoding scaling in Ct
3333 // the 720 is so that 1 deltaE = 1 JND
3334 // per ITU-R BT.2124-0 p.3
3335
3336 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
3337 }
3338
3339 /**
3340 * More accurate color-difference formulae
3341 * than the simple 1976 Euclidean distance in CIE Lab
3342 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
3343 * Björn Ottosson said:
3344 * "I've recently done some tests with color distance datasets as implemented
3345 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
3346 * scale factor of slightly more than 2 for a and b would give the best results
3347 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
3348 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
3349 * @param {import("../types.js").ColorTypes} color
3350 * @param {import("../types.js").ColorTypes} sample
3351 * @returns {number}
3352 */
3353 function deltaEOK2 (color, sample) {
3354 [color, sample] = getColor([color, sample]);
3355
3356 // Given this color as the reference
3357 // and a sample,
3358 // calculate deltaEOK2, term by term as root sum of squares
3359 let abscale = 2;
3360 let [L1, a1, b1] = Oklab.from(color);
3361 let [L2, a2, b2] = Oklab.from(sample);
3362 let ΔL = L1 - L2;
3363 let Δa = abscale * (a1 - a2);
3364 let Δb = abscale * (b1 - b2);
3365 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
3366 }
3367
3368 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
3369
3370 // Type re-exports
3371 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
3372 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
3373 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
3374
3375 const white$3 = WHITES.D65;
3376 const adaptedCoef = 0.42;
3377 const adaptedCoefInv = 1 / adaptedCoef;
3378 const tau$1 = 2 * Math.PI;
3379
3380 /**
3381 * Matrices used by this color space, also available as `CAM16_JMh.M`
3382 * @type {Record<string, Matrix3x3>}
3383 */
3384 // prettier-ignore
3385 const M$a = {
3386 cat16: [
3387 [ 0.401288, 0.650173, -0.051461 ],
3388 [ -0.250268, 1.204414, 0.045854 ],
3389 [ -0.002079, 0.048952, 0.953127 ],
3390 ],
3391 cat16Inv: [
3392 [ 1.8620678550872327, -1.0112546305316843, 0.14918677544445175 ],
3393 [ 0.38752654323613717, 0.6214474419314753, -0.008973985167612518 ],
3394 [ -0.015841498849333856, -0.03412293802851557, 1.0499644368778496 ],
3395 ],
3396 m1: [
3397 [ 460.0, 451.0, 288.0 ],
3398 [ 460.0, -891.0, -261.0 ],
3399 [ 460.0, -220.0, -6300.0 ],
3400 ],
3401 };
3402
3403 const surroundMap = {
3404 dark: [0.8, 0.525, 0.8],
3405 dim: [0.9, 0.59, 0.9],
3406 average: [1, 0.69, 1],
3407 };
3408
3409 const hueQuadMap = {
3410 // Red, Yellow, Green, Blue, Red
3411 h: [20.14, 90.0, 164.25, 237.53, 380.14],
3412 e: [0.8, 0.7, 1.0, 1.2, 0.8],
3413 H: [0.0, 100.0, 200.0, 300.0, 400.0],
3414 };
3415
3416 const rad2deg = 180 / Math.PI;
3417 const deg2rad$1 = Math.PI / 180;
3418
3419 /**
3420 * @param {Coords} coords
3421 * @param {number} fl
3422 * @returns {[number, number, number]}
3423 */
3424 function adapt$1 (coords, fl) {
3425 const temp = /** @type {[number, number, number]} */ (
3426 coords.map(c => {
3427 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
3428 return (400 * copySign(x, c)) / (x + 27.13);
3429 })
3430 );
3431 return temp;
3432 }
3433
3434 /**
3435 * @param {Coords} adapted
3436 * @param {number} fl
3437 * @returns {[number, number, number]}
3438 */
3439 function unadapt (adapted, fl) {
3440 const constant = (100 / fl) * 27.13 ** adaptedCoefInv;
3441 return /** @type {[number, number, number]} */ (
3442 adapted.map(c => {
3443 const cabs = Math.abs(c);
3444 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
3445 })
3446 );
3447 }
3448
3449 /**
3450 * @param {number} h
3451 */
3452 function hueQuadrature (h) {
3453 let hp = constrain(h);
3454 if (hp <= hueQuadMap.h[0]) {
3455 hp += 360;
3456 }
3457
3458 const i = bisectLeft(hueQuadMap.h, hp) - 1;
3459 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
3460 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
3461 const Hi = hueQuadMap.H[i];
3462
3463 const t = (hp - hi) / ei;
3464 return Hi + (100 * t) / (t + (hii - hp) / eii);
3465 }
3466
3467 /**
3468 * @param {number} H
3469 */
3470 function invHueQuadrature (H) {
3471 let Hp = ((H % 400) + 400) % 400;
3472 const i = Math.floor(0.01 * Hp);
3473 Hp = Hp % 100;
3474 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
3475 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
3476
3477 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
3478 }
3479
3480 /**
3481 * @param {[number, number, number]} refWhite
3482 * @param {number} adaptingLuminance
3483 * @param {number} backgroundLuminance
3484 * @param {keyof typeof surroundMap} surround
3485 * @param {boolean} discounting
3486 * @returns {Cam16Environment}
3487 */
3488 function environment (
3489 refWhite,
3490 adaptingLuminance,
3491 backgroundLuminance,
3492 surround,
3493 discounting,
3494 ) {
3495 const env = {};
3496
3497 env.discounting = discounting;
3498 env.refWhite = refWhite;
3499 env.surround = surround;
3500 const xyzW = /** @type {Vector3} */ (
3501 refWhite.map(c => {
3502 return c * 100;
3503 })
3504 );
3505
3506 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
3507 env.la = adaptingLuminance;
3508 // The relative luminance of the nearby background
3509 env.yb = backgroundLuminance;
3510 // Absolute luminance of the reference white.
3511 const yw = xyzW[1];
3512
3513 // Cone response for reference white
3514 const rgbW = multiply_v3_m3x3(xyzW, M$a.cat16);
3515
3516 // Surround: dark, dim, and average
3517 let values = surroundMap[env.surround];
3518 const f = values[0];
3519 env.c = values[1];
3520 env.nc = values[2];
3521
3522 const k = 1 / (5 * env.la + 1);
3523 const k4 = k ** 4;
3524
3525 // Factor of luminance level adaptation
3526 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
3527 env.flRoot = env.fl ** 0.25;
3528
3529 env.n = env.yb / yw;
3530 env.z = 1.48 + Math.sqrt(env.n);
3531 env.nbb = 0.725 * env.n ** -0.2;
3532 env.ncb = env.nbb;
3533
3534 // Degree of adaptation calculating if not discounting
3535 // illuminant (assumed eye is fully adapted)
3536 const d = Math.max(Math.min(f * (1 - (1 / 3.6) * Math.exp((-env.la - 42) / 92)), 1), 0);
3537 env.dRgb = /** @type {[number, number, number]} */ (
3538 rgbW.map(c => {
3539 return interpolate(1, yw / c, d);
3540 })
3541 );
3542 env.dRgbInv = /** @type {[number, number, number]} */ (
3543 env.dRgb.map(c => {
3544 return 1 / c;
3545 })
3546 );
3547
3548 // Achromatic response
3549 const rgbCW = /** @type {[number, number, number]} */ (
3550 rgbW.map((c, i) => {
3551 return c * env.dRgb[i];
3552 })
3553 );
3554 const rgbAW = adapt$1(rgbCW, env.fl);
3555 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
3556
3557 // console.log(env);
3558
3559 return env;
3560 }
3561
3562 // Pre-calculate everything we can with the viewing conditions
3563 const viewingConditions$1 = environment(white$3, (64 / Math.PI) * 0.2, 20, "average", false);
3564
3565 /**
3566 * @param {Cam16Input} cam16
3567 * @param {Cam16Environment} env
3568 * @returns {[number, number, number]}
3569 */
3570 function fromCam16 (cam16, env) {
3571 // These check ensure one, and only one attribute for a
3572 // given category is provided.
3573 // @ts-expect-error The '^` operator is not allowed for boolean types
3574 if (!((cam16.J !== undefined) ^ (cam16.Q !== undefined))) {
3575 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
3576 }
3577
3578 // @ts-expect-error - The '^` operator is not allowed for boolean types
3579 if (!((cam16.C !== undefined) ^ (cam16.M !== undefined) ^ (cam16.s !== undefined))) {
3580 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
3581 }
3582
3583 // Hue is absolutely required
3584 // @ts-expect-error - The '^` operator is not allowed for boolean types
3585 if (!((cam16.h !== undefined) ^ (cam16.H !== undefined))) {
3586 throw new Error("Conversion requires one and only one: 'h' or 'H'");
3587 }
3588
3589 // Black
3590 if (cam16.J === 0.0 || cam16.Q === 0.0) {
3591 return [0.0, 0.0, 0.0];
3592 }
3593
3594 // Break hue into Cartesian components
3595 let hRad = 0.0;
3596 if (cam16.h !== undefined) {
3597 hRad = constrain(cam16.h) * deg2rad$1;
3598 }
3599 else {
3600 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
3601 }
3602
3603 const cosh = Math.cos(hRad);
3604 const sinh = Math.sin(hRad);
3605
3606 // Calculate `Jroot` from one of the lightness derived coordinates.
3607 let Jroot = 0.0;
3608 if (cam16.J !== undefined) {
3609 Jroot = spow(cam16.J, 1 / 2) * 0.1;
3610 }
3611 else if (cam16.Q !== undefined) {
3612 Jroot = (0.25 * env.c * cam16.Q) / ((env.aW + 4) * env.flRoot);
3613 }
3614
3615 // Calculate the `t` value from one of the chroma derived coordinates
3616 let alpha = 0.0;
3617 if (cam16.C !== undefined) {
3618 alpha = cam16.C / Jroot;
3619 }
3620 else if (cam16.M !== undefined) {
3621 alpha = cam16.M / env.flRoot / Jroot;
3622 }
3623 else if (cam16.s !== undefined) {
3624 alpha = (0.0004 * cam16.s ** 2 * (env.aW + 4)) / env.c;
3625 }
3626 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
3627
3628 // Eccentricity
3629 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
3630
3631 // Achromatic response
3632 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
3633
3634 // Calculate red-green and yellow-blue components
3635 const p1 = (5e4 / 13) * env.nc * env.ncb * et;
3636 const p2 = A / env.nbb;
3637 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
3638 const a = r * cosh;
3639 const b = r * sinh;
3640
3641 // Calculate back from cone response to XYZ
3642 const rgb_c = unadapt(
3643 /** @type {Vector3} */
3644 (
3645 multiply_v3_m3x3([p2, a, b], M$a.m1).map(c => {
3646 return (c * 1) / 1403;
3647 })
3648 ),
3649 env.fl,
3650 );
3651 return /** @type {Vector3} */ (
3652 multiply_v3_m3x3(
3653 /** @type {Vector3} */ (
3654 rgb_c.map((c, i) => {
3655 return c * env.dRgbInv[i];
3656 })
3657 ),
3658 M$a.cat16Inv,
3659 ).map(c => {
3660 return c / 100;
3661 })
3662 );
3663 }
3664
3665 /**
3666 * @param {[number, number, number]} xyzd65
3667 * @param {Cam16Environment} env
3668 * @returns {Cam16Object}
3669 */
3670 function toCam16 (xyzd65, env) {
3671 // Cone response
3672 const xyz100 = /** @type {Vector3} */ (
3673 xyzd65.map(c => {
3674 return c * 100;
3675 })
3676 );
3677 const rgbA = adapt$1(
3678 /** @type {[number, number, number]} */
3679 (
3680 multiply_v3_m3x3(xyz100, M$a.cat16).map((c, i) => {
3681 return c * env.dRgb[i];
3682 })
3683 ),
3684 env.fl,
3685 );
3686
3687 // Calculate hue from red-green and yellow-blue components
3688 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
3689 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
3690 const hRad = ((Math.atan2(b, a) % tau$1) + tau$1) % tau$1;
3691
3692 // Eccentricity
3693 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
3694
3695 const t =
3696 (5e4 / 13) *
3697 env.nc *
3698 env.ncb *
3699 zdiv(et * Math.sqrt(a ** 2 + b ** 2), rgbA[0] + rgbA[1] + 1.05 * rgbA[2] + 0.305);
3700 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
3701
3702 // Achromatic response
3703 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
3704
3705 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
3706
3707 // Lightness
3708 const J = 100 * spow(Jroot, 2);
3709
3710 // Brightness
3711 const Q = (4 / env.c) * Jroot * (env.aW + 4) * env.flRoot;
3712
3713 // Chroma
3714 const C = alpha * Jroot;
3715
3716 // Colorfulness
3717 const colorfulness = C * env.flRoot;
3718
3719 // Hue
3720 const h = constrain(hRad * rad2deg);
3721
3722 // Hue quadrature
3723 const H = hueQuadrature(h);
3724
3725 // Saturation
3726 const s = 50 * spow((env.c * alpha) / (env.aW + 4), 1 / 2);
3727
3728 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H});
3729
3730 return { J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H };
3731 }
3732
3733 // Provided as a way to directly evaluate the CAM16 model
3734 // https://observablehq.com/@jrus/cam16: reference implementation
3735 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
3736 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
3737 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
3738 // Results compared against: https://github.com/colour-science/colour
3739 var cam16 = new ColorSpace({
3740 id: "cam16-jmh",
3741 cssId: "--cam16-jmh",
3742 name: "CAM16-JMh",
3743 coords: {
3744 j: {
3745 refRange: [0, 100],
3746 name: "J",
3747 },
3748 m: {
3749 refRange: [0, 105.0],
3750 name: "Colorfulness",
3751 },
3752 h: {
3753 refRange: [0, 360],
3754 type: "angle",
3755 name: "Hue",
3756 },
3757 },
3758
3759 base: XYZ_D65,
3760
3761 M: M$a,
3762
3763 fromBase (xyz) {
3764 // If another derivation is created, ε could vary, so we can't hardcode
3765 if (this.ε === undefined) {
3766 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
3767 }
3768 const cam16 = toCam16(xyz, viewingConditions$1);
3769 const isAchromatic = Math.abs(cam16.M) < this.ε;
3770 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
3771 },
3772 toBase (cam16) {
3773 return fromCam16({ J: cam16[0], M: cam16[1], h: cam16[2] }, viewingConditions$1);
3774 },
3775 });
3776
3777 const white$2 = WHITES.D65;
3778 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
3779 const κ$3 = 24389 / 27; // 29^3/3^3
3780
3781 function toLstar (y) {
3782 // Convert XYZ Y to L*
3783
3784 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
3785 return 116.0 * fy - 16.0;
3786 }
3787
3788 function fromLstar (lstar) {
3789 // Convert L* back to XYZ Y
3790
3791 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
3792 }
3793
3794 function fromHct (coords, env) {
3795 // Use Newton's method to try and converge as quick as possible or
3796 // converge as close as we can. While the requested precision is achieved
3797 // most of the time, it may not always be achievable. Especially past the
3798 // visible spectrum, the algorithm will likely struggle to get the same
3799 // precision. If, for whatever reason, we cannot achieve the accuracy we
3800 // seek in the allotted iterations, just return the closest we were able to
3801 // get.
3802
3803 let [h, c, t] = coords;
3804 let xyz = [];
3805 let j = 0;
3806
3807 // Shortcut out for black
3808 if (t === 0) {
3809 return [0.0, 0.0, 0.0];
3810 }
3811
3812 // Calculate the Y we need to target
3813 let y = fromLstar(t);
3814
3815 // A better initial guess yields better results. Polynomials come from
3816 // curve fitting the T vs J response.
3817 if (t > 0) {
3818 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
3819 }
3820 else {
3821 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
3822 }
3823
3824 // Threshold of how close is close enough, and max number of attempts.
3825 // More precision and more attempts means more time spent iterating. Higher
3826 // required precision gives more accuracy but also increases the chance of
3827 // not hitting the goal. 2e-12 allows us to convert round trip with
3828 // reasonable accuracy of six decimal places or more.
3829 const threshold = 2e-12;
3830 const max_attempts = 15;
3831
3832 let attempt = 0;
3833 let last = Infinity;
3834 let best = [0, 0, 0];
3835
3836 // Try to find a J such that the returned y matches the returned y of the L*
3837 while (attempt <= max_attempts) {
3838 xyz = fromCam16({ J: j, C: c, h: h }, env);
3839
3840 // If we are within range, return XYZ
3841 // If we are closer than last time, save the values
3842 const delta = Math.abs(xyz[1] - y);
3843 if (delta < last) {
3844 if (delta <= threshold) {
3845 return xyz;
3846 }
3847 best = xyz;
3848 last = delta;
3849 }
3850
3851 // f(j_root) = (j ** (1 / 2)) * 0.1
3852 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
3853 // f(j_root) = Y = y / 100
3854 // f(j) = (y ** 2) / j - 1
3855 // f'(j) = (2 * y) / j
3856 j = j - ((xyz[1] - y) * j) / (2 * xyz[1]);
3857
3858 attempt += 1;
3859 }
3860
3861 // We could not acquire the precision we desired,
3862 // return our closest attempt.
3863 return best;
3864 }
3865
3866 function toHct (xyz, env) {
3867 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
3868
3869 const t = toLstar(xyz[1]);
3870 if (t === 0.0) {
3871 return [0.0, 0.0, 0.0];
3872 }
3873 const cam16 = toCam16(xyz, viewingConditions);
3874 return [constrain(cam16.h), cam16.C, t];
3875 }
3876
3877 // Pre-calculate everything we can with the viewing conditions
3878 const viewingConditions = environment(
3879 white$2,
3880 (200 / Math.PI) * fromLstar(50.0),
3881 fromLstar(50.0) * 100,
3882 "average",
3883 false,
3884 );
3885
3886 // https://material.io/blog/science-of-color-design
3887 // This is not a port of the material-color-utilities,
3888 // but instead implements the full color space as described,
3889 // combining CAM16 JCh and Lab D65. This does not clamp conversion
3890 // to HCT to specific chroma bands and provides support for wider
3891 // gamuts than Google currently supports and does so at a greater
3892 // precision (> 8 bits back to sRGB).
3893 // This implementation comes from https://github.com/facelessuser/coloraide
3894 // which is licensed under MIT.
3895 var hct = new ColorSpace({
3896 id: "hct",
3897 name: "HCT",
3898 coords: {
3899 h: {
3900 refRange: [0, 360],
3901 type: "angle",
3902 name: "Hue",
3903 },
3904 c: {
3905 refRange: [0, 145],
3906 name: "Colorfulness",
3907 },
3908 t: {
3909 refRange: [0, 100],
3910 name: "Tone",
3911 },
3912 },
3913
3914 base: XYZ_D65,
3915
3916 fromBase (xyz) {
3917 if (this.ε === undefined) {
3918 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
3919 }
3920 let hct = toHct(xyz);
3921 if (hct[1] < this.ε) {
3922 hct[1] = 0.0;
3923 hct[0] = null;
3924 }
3925 return hct;
3926 },
3927 toBase (hct) {
3928 return fromHct(hct, viewingConditions);
3929 },
3930 formats: {
3931 color: {
3932 id: "--hct",
3933 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
3934 },
3935 },
3936 });
3937
3938 const deg2rad = Math.PI / 180;
3939 const ucsCoeff = [1.0, 0.007, 0.0228];
3940
3941 /**
3942 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
3943 * @param {Coords} coords - HCT coordinates.
3944 * @return {number[]}
3945 */
3946 function convertUcsAb (coords) {
3947 // We want the distance between the actual color.
3948 // If chroma is negative, it will throw off our calculations.
3949 // Normally, converting back to the base and forward will correct it.
3950 // If we have a negative chroma after this, then we have a color that
3951 // cannot resolve to positive chroma.
3952 if (coords[1] < 0) {
3953 coords = hct.fromBase(hct.toBase(coords));
3954 }
3955
3956 // Only in extreme cases (usually outside the visible spectrum)
3957 // can the input value for log become negative.
3958 // Avoid domain error by forcing a zero result via "max" if necessary.
3959 const M =
3960 Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) /
3961 ucsCoeff[2];
3962 const hrad = coords[0] * deg2rad;
3963 const a = M * Math.cos(hrad);
3964 const b = M * Math.sin(hrad);
3965
3966 return [coords[2], a, b];
3967 }
3968
3969 /**
3970 * Color distance using HCT.
3971 * @param {import("../types.js").ColorTypes} color
3972 * @param {import("../types.js").ColorTypes} sample
3973 * @returns {number}
3974 */
3975 function deltaEHCT (color, sample) {
3976 [color, sample] = getColor([color, sample]);
3977
3978 let [t1, a1, b1] = convertUcsAb(hct.from(color));
3979 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
3980
3981 // Use simple euclidean distance with a and b using UCS conversion
3982 // and LCh lightness (HCT tone).
3983 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
3984 }
3985
3986 /**
3987 * Helmlab MetricSpace — 13-stage perceptual color space.
3988 *
3989 * A data-driven analytical color space fit on COMBVD (3,813 paired human
3990 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
3991 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
3992 * color space `helmlab-metric` for inspectability. Its coordinate system
3993 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
3994 * from origin) is shaped for ΔE accuracy rather than author-facing
3995 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
3996 *
3997 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
3998 *
3999 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
4000 * → hue-dep chroma scale → chroma power → L-dep chroma scale
4001 * → HLC interaction → hue-dep lightness → rotation
4002 *
4003 * Reference: arXiv:2602.23010
4004 * @see https://github.com/Grkmyldz148/helmlab
4005 */
4006
4007 /** @import { Matrix3x3 } from "../types.js" */
4008
4009 const {cos, sin, sqrt, atan2, exp, abs, pow, PI} = Math;
4010
4011 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
4012 /** @type {Matrix3x3} */
4013 // prettier-ignore
4014 const CAT_TO_HELM = [
4015 [1.000042977349746, 2.0718877053183e-05, -4.361018085669474e-05],
4016 [2.6946201090235744e-05, 0.9999906145080147, -1.4898828405401079e-05],
4017 [-7.941753620756204e-06, 1.2875204405137254e-05, 0.9997859822609763],
4018 ];
4019
4020 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
4021 /** @type {Matrix3x3} */
4022 // prettier-ignore
4023 const CAT_FROM_HELM = [
4024 [0.9999570254019492, -2.071874272730964e-05, 4.361733292468361e-05],
4025 [-2.694517763358666e-05, 1.000009385946497, 1.490098223546482e-05],
4026 [7.943459292954202e-06, -1.287824596735154e-05, 1.000214063706999],
4027 ];
4028
4029 // ── Utility functions ──────────────────────────────────────────────
4030
4031 // ── Core parameters (v21, 72 params) ──────────────────────────────
4032
4033 /** @type {Matrix3x3} */
4034 // prettier-ignore
4035 const M1 = [
4036 [ 0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377],
4037 [ -0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503],
4038 [ -0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842],
4039 ];
4040 /** @type {Matrix3x3} */
4041 // prettier-ignore
4042 const M1_INV = [
4043 [ 1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302],
4044 [ 0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689],
4045 [ -0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399],
4046 ];
4047
4048 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
4049 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
4050
4051 /** @type {Matrix3x3} */
4052 // prettier-ignore
4053 const M2 = [
4054 [ -0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335],
4055 [ 1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590],
4056 [ 0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967],
4057 ];
4058 /** @type {Matrix3x3} */
4059 // prettier-ignore
4060 const M2_INV = [
4061 [ 0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038],
4062 [ 1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853],
4063 [ 1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097],
4064 ];
4065
4066 /** Matrices used by this color space, also available as `Helmlab.M` */
4067 const M$9 = { CAT_TO_HELM, CAT_FROM_HELM, M1, M1_INV, M2, M2_INV };
4068
4069 // Enrichment parameters
4070 const hue_cos1 = -0.02833024015436984, hue_sin1 = -0.21131429516166544;
4071 const hue_cos2 = 0.2189784817615645, hue_sin2 = -0.06871898981942523;
4072 const hue_cos3 = 0.005506053349515315, hue_sin3 = -0.0641329861299175;
4073 const hue_cos4 = -0.053592461436994296, hue_sin4 = -0.00954137464208059;
4074
4075 const hk_weight = 0.2676231133101982, hk_power = 0.8934892185255707;
4076 const hk_hue_mod = 0.7173169828841472;
4077 const hk_sin1 = 0.6915224124600773, hk_cos2 = 0.48647127559605596, hk_sin2 = 0.9853124591201782;
4078
4079 const L_corr_p1 = 0.5385456675962418, L_corr_p2 = 0.12508858146241716, L_corr_p3 = 0.6768950256217603;
4080 const Lh_cos1 = -0.4963251525324449, Lh_sin1 = -0.09564696283240552;
4081
4082 const lp_dark = -0.029053748937210654, lp_dark_hcos = 1.3346761652952872, lp_dark_hsin = -0.1698908144723919;
4083
4084 const cs_cos1 = -0.195370576218515, cs_sin1 = 0.5330819227283227;
4085 const cs_cos2 = 0.08863325582067766, cs_sin2 = 0.9365540137751136;
4086 const cs_cos3 = 0.13789738139719568, cs_sin3 = 0.061650260197979936;
4087 const cs_cos4 = 0.0641970862504494, cs_sin4 = -0.027401052793571013;
4088
4089 const cp_cos1 = -0.09900209889026965, cp_sin1 = 0.059635520647228726;
4090 const cp_cos2 = -0.013586499967803128, cp_sin2 = 0.2253393118474472;
4091
4092 const lc1 = -1.5239477450767043, lc2 = -1.751157310240011;
4093
4094 const hlc_cos1 = -0.43576378069144767, hlc_sin1 = 1.060094063845983;
4095 const hlc_cos2 = 0.47931193034584496, hlc_sin2 = -0.2622579649434462;
4096
4097 const hl_cos1 = 0.13610794232685908, hl_sin1 = 0.1168702235362288;
4098 const hl_cos2 = -0.01617739641422492, hl_sin2 = 0.038145638815030566;
4099
4100 // Rigid rotation φ = −28.2°
4101 const PHI = -28.2 * PI / 180;
4102 const ROT_COS = cos(PHI);
4103 const ROT_SIN = sin(PHI);
4104
4105 // ── Pipeline helper functions ──────────────────────────────────────
4106
4107 function hueDelta (h) {
4108 return hue_cos1 * cos(h) + hue_sin1 * sin(h) +
4109 hue_cos2 * cos(2 * h) + hue_sin2 * sin(2 * h) +
4110 hue_cos3 * cos(3 * h) + hue_sin3 * sin(3 * h) +
4111 hue_cos4 * cos(4 * h) + hue_sin4 * sin(4 * h);
4112 }
4113
4114 function hueDeltaDeriv (h) {
4115 return -hue_cos1 * sin(h) + hue_sin1 * cos(h) +
4116 -2 * hue_cos2 * sin(2 * h) + 2 * hue_sin2 * cos(2 * h) +
4117 -3 * hue_cos3 * sin(3 * h) + 3 * hue_sin3 * cos(3 * h) +
4118 -4 * hue_cos4 * sin(4 * h) + 4 * hue_sin4 * cos(4 * h);
4119 }
4120
4121 function chromaScaleH (h) {
4122 let logS = cs_cos1 * cos(h) + cs_sin1 * sin(h) +
4123 cs_cos2 * cos(2 * h) + cs_sin2 * sin(2 * h) +
4124 cs_cos3 * cos(3 * h) + cs_sin3 * sin(3 * h) +
4125 cs_cos4 * cos(4 * h) + cs_sin4 * sin(4 * h);
4126 return exp(logS);
4127 }
4128
4129 function lChromaScale (L) {
4130 let dL = L - 0.5;
4131 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
4132 }
4133
4134 function hlcScale (h, L) {
4135 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) +
4136 hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
4137 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
4138 }
4139
4140 function hueLightnessScale (h) {
4141 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) +
4142 hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
4143 return exp(logS);
4144 }
4145
4146 function chromaPowerH (h) {
4147 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) +
4148 cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
4149 }
4150
4151 function lCorrectFwd (L, h) {
4152 let t = L * (1 - L);
4153 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
4154 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
4155 return result;
4156 }
4157
4158 function lCorrectInv (L1, h) {
4159 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
4160 let L = L1;
4161 for (let i = 0; i < 15; i++) {
4162 let t = L * (1 - L);
4163 let dt = 1 - 2 * L;
4164 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) +
4165 L_corr_p3 * t * t - L1;
4166 let dfdL = 1 + (L_corr_p1 + Lh) * dt +
4167 L_corr_p2 * (dt * (0.5 - L) - t) +
4168 L_corr_p3 * 2 * t * dt;
4169 if (abs(dfdL) < 1e-10) {
4170 dfdL = 1;
4171 }
4172 L -= f / dfdL;
4173 }
4174 return L;
4175 }
4176
4177 function darkLFwd (L, h) {
4178 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
4179 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
4180 let g = coeff * L * oml * oml;
4181 return L * exp(clamp(-30, g, 30));
4182 }
4183
4184 function darkLInv (Ln, h) {
4185 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
4186 let L = Ln;
4187 for (let i = 0; i < 12; i++) {
4188 let oml = L < 1 ? 1 - L : 0;
4189 let g = coeff * L * oml * oml;
4190 let eg = exp(clamp(-30, g, 30));
4191 let f = L * eg - Ln;
4192 let gp = coeff * oml * (1 - 3 * L);
4193 let fp = eg * (1 + L * gp);
4194 if (abs(fp) < 1e-10) {
4195 fp = 1;
4196 }
4197 L -= f / fp;
4198 }
4199 return L;
4200 }
4201
4202 // ── Color space definition ─────────────────────────────────────────
4203 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
4204 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
4205 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
4206 // not author convenience. As a result:
4207 // - the ab plane is asymmetric (the metric was fit to directionally
4208 // asymmetric human discrimination thresholds);
4209 // - the L axis exceeds 1 for highly chromatic colors because the
4210 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
4211 // appear brighter than equiluminant neutrals);
4212 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
4213 // slightly off-origin in this coordinate system. Distance is
4214 // translation-invariant, so this does not affect ΔE quality.
4215 //
4216 // For CSS-author-facing color authoring (palettes, gradients, gamut
4217 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
4218 // is exposed primarily so the metric forward is inspectable for
4219 // debugging, color-science exploration, and as the internal forward used
4220 // by `deltaEHelmlab`.
4221
4222 const fromXYZ = function (xyz) {
4223 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
4224 let adapted = multiply_v3_m3x3(xyz, M$9.CAT_TO_HELM);
4225
4226 // Stage 1: XYZ → LMS (M1)
4227 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M$9.M1);
4228
4229 // Stage 2: Power compression (signed)
4230 let c0 = spow(lms0, GAMMA[0]);
4231 let c1 = spow(lms1, GAMMA[1]);
4232 let c2 = spow(lms2, GAMMA[2]);
4233
4234 // Stage 3: LMS_c → Lab_raw (M2)
4235 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$9.M2);
4236
4237 // Stage 3.5: Hue correction (4-harmonic Fourier)
4238 let h = atan2(b, a);
4239 let C = sqrt(a * a + b * b);
4240 let delta = hueDelta(h);
4241 let hNew = h + delta;
4242 a = C * cos(hNew);
4243 b = C * sin(hNew);
4244
4245 // Stage 3.7: Helmholtz-Kohlrausch correction
4246 let Cr = sqrt(a * a + b * b);
4247 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
4248 let hr = atan2(b, a);
4249 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) +
4250 hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
4251 L += hkBoost * factor;
4252
4253 // Stage 4: Cubic L correction (with hue modulation)
4254 h = atan2(b, a);
4255 L = lCorrectFwd(L, h);
4256
4257 // Stage 4.5: Dark L compression
4258 h = atan2(b, a);
4259 L = darkLFwd(L, h);
4260
4261 // Stage 5: Hue-dependent chroma scaling
4262 h = atan2(b, a);
4263 let cs = chromaScaleH(h);
4264 a *= cs;
4265 b *= cs;
4266
4267 // Stage 5.5: Nonlinear chroma power
4268 h = atan2(b, a);
4269 C = sqrt(a * a + b * b);
4270 let p = chromaPowerH(h);
4271 let Cn = C > 0 ? pow(C, p) : 0;
4272 a = Cn * cos(h);
4273 b = Cn * sin(h);
4274
4275 // Stage 6: L-dependent chroma scaling
4276 let T = lChromaScale(L);
4277 a *= T;
4278 b *= T;
4279
4280 // Stage 6.5: HLC interaction
4281 h = atan2(b, a);
4282 let hlcS = hlcScale(h, L);
4283 a *= hlcS;
4284 b *= hlcS;
4285
4286 // Stage 8: Hue-dependent lightness scaling
4287 h = atan2(b, a);
4288 L *= hueLightnessScale(h);
4289
4290 // Stage 11: Rigid rotation (φ = −28.2°)
4291 let aRot = a * ROT_COS - b * ROT_SIN;
4292 let bRot = a * ROT_SIN + b * ROT_COS;
4293
4294 return [L, aRot, bRot];
4295 };
4296
4297 const toXYZ = function (lab) {
4298 let [L, a, b] = lab;
4299
4300 // Undo Stage 11: rotation
4301 let aUn = a * ROT_COS + b * ROT_SIN;
4302 let bUn = -a * ROT_SIN + b * ROT_COS;
4303 a = aUn;
4304 b = bUn;
4305
4306 // Undo Stage 8: hue-dep lightness
4307 let h = atan2(b, a);
4308 L /= hueLightnessScale(h);
4309
4310 // Undo Stage 6.5: HLC
4311 h = atan2(b, a);
4312 let hlcS = hlcScale(h, L);
4313 a /= hlcS;
4314 b /= hlcS;
4315
4316 // Undo Stage 6: L-dep chroma
4317 let T = lChromaScale(L);
4318 a /= T;
4319 b /= T;
4320
4321 // Undo Stage 5.5: chroma power
4322 h = atan2(b, a);
4323 let C = sqrt(a * a + b * b);
4324 let p = chromaPowerH(h);
4325 let Co = C > 0 ? pow(C, 1 / p) : 0;
4326 a = Co * cos(h);
4327 b = Co * sin(h);
4328
4329 // Undo Stage 5: chroma scaling
4330 h = atan2(b, a);
4331 let cs = chromaScaleH(h);
4332 a /= cs;
4333 b /= cs;
4334
4335 // Undo Stage 4.5: dark L
4336 h = atan2(b, a);
4337 L = darkLInv(L, h);
4338
4339 // Undo Stage 4: cubic L
4340 h = atan2(b, a);
4341 L = lCorrectInv(L, h);
4342
4343 // Undo Stage 3.7: H-K
4344 let Cr = sqrt(a * a + b * b);
4345 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
4346 let hr = atan2(b, a);
4347 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) +
4348 hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
4349 L -= hkBoost * factor;
4350
4351 // Undo Stage 3.5: hue correction (Newton iteration)
4352 let hOut = atan2(b, a);
4353 C = sqrt(a * a + b * b);
4354 let hRaw = hOut;
4355 for (let i = 0; i < 8; i++) {
4356 let f = hRaw + hueDelta(hRaw) - hOut;
4357 let fp = 1 + hueDeltaDeriv(hRaw);
4358 if (abs(fp) < 1e-10) {
4359 fp = 1;
4360 }
4361 hRaw -= f / fp;
4362 }
4363 a = C * cos(hRaw);
4364 b = C * sin(hRaw);
4365
4366 // Undo Stage 3: Lab → LMS_c (M2_inv)
4367 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$9.M2_INV);
4368
4369 // Undo Stage 2: power compression
4370 let l0 = spow(lc0, INV_GAMMA[0]);
4371 let l1 = spow(lc1, INV_GAMMA[1]);
4372 let l2 = spow(lc2, INV_GAMMA[2]);
4373
4374 // Undo Stage 1: LMS → XYZ (M1_inv)
4375 let xyz = multiply_v3_m3x3([l0, l1, l2], M$9.M1_INV);
4376
4377 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
4378 return multiply_v3_m3x3(xyz, M$9.CAT_FROM_HELM);
4379 };
4380
4381 var helmlab = new ColorSpace({
4382 id: "helmlab-metric",
4383 name: "Helmlab MetricSpace",
4384 cssId: "--helmlab-metric",
4385 coords: {
4386 l: {
4387 refRange: [0, 1.6],
4388 name: "Lightness",
4389 },
4390 a: {
4391 refRange: [-1.5, 1.5],
4392 },
4393 b: {
4394 refRange: [-1.5, 1.5],
4395 },
4396 },
4397 white: "D65",
4398 base: XYZ_D65,
4399 M: M$9,
4400 fromBase (xyz) {
4401 return fromXYZ(xyz);
4402 },
4403 toBase (lab) {
4404 return toXYZ(lab);
4405 },
4406 });
4407
4408 // Helmlab MetricSpace weighted distance (v21, 72 params).
4409 // Optimized on COMBVD human color-difference judgments.
4410 //
4411 // Formula:
4412 // SL = 1 + sl * (L_avg - 0.5)²
4413 // SC = 1 + sc * C_avg
4414 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
4415 // compressed = raw / (1 + c * raw)
4416 // ΔE = compressed ^ q
4417
4418 const sl = -0.9155125151657894;
4419 const sc = 2.9268353744941558;
4420 const wC = 3.966003089807536;
4421 const p = 1.9737081170404969;
4422 const compress = 52.473130649294724;
4423 const q = 0.47897301074925214;
4424
4425 /**
4426 * @param {import("../types.js").ColorTypes} color
4427 * @param {import("../types.js").ColorTypes} sample
4428 * @returns {number}
4429 */
4430 function deltaEHelmlab (color, sample) {
4431 [color, sample] = getColor([color, sample]);
4432
4433 let [L1, a1, b1] = helmlab.from(color);
4434 let [L2, a2, b2] = helmlab.from(sample);
4435
4436 let ΔL = L1 - L2;
4437 let Δa = a1 - a2;
4438 let Δb = b1 - b2;
4439
4440 // Pair-dependent weighting
4441 let Lavg = (L1 + L2) * 0.5;
4442 let SL = 1 + sl * (Lavg - 0.5) ** 2;
4443
4444 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
4445 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
4446 let Cavg = (C1 + C2) * 0.5;
4447 let SC = 1 + sc * Cavg;
4448
4449 // Weighted Minkowski distance
4450 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
4451
4452 // Monotonic compression
4453 let compressed = raw / (1 + compress * raw);
4454
4455 return compressed ** q;
4456 }
4457
4458 /**
4459 * @packageDocumentation
4460 * This module defines all the builtin deltaE methods.
4461 */
4462
4463 var deltaEMethods = {
4464 deltaE76,
4465 deltaECMC,
4466 deltaE2000,
4467 deltaEJz,
4468 deltaEITP,
4469 deltaEOK,
4470 deltaEOK2,
4471 deltaEHCT,
4472 deltaEHelmlab,
4473 };
4474
4475 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
4476
4477 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
4478
4479 // Type re-exports
4480 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
4481
4482 /**
4483 * Calculate the epsilon to 2 degrees smaller than the specified JND.
4484 * @param {number} jnd The target "just noticeable difference".
4485 * @returns {number}
4486 */
4487 function calcEpsilon (jnd) {
4488 // Calculate the epsilon to 2 degrees smaller than the specified JND.
4489
4490 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
4491 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
4492 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
4493 }
4494
4495 const GMAPPRESET = {
4496 hct: {
4497 method: "hct.c",
4498 jnd: 2,
4499 deltaEMethod: "hct",
4500 blackWhiteClamp: {},
4501 },
4502 "hct-tonal": {
4503 method: "hct.c",
4504 jnd: 0,
4505 deltaEMethod: "hct",
4506 blackWhiteClamp: { channel: "hct.t", min: 0, max: 100 },
4507 },
4508 };
4509
4510 /**
4511 * Force coordinates to be in gamut of a certain color space.
4512 * Mutates the color it is passed.
4513 * @overload
4514 * @param {ColorTypes} color
4515 * @param {ToGamutOptions} [options]
4516 * @returns {PlainColorObject}
4517 */
4518 /**
4519 * @overload
4520 * @param {ColorTypes} color
4521 * @param {string} [space]
4522 * @returns {PlainColorObject}
4523 */
4524 /**
4525 * @param {ColorTypes} color
4526 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
4527 * @returns {PlainColorObject}
4528 */
4529 function toGamut (
4530 color,
4531 {
4532 method = defaults.gamut_mapping,
4533 space = undefined,
4534 deltaEMethod = "",
4535 jnd = 2,
4536 blackWhiteClamp = undefined,
4537 } = {},
4538 ) {
4539 color = getColor(color);
4540
4541 if (isString(arguments[1])) {
4542 space = arguments[1];
4543 }
4544 else if (!space) {
4545 space = color.space;
4546 }
4547
4548 space = ColorSpace.get(space);
4549
4550 // 3 spaces:
4551 // color.space: current color space
4552 // space: space whose gamut we are mapping to
4553 // mapSpace: space with the coord we're reducing
4554
4555 if (inGamut(color, space, { epsilon: 0 })) {
4556 return /** @type {PlainColorObject} */ (color);
4557 }
4558
4559 let spaceColor;
4560 if (method === "css") {
4561 spaceColor = toGamutCSS(color, { space });
4562 }
4563 else if (method === "raytrace") {
4564 spaceColor = toGamutRayTrace(color, { space });
4565 }
4566 else {
4567 if (method !== "clip") {
4568 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
4569 ({ method, jnd, deltaEMethod, blackWhiteClamp } = GMAPPRESET[method]);
4570 }
4571
4572 // Get the correct delta E method
4573 let de = deltaE2000;
4574 if (deltaEMethod !== "") {
4575 for (let m in deltaEMethods) {
4576 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
4577 de = deltaEMethods[m];
4578 break;
4579 }
4580 }
4581 }
4582
4583 if (jnd === 0) {
4584 jnd = 1e-16;
4585 }
4586
4587 let clipped = toGamut(to(color, space), { method: "clip", space });
4588 if (de(color, clipped) > jnd) {
4589 // Clamp to SDR white and black if required
4590 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
4591 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
4592 let channel = get(to(color, channelMeta.space), channelMeta.id);
4593 if (isNone(channel)) {
4594 channel = 0;
4595 }
4596 if (channel >= blackWhiteClamp.max) {
4597 return to({ space: "xyz-d65", coords: WHITES["D65"] }, color.space);
4598 }
4599 else if (channel <= blackWhiteClamp.min) {
4600 return to({ space: "xyz-d65", coords: [0, 0, 0] }, color.space);
4601 }
4602 }
4603
4604 // Reduce a coordinate of a certain color space until the color is in gamut
4605 let coordMeta = ColorSpace.resolveCoord(method);
4606 let mapSpace = coordMeta.space;
4607 let coordId = coordMeta.id;
4608
4609 let mappedColor = to(color, mapSpace);
4610 // If we were already in the mapped color space, we need to resolve undefined channels
4611 mappedColor.coords.forEach((c, i) => {
4612 if (isNone(c)) {
4613 mappedColor.coords[i] = 0;
4614 }
4615 });
4616 let bounds = coordMeta.range || coordMeta.refRange;
4617 let min = bounds[0];
4618 let ε = calcEpsilon(jnd);
4619 let low = min;
4620 let high = get(mappedColor, coordId);
4621
4622 while (high - low > ε) {
4623 let clipped = clone(mappedColor);
4624 clipped = toGamut(clipped, { space, method: "clip" });
4625 let deltaE = de(mappedColor, clipped);
4626
4627 if (deltaE - jnd < ε) {
4628 low = get(mappedColor, coordId);
4629 }
4630 else {
4631 high = get(mappedColor, coordId);
4632 }
4633
4634 set(mappedColor, coordId, (low + high) / 2);
4635 }
4636
4637 spaceColor = to(mappedColor, space);
4638 }
4639 else {
4640 spaceColor = clipped;
4641 }
4642 }
4643 else {
4644 spaceColor = to(color, space);
4645 }
4646
4647 if (
4648 method === "clip" || // Dumb coord clipping
4649 // finish off smarter gamut mapping with clip to get rid of ε, see #17
4650 !inGamut(spaceColor, space, { epsilon: 0 })
4651 ) {
4652 let bounds = Object.values(space.coords).map(c => c.range || []);
4653
4654 spaceColor.coords = /** @type {[number, number, number]} */ (
4655 spaceColor.coords.map((c, i) => {
4656 let [min, max] = bounds[i];
4657
4658 if (min !== undefined) {
4659 c = Math.max(min, c);
4660 }
4661
4662 if (max !== undefined) {
4663 c = Math.min(c, max);
4664 }
4665
4666 return c;
4667 })
4668 );
4669 }
4670 }
4671
4672 if (space !== color.space) {
4673 spaceColor = to(spaceColor, color.space);
4674 }
4675
4676 color.coords = spaceColor.coords;
4677 return /** @type {PlainColorObject} */ (color);
4678 }
4679
4680 /** @type {"color"} */
4681 toGamut.returns = "color";
4682
4683 /**
4684 * The reference colors to be used if lightness is out of the range 0-1 in the
4685 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
4686 * DeltaEOK calculation, so it is guaranteed to be imported.
4687 * @satisfies {Record<string, ColorTypes>}
4688 */
4689 const COLORS = {
4690 WHITE: { space: Oklab, coords: [1, 0, 0], alpha: 1 },
4691 BLACK: { space: Oklab, coords: [0, 0, 0], alpha: 1 },
4692 };
4693
4694 /**
4695 * Given a color `origin`, returns a new color that is in gamut using
4696 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
4697 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
4698 * returned in the color space of `origin`.
4699 * @param {ColorTypes} origin
4700 * @param {{ space?: string | ColorSpace | undefined }} options
4701 * @returns {PlainColorObject}
4702 */
4703 function toGamutCSS (origin, { space } = {}) {
4704 const JND = 0.02;
4705 const ε = 0.0001;
4706
4707 origin = getColor(origin);
4708
4709 if (!space) {
4710 space = origin.space;
4711 }
4712
4713 space = ColorSpace.get(space);
4714
4715 if (space.isUnbounded) {
4716 return to(origin, space);
4717 }
4718
4719 const origin_OKLCH = to(origin, OKLCH);
4720 let L = origin_OKLCH.coords[0];
4721
4722 // return media white or black, if lightness is out of range
4723 if (L >= 1) {
4724 const white = to(COLORS.WHITE, space);
4725 white.alpha = origin.alpha;
4726 return to(white, space);
4727 }
4728 if (L <= 0) {
4729 const black = to(COLORS.BLACK, space);
4730 black.alpha = origin.alpha;
4731 return to(black, space);
4732 }
4733
4734 if (inGamut(origin_OKLCH, space, { epsilon: 0 })) {
4735 return to(origin_OKLCH, space);
4736 }
4737
4738 function clip (_color) {
4739 const destColor = to(_color, space);
4740 const spaceCoords = Object.values(/** @type {ColorSpace} */ (space).coords);
4741 destColor.coords = /** @type {[number, number, number]} */ (
4742 destColor.coords.map((coord, index) => {
4743 if ("range" in spaceCoords[index]) {
4744 const [min, max] = spaceCoords[index].range;
4745 return clamp(min, coord, max);
4746 }
4747 return coord;
4748 })
4749 );
4750 return destColor;
4751 }
4752 let min = 0;
4753 let max = origin_OKLCH.coords[1];
4754 let min_inGamut = true;
4755 let current = clone(origin_OKLCH);
4756 let clipped = clip(current);
4757
4758 let E = deltaEOK(clipped, current);
4759 if (E < JND) {
4760 return clipped;
4761 }
4762
4763 while (max - min > ε) {
4764 const chroma = (min + max) / 2;
4765 current.coords[1] = chroma;
4766 if (min_inGamut && inGamut(current, space, { epsilon: 0 })) {
4767 min = chroma;
4768 }
4769 else {
4770 clipped = clip(current);
4771 E = deltaEOK(clipped, current);
4772 if (E < JND) {
4773 if (JND - E < ε) {
4774 break;
4775 }
4776 else {
4777 min_inGamut = false;
4778 min = chroma;
4779 }
4780 }
4781 else {
4782 max = chroma;
4783 }
4784 }
4785 }
4786 return clipped;
4787 }
4788
4789 /**
4790 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
4791 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
4792 * @param {[number, number, number]} start
4793 * @param {[number, number, number]} end
4794 * @param {[number, number, number]} bmin
4795 * @param {[number, number, number]} bmax
4796 * @returns {[number, number, number] | []}
4797 */
4798 function raytrace_box (start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
4799 // Use slab method to detect intersection of ray and box and return intersect.
4800 // https://en.wikipedia.org/wiki/Slab_method
4801
4802 // Calculate whether there was a hit
4803 let tfar = Infinity;
4804 let tnear = -Infinity;
4805 let direction = [];
4806
4807 for (let i = 0; i < 3; i++) {
4808 const a = start[i];
4809 const b = end[i];
4810 const d = b - a;
4811 const bn = bmin[i];
4812 const bx = bmax[i];
4813 direction.push(d);
4814
4815 // Non parallel cases
4816 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types
4817 if (Math.abs(d) > 1e-12) {
4818 const inv_d = 1 / d;
4819 const t1 = (bn - a) * inv_d;
4820 const t2 = (bx - a) * inv_d;
4821 tnear = Math.max(Math.min(t1, t2), tnear);
4822 tfar = Math.min(Math.max(t1, t2), tfar);
4823 }
4824
4825 // Impossible parallel case
4826 else if (a < bn || a > bx) {
4827 return [];
4828 }
4829 }
4830
4831 // No hit
4832 if (tnear > tfar || tfar < 0) {
4833 return [];
4834 }
4835
4836 // Favor the intersection first in the direction start -> end
4837 if (tnear < 0) {
4838 tnear = tfar;
4839 }
4840
4841 // A point, or something approaching a single point where start and end are the same.
4842 if (!isFinite(tnear)) {
4843 return [];
4844 }
4845
4846 // Calculate nearest intersection via interpolation
4847 return [
4848 start[0] + direction[0] * tnear,
4849 start[1] + direction[1] * tnear,
4850 start[2] + direction[2] * tnear,
4851 ];
4852 }
4853
4854 /**
4855 * Given a color `origin`, returns a new color that is in gamut using
4856 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
4857 * it will be in gamut `space`, and returned in `space`. Otherwise,
4858 * it will be in gamut and returned in the color space of `origin`.
4859 * @param {ColorTypes} origin
4860 * @param {{ space?: string | ColorSpace | undefined }} options
4861 * @returns {PlainColorObject}
4862 */
4863 function toGamutRayTrace (origin, { space } = {}) {
4864 origin = getColor(origin);
4865
4866 if (!space) {
4867 space = origin.space;
4868 }
4869
4870 space = ColorSpace.get(space);
4871
4872 // If the space is already in gamut, stop.
4873 if (space.isUnbounded) {
4874 return to(origin, space);
4875 }
4876
4877 // Get the OkLCh coordinates.
4878 let oklchOrigin = to(origin, OKLCH);
4879 let [lightness, chroma, hue] = oklchOrigin.coords;
4880
4881 // Return white or black if color's lightness exceeds the SDR range.
4882 if (lightness >= 1) {
4883 const white = to(COLORS.WHITE, space);
4884 white.alpha = origin.alpha;
4885 return to(white, space);
4886 }
4887 else if (lightness <= 0) {
4888 const black = to(COLORS.BLACK, space);
4889 black.alpha = origin.alpha;
4890 return to(black, space);
4891 }
4892
4893 // Get a copy of the origin color as the RGB target space.
4894 const originSpace = space;
4895 const rGamut = space.rgbGamut;
4896 if (rGamut !== undefined) {
4897 space = rGamut;
4898 }
4899
4900 if (!isInstance(space, RGBColorSpace)) {
4901 throw Error('An RGB gamut is required')
4902 }
4903
4904 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
4905 let [mn, mx] = Object.values(space.coords)[0].range;
4906 let max = /** @type {[number, number, number]} */ ([mx, mx, mx]);
4907
4908 // See if we have a linear version of the color space
4909 const lGamut = space.linearGamut;
4910 if (lGamut !== undefined) {
4911 // Recalculate minimum and maximum relative to the linear space
4912 let temp = to({ space: space, coords: max, alpha: origin.alpha }, lGamut);
4913 mx = temp.coords[0];
4914 max = /** @type {[number, number, number]} */ ([mx, mx, mx]);
4915 space = lGamut;
4916 mn = Object.values(space.coords)[0].range[0];
4917 }
4918 let min = /** @type {[number, number, number]} */ ([mn, mn, mn]);
4919 let rgbOrigin = to(oklchOrigin, space);
4920
4921 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
4922 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
4923 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
4924 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
4925 let anchor = to({ space: OKLCH, coords: [lightness, 0, hue] }, space).coords;
4926
4927 // Calculate bounds to adjust the anchor closer to the gamut surface.
4928 // We don't want to make the ray too short, so offset some amount from the low and high range.
4929 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types.
4930 const low = mn + 1e-12;
4931 const high = mx - 1e-12;
4932
4933 // Cast a ray from the zero chroma color to the target color.
4934 // Trace the line to the RGB cube edge and find where it intersects.
4935 // Correct L and h within the perceptual OkLCh after each attempt.
4936 let last = rgbOrigin.coords;
4937 for (let i = 0; i < 4; i++) {
4938 if (i) {
4939 // For constant luminance, we correct the color by simply setting lightness and hue to
4940 // match the original color. In a non constant luminance reduction, it is better to
4941 // project the color onto the reduction path vector.
4942 const oklchColor = to(rgbOrigin, OKLCH);
4943 oklchColor.coords[0] = lightness;
4944 oklchColor.coords[2] = hue;
4945 rgbOrigin = to(oklchColor, space);
4946 }
4947 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
4948 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
4949
4950 // If we cannot find an intersection, reset to last successful iteration of the color.
4951 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
4952 if (intersection.length === 0) {
4953 rgbOrigin.coords = [...last];
4954 break;
4955 }
4956
4957 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
4958 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
4959 anchor = [...rgbOrigin.coords];
4960 }
4961
4962 // If we have an intersection, update the color.
4963 last = /** @type {[number, number, number]} */ (intersection);
4964 rgbOrigin.coords = [...intersection];
4965 }
4966 }
4967
4968 // Convert to the original, specified gamut
4969 rgbOrigin = to(rgbOrigin, originSpace);
4970 const spaceCoords = Object.values(/** @type {ColorSpace} */ (originSpace).coords);
4971
4972 // Remove noise from floating point math by clipping
4973 rgbOrigin.coords = /** @type {[number, number, number]} */ (
4974 rgbOrigin.coords.map((coord, index) => {
4975 if ("range" in spaceCoords[index]) {
4976 const [lower, upper] = spaceCoords[index].range;
4977 return clamp(lower, coord, upper);
4978 }
4979 return coord;
4980 })
4981 );
4982
4983 return rgbOrigin;
4984 }
4985
4986 /** @import { SpaceOptions } from "./ColorSpace.js" */
4987
4988 /**
4989 * A color space whose chroma-like coordinate is expressed relative to an RGB gamut: chroma = 1 is
4990 * the most colorful in-gamut color for the rest of the coordinates, so any chroma in [0, 1] stays
4991 * in gamut. The reduced coordinate (`chroma`, default `"c"`) is rescaled against `gamutSpace`; every
4992 * other coordinate is inherited unchanged from `base`. Works for any base whose chroma coordinate
4993 * brings the color into gamut as it is reduced (e.g. OKLCh, LCH).
4994 */
4995 class GamutRelativeColorSpace extends ColorSpace {
4996 /**
4997 * @param {SpaceOptions & { gamutSpace: string | ColorSpace, chroma?: string }} options
4998 * Requires `base` (the source space) and `gamutSpace` (the RGB gamut). `chroma` names the
4999 * coordinate to rescale (default `"c"`).
5000 */
5001 constructor (options) {
5002 let base = ColorSpace.get(options.base);
5003 let chroma = options.chroma ?? "c";
5004 let ids = Object.keys(base.coords);
5005 let chromaIndex = ids.indexOf(chroma);
5006
5007 if (chromaIndex === -1) {
5008 throw new TypeError(
5009 `GamutRelativeColorSpace needs a "${chroma}" coordinate, got ${base.id}`,
5010 );
5011 }
5012
5013 // Inherit the base's coords; the reduced coordinate becomes a 0–1 fraction of its gamut maximum
5014 let coords = Object.fromEntries(
5015 Object.entries(base.coords).map(([id, meta]) => [id, { ...meta }]),
5016 );
5017 coords[chroma].range = [0, 1];
5018 delete coords[chroma].refRange;
5019 options.coords ??= coords;
5020
5021 // Serialize the reduced coordinate and any other 0–1 coordinate as percentages; angles as angles
5022 options.formats ??= {
5023 color: {
5024 coords: ids.map(id => {
5025 if (base.coords[id].type === "angle") {
5026 return "<number> | <angle>";
5027 }
5028 let [min, max] = base.coords[id].range ?? base.coords[id].refRange ?? [];
5029 let pctFirst = id === chroma || (min === 0 && max === 1);
5030 return pctFirst ? "<percentage> | <number>" : "<number> | <percentage>";
5031 }),
5032 },
5033 };
5034
5035 super(options);
5036
5037 this.chromaIndex = chromaIndex;
5038 this.method = `${base.id}.${chroma}`;
5039
5040 // A chroma that is out of gamut at every lightness and hue: the gamut's most saturated corner
5041 // (its primaries/secondaries are its chroma maxima) plus headroom. Seeding the gamut search
5042 // from here lands on the first in-gamut crossing — the highest contiguous in-gamut chroma —
5043 // and avoids clamping wide gamuts (e.g. Rec.2020 exceeds OKLCh's nominal 0.4 chroma).
5044 // prettier-ignore
5045 let corners = /** @type {[number, number, number][]} */ (
5046 [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]]
5047 );
5048 this.oogChroma =
5049 1.01 *
5050 Math.max(...corners.map(rgb => base.from(this.gamutSpace, rgb)[this.chromaIndex] || 0));
5051 }
5052
5053 /**
5054 * The highest in-gamut value of the reduced coordinate for the given coordinates. The reduced
5055 * coordinate's own value is ignored; the others determine the result.
5056 * @param {number[]} coords
5057 * @returns {number}
5058 */
5059 maxChroma (coords) {
5060 let seed = /** @type {[number, number, number]} */ ([...coords]);
5061 seed[this.chromaIndex] = this.oogChroma;
5062
5063 return toGamut(
5064 { space: this.base, coords: seed },
5065 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
5066 { space: this.gamutSpace, method: this.method, deltaEMethod: "OK", jnd: 0 },
5067 ).coords[this.chromaIndex];
5068 }
5069
5070 toBase (coords) {
5071 coords = [...coords];
5072
5073 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
5074 // chroma is a fraction of maxChroma(the other coords); without them all it is undefined
5075 if (coords[this.chromaIndex] !== 0) {
5076 coords[this.chromaIndex] = null;
5077 }
5078 }
5079 else if (!isNone(coords[this.chromaIndex])) {
5080 coords[this.chromaIndex] *= this.maxChroma(coords);
5081 }
5082
5083 return coords;
5084 }
5085
5086 fromBase (coords) {
5087 coords = [...coords];
5088
5089 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
5090 if (coords[this.chromaIndex] !== 0) {
5091 coords[this.chromaIndex] = null;
5092 }
5093 }
5094 else if (!isNone(coords[this.chromaIndex])) {
5095 let cMax = this.maxChroma(coords);
5096 coords[this.chromaIndex] = cMax ? coords[this.chromaIndex] / cMax : 0;
5097 }
5098
5099 return coords;
5100 }
5101 }
5102
5103 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
5104
5105 // Type re-exports
5106 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
5107
5108 /**
5109 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
5110 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
5111 *
5112 * @overload
5113 * @param {ColorTypes} color
5114 * @param {TryColorOptions} [options]
5115 * @returns {PlainColorObject | null}
5116 */
5117 /**
5118 * @overload
5119 * @param {ColorTypes[]} color
5120 * @param {TryColorOptions} [options]
5121 * @returns {(PlainColorObject | null)[]}
5122 */
5123 function tryColor (color, options = {}) {
5124 if (Array.isArray(color)) {
5125 return color.map(c => tryColor(c, options));
5126 }
5127
5128 let { cssProperty = "background-color", element, ...getColorOptions } = options;
5129 let error = null;
5130 try {
5131 return getColor(color, getColorOptions);
5132 }
5133 catch (e) {
5134 error = e;
5135 }
5136
5137 let { CSS, getComputedStyle } = globalThis;
5138 if (isString(color) && element && CSS && getComputedStyle) {
5139 // Try resolving the color using the DOM, if supported in CSS
5140 if (CSS.supports(cssProperty, color)) {
5141 let previousValue = element.style[cssProperty];
5142
5143 if (color !== previousValue) {
5144 element.style[cssProperty] = color;
5145 }
5146
5147 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
5148
5149 if (color !== previousValue) {
5150 element.style[cssProperty] = previousValue;
5151 }
5152
5153 if (computedColor !== color) {
5154 // getComputedStyle() changed the color, try again
5155 try {
5156 return getColor(computedColor, getColorOptions);
5157 }
5158 catch (e) {
5159 error = e;
5160 }
5161 }
5162 else {
5163 // Still not resolved
5164 error = {
5165 message: "Color value is a valid CSS color, but it could not be resolved :(",
5166 };
5167 }
5168 }
5169 }
5170
5171 // If we're here, we failed to resolve the color
5172 if (options.errorMeta) {
5173 options.errorMeta.error = error;
5174 }
5175
5176 return null;
5177 }
5178
5179 // @ts-nocheck
5180
5181
5182 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
5183
5184 // Type re-exports
5185 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
5186
5187 /**
5188 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
5189 * @param {ColorTypes} color
5190 * @param {SerializeOptions & Record<string, any>} options
5191 * @returns {string}
5192 */
5193 function serialize (color, options = {}) {
5194 let {
5195 precision = defaults.precision,
5196 format,
5197 inGamut: inGamut$1 = true,
5198 coords: coordFormat,
5199 alpha: alphaFormat,
5200 commas,
5201 } = options;
5202 let ret;
5203
5204 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */ (getColor(color));
5205
5206 let formatId = format;
5207 let parseMeta = colorWithMeta.parseMeta;
5208
5209 if (parseMeta && !format) {
5210 if (parseMeta.format.canSerialize()) {
5211 format = parseMeta.format;
5212 formatId = parseMeta.formatId;
5213 }
5214
5215 coordFormat ??= parseMeta.types;
5216 alphaFormat ??= parseMeta.alphaType;
5217 commas ??= parseMeta.commas;
5218 }
5219
5220 if (formatId) {
5221 // A format is explicitly specified
5222 format = colorWithMeta.space.getFormat(format) ?? ColorSpace.findFormat(formatId);
5223 }
5224
5225 if (!format) {
5226 // No format specified, or format not found
5227 format = colorWithMeta.space.getFormat("default") ?? ColorSpace.DEFAULT_FORMAT;
5228 formatId = format.name;
5229 }
5230
5231 if (format && format.space && format.space !== colorWithMeta.space) {
5232 // Format specified belongs to a different color space,
5233 // need to convert to it first
5234 colorWithMeta = to(colorWithMeta, format.space);
5235 }
5236
5237 // The assignment to coords and inGamut needs to stay in the order they are now
5238 // The order of the assignment was changed as a workaround for a bug in Next.js
5239 // See this issue for details: https://github.com/color-js/color.js/issues/260
5240
5241 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
5242
5243 inGamut$1 ||= format.toGamut;
5244
5245 if (inGamut$1 && !inGamut(colorWithMeta)) {
5246 // FIXME what happens if the color contains none values?
5247 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
5248 }
5249
5250 if (format.type === "custom") {
5251 if (format.serialize) {
5252 ret = format.serialize(coords, colorWithMeta.alpha, options);
5253 }
5254 else {
5255 throw new TypeError(
5256 `format ${formatId} can only be used to parse colors, not for serialization`,
5257 );
5258 }
5259 }
5260 else {
5261 // Functional syntax
5262 let name = format.name || "color";
5263
5264 let args = format.serializeCoords(coords, precision, coordFormat);
5265
5266 if (name === "color") {
5267 // If output is a color() function, add colorspace id as first argument
5268 let cssId =
5269 format.id || format.ids?.[0] || colorWithMeta.space.cssId || colorWithMeta.space.id;
5270 args.unshift(cssId);
5271 }
5272
5273 // Serialize alpha?
5274 /** @type {string | number} */
5275 let alpha = colorWithMeta.alpha;
5276
5277 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
5278 alphaFormat =
5279 typeof alphaFormat === "string" ? { type: alphaFormat } : { include: alphaFormat };
5280 }
5281
5282 let alphaType = alphaFormat?.type ?? "<number>";
5283 let serializeAlpha =
5284 alphaFormat?.include === true ||
5285 format.alpha === true ||
5286 (alphaFormat?.include !== false && format.alpha !== false && alpha < 1);
5287 let strAlpha = "";
5288
5289 commas ??= format.commas;
5290
5291 if (serializeAlpha) {
5292 if (precision !== null) {
5293 let unit;
5294
5295 if (alphaType === "<percentage>") {
5296 unit = "%";
5297 alpha *= 100;
5298 }
5299
5300 alpha = serializeNumber(alpha, { precision, unit });
5301 }
5302
5303 strAlpha = `${commas ? "," : " /"} ${alpha}`;
5304 }
5305
5306 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
5307 }
5308
5309 return ret;
5310 }
5311
5312 /** @import { Matrix3x3 } from "../types.js" */
5313
5314 /**
5315 * Matrices used by this color space, also available as `REC_2020_Linear.M`.
5316 * Uses D65 (no chromatic adaptation).
5317 * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
5318 * @type {Record<string, Matrix3x3>}
5319 */
5320 // prettier-ignore
5321 const M$8 = {
5322 // 0 is actually calculated as 4.994106574466076e-17
5323 toXYZ: [
5324 [ 0.6369580483012914, 0.14461690358620832, 0.1688809751641721 ],
5325 [ 0.2627002120112671, 0.6779980715188708, 0.05930171646986196 ],
5326 [ 0.000000000000000, 0.028072693049087428, 1.060985057710791 ],
5327 ],
5328 // from ITU-R BT.2124-0 Annex 2 p.3
5329 fromXYZ: [
5330 [ 1.716651187971268, -0.355670783776392, -0.253366281373660 ],
5331 [ -0.666684351832489, 1.616481236634939, 0.0157685458139111 ],
5332 [ 0.017639857445311, -0.042770613257809, 0.942103121235474 ],
5333 ],
5334 };
5335
5336 var REC2020Linear = new RGBColorSpace({
5337 id: "rec2020-linear",
5338 cssId: "--rec2020-linear",
5339 name: "Linear REC.2020",
5340 white: "D65",
5341 M: M$8,
5342 });
5343
5344 // import sRGB from "./srgb.js";
5345
5346 var REC2020 = new RGBColorSpace({
5347 id: "rec2020",
5348 name: "REC.2020",
5349 base: REC2020Linear,
5350 linearGamut: REC2020Linear,
5351 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
5352 // with b (black lift) = 0 and a (user gain) = 1
5353 // defined over the extended range, not clamped
5354 toBase (RGB) {
5355 return RGB.map(function (val) {
5356 let sign = val < 0 ? -1 : 1;
5357 let abs = val * sign;
5358 return sign * Math.pow(abs, 2.4);
5359 });
5360 },
5361 fromBase (RGB) {
5362 return RGB.map(function (val) {
5363 let sign = val < 0 ? -1 : 1;
5364 let abs = val * sign;
5365 return sign * Math.pow(abs, 1 / 2.4);
5366 });
5367 },
5368 });
5369
5370 /** @import { Matrix3x3 } from "../types.js" */
5371
5372 /**
5373 * Matrices used by this color space, also available as `P3_Linear.M`
5374 * @type {Record<string, Matrix3x3>}
5375 */
5376 // prettier-ignore
5377 const M$7 = {
5378 toXYZ: [
5379 [0.4865709486482162, 0.26566769316909306, 0.1982172852343625],
5380 [0.2289745640697488, 0.6917385218365064, 0.079286914093745],
5381 [0.0000000000000000, 0.04511338185890264, 1.043944368900976],
5382 ],
5383 fromXYZ: [
5384 [ 2.493496911941425, -0.9313836179191239, -0.40271078445071684],
5385 [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577],
5386 [ 0.03584583024378447, -0.07617238926804182, 0.9568845240076872],
5387 ],
5388 };
5389
5390 var P3Linear = new RGBColorSpace({
5391 id: "p3-linear",
5392 cssId: "display-p3-linear",
5393 name: "Linear P3",
5394 white: "D65",
5395 M: M$7,
5396 });
5397
5398 /** @import { Matrix3x3 } from "../types.js" */
5399
5400 // This is the linear-light version of sRGB
5401 // as used for example in SVG filters
5402 // or in Canvas
5403
5404 /**
5405 * Matrices used by this color space, also available as `sRGB_Linear.M`
5406 * @type {Record<string, Matrix3x3>}
5407 */
5408 // prettier-ignore
5409 const M$6 = {
5410 // calculated directly from the RGB and white chromaticities; when rounded to
5411 // 8 decimal places, agrees completely with the official matrix
5412 // see https://github.com/w3c/csswg-drafts/issues/5922
5413 toXYZ: [
5414 [ 0.41239079926595934, 0.357584339383878, 0.1804807884018343 ],
5415 [ 0.21263900587151027, 0.715168678767756, 0.07219231536073371 ],
5416 [ 0.01933081871559182, 0.11919477979462598, 0.9505321522496607 ],
5417 ],
5418 // the inverse of the above; again agrees with the official definition
5419 // when rounded to 8 decimal places
5420 fromXYZ: [
5421 [ 3.2409699419045226, -1.537383177570094, -0.4986107602930034 ],
5422 [ -0.9692436362808796, 1.8759675015077202, 0.04155505740717559 ],
5423 [ 0.05563007969699366, -0.20397695888897652, 1.0569715142428786 ],
5424 ],
5425 };
5426
5427 var sRGBLinear = new RGBColorSpace({
5428 id: "srgb-linear",
5429 name: "Linear sRGB",
5430 white: "D65",
5431 M: M$6,
5432 });
5433
5434 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
5435 // and run in the console:
5436 // copy($$("tr", $(".named-color-table tbody")).map(tr => `"${tr.cells[2].textContent.trim()}": [${tr.cells[4].textContent.trim().split(/\s+/).map(c => c === "0"? "0" : c === "255"? "1" : c + " / 255").join(", ")}]`).join(",\n"))
5437
5438 /** List of CSS color keywords
5439 * Note that this does not include currentColor, transparent,
5440 * or system colors
5441 *
5442 * @type {Record<string, [number, number, number]>}
5443 */
5444 var KEYWORDS = {
5445 aliceblue: [240 / 255, 248 / 255, 1],
5446 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
5447 aqua: [0, 1, 1],
5448 aquamarine: [127 / 255, 1, 212 / 255],
5449 azure: [240 / 255, 1, 1],
5450 beige: [245 / 255, 245 / 255, 220 / 255],
5451 bisque: [1, 228 / 255, 196 / 255],
5452 black: [0, 0, 0],
5453 blanchedalmond: [1, 235 / 255, 205 / 255],
5454 blue: [0, 0, 1],
5455 blueviolet: [138 / 255, 43 / 255, 226 / 255],
5456 brown: [165 / 255, 42 / 255, 42 / 255],
5457 burlywood: [222 / 255, 184 / 255, 135 / 255],
5458 cadetblue: [95 / 255, 158 / 255, 160 / 255],
5459 chartreuse: [127 / 255, 1, 0],
5460 chocolate: [210 / 255, 105 / 255, 30 / 255],
5461 coral: [1, 127 / 255, 80 / 255],
5462 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
5463 cornsilk: [1, 248 / 255, 220 / 255],
5464 crimson: [220 / 255, 20 / 255, 60 / 255],
5465 cyan: [0, 1, 1],
5466 darkblue: [0, 0, 139 / 255],
5467 darkcyan: [0, 139 / 255, 139 / 255],
5468 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
5469 darkgray: [169 / 255, 169 / 255, 169 / 255],
5470 darkgreen: [0, 100 / 255, 0],
5471 darkgrey: [169 / 255, 169 / 255, 169 / 255],
5472 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
5473 darkmagenta: [139 / 255, 0, 139 / 255],
5474 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
5475 darkorange: [1, 140 / 255, 0],
5476 darkorchid: [153 / 255, 50 / 255, 204 / 255],
5477 darkred: [139 / 255, 0, 0],
5478 darksalmon: [233 / 255, 150 / 255, 122 / 255],
5479 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
5480 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
5481 darkslategray: [47 / 255, 79 / 255, 79 / 255],
5482 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
5483 darkturquoise: [0, 206 / 255, 209 / 255],
5484 darkviolet: [148 / 255, 0, 211 / 255],
5485 deeppink: [1, 20 / 255, 147 / 255],
5486 deepskyblue: [0, 191 / 255, 1],
5487 dimgray: [105 / 255, 105 / 255, 105 / 255],
5488 dimgrey: [105 / 255, 105 / 255, 105 / 255],
5489 dodgerblue: [30 / 255, 144 / 255, 1],
5490 firebrick: [178 / 255, 34 / 255, 34 / 255],
5491 floralwhite: [1, 250 / 255, 240 / 255],
5492 forestgreen: [34 / 255, 139 / 255, 34 / 255],
5493 fuchsia: [1, 0, 1],
5494 gainsboro: [220 / 255, 220 / 255, 220 / 255],
5495 ghostwhite: [248 / 255, 248 / 255, 1],
5496 gold: [1, 215 / 255, 0],
5497 goldenrod: [218 / 255, 165 / 255, 32 / 255],
5498 gray: [128 / 255, 128 / 255, 128 / 255],
5499 green: [0, 128 / 255, 0],
5500 greenyellow: [173 / 255, 1, 47 / 255],
5501 grey: [128 / 255, 128 / 255, 128 / 255],
5502 honeydew: [240 / 255, 1, 240 / 255],
5503 hotpink: [1, 105 / 255, 180 / 255],
5504 indianred: [205 / 255, 92 / 255, 92 / 255],
5505 indigo: [75 / 255, 0, 130 / 255],
5506 ivory: [1, 1, 240 / 255],
5507 khaki: [240 / 255, 230 / 255, 140 / 255],
5508 lavender: [230 / 255, 230 / 255, 250 / 255],
5509 lavenderblush: [1, 240 / 255, 245 / 255],
5510 lawngreen: [124 / 255, 252 / 255, 0],
5511 lemonchiffon: [1, 250 / 255, 205 / 255],
5512 lightblue: [173 / 255, 216 / 255, 230 / 255],
5513 lightcoral: [240 / 255, 128 / 255, 128 / 255],
5514 lightcyan: [224 / 255, 1, 1],
5515 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
5516 lightgray: [211 / 255, 211 / 255, 211 / 255],
5517 lightgreen: [144 / 255, 238 / 255, 144 / 255],
5518 lightgrey: [211 / 255, 211 / 255, 211 / 255],
5519 lightpink: [1, 182 / 255, 193 / 255],
5520 lightsalmon: [1, 160 / 255, 122 / 255],
5521 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
5522 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
5523 lightslategray: [119 / 255, 136 / 255, 153 / 255],
5524 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
5525 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
5526 lightyellow: [1, 1, 224 / 255],
5527 lime: [0, 1, 0],
5528 limegreen: [50 / 255, 205 / 255, 50 / 255],
5529 linen: [250 / 255, 240 / 255, 230 / 255],
5530 magenta: [1, 0, 1],
5531 maroon: [128 / 255, 0, 0],
5532 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
5533 mediumblue: [0, 0, 205 / 255],
5534 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
5535 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
5536 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
5537 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
5538 mediumspringgreen: [0, 250 / 255, 154 / 255],
5539 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
5540 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
5541 midnightblue: [25 / 255, 25 / 255, 112 / 255],
5542 mintcream: [245 / 255, 1, 250 / 255],
5543 mistyrose: [1, 228 / 255, 225 / 255],
5544 moccasin: [1, 228 / 255, 181 / 255],
5545 navajowhite: [1, 222 / 255, 173 / 255],
5546 navy: [0, 0, 128 / 255],
5547 oldlace: [253 / 255, 245 / 255, 230 / 255],
5548 olive: [128 / 255, 128 / 255, 0],
5549 olivedrab: [107 / 255, 142 / 255, 35 / 255],
5550 orange: [1, 165 / 255, 0],
5551 orangered: [1, 69 / 255, 0],
5552 orchid: [218 / 255, 112 / 255, 214 / 255],
5553 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
5554 palegreen: [152 / 255, 251 / 255, 152 / 255],
5555 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
5556 palevioletred: [219 / 255, 112 / 255, 147 / 255],
5557 papayawhip: [1, 239 / 255, 213 / 255],
5558 peachpuff: [1, 218 / 255, 185 / 255],
5559 peru: [205 / 255, 133 / 255, 63 / 255],
5560 pink: [1, 192 / 255, 203 / 255],
5561 plum: [221 / 255, 160 / 255, 221 / 255],
5562 powderblue: [176 / 255, 224 / 255, 230 / 255],
5563 purple: [128 / 255, 0, 128 / 255],
5564 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
5565 red: [1, 0, 0],
5566 rosybrown: [188 / 255, 143 / 255, 143 / 255],
5567 royalblue: [65 / 255, 105 / 255, 225 / 255],
5568 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
5569 salmon: [250 / 255, 128 / 255, 114 / 255],
5570 sandybrown: [244 / 255, 164 / 255, 96 / 255],
5571 seagreen: [46 / 255, 139 / 255, 87 / 255],
5572 seashell: [1, 245 / 255, 238 / 255],
5573 sienna: [160 / 255, 82 / 255, 45 / 255],
5574 silver: [192 / 255, 192 / 255, 192 / 255],
5575 skyblue: [135 / 255, 206 / 255, 235 / 255],
5576 slateblue: [106 / 255, 90 / 255, 205 / 255],
5577 slategray: [112 / 255, 128 / 255, 144 / 255],
5578 slategrey: [112 / 255, 128 / 255, 144 / 255],
5579 snow: [1, 250 / 255, 250 / 255],
5580 springgreen: [0, 1, 127 / 255],
5581 steelblue: [70 / 255, 130 / 255, 180 / 255],
5582 tan: [210 / 255, 180 / 255, 140 / 255],
5583 teal: [0, 128 / 255, 128 / 255],
5584 thistle: [216 / 255, 191 / 255, 216 / 255],
5585 tomato: [1, 99 / 255, 71 / 255],
5586 turquoise: [64 / 255, 224 / 255, 208 / 255],
5587 violet: [238 / 255, 130 / 255, 238 / 255],
5588 wheat: [245 / 255, 222 / 255, 179 / 255],
5589 white: [1, 1, 1],
5590 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
5591 yellow: [1, 1, 0],
5592 yellowgreen: [154 / 255, 205 / 255, 50 / 255],
5593 };
5594
5595 /** @import { Coords } from "../types.js" */
5596
5597 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
5598 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
5599
5600 var sRGB = new RGBColorSpace({
5601 id: "srgb",
5602 name: "sRGB",
5603 base: sRGBLinear,
5604 linearGamut: sRGBLinear,
5605 fromBase: rgb => {
5606 // convert an array of linear-light sRGB values in the range 0.0-1.0
5607 // to gamma corrected form
5608 // https://en.wikipedia.org/wiki/SRGB
5609 return rgb.map(val => {
5610 let sign = val < 0 ? -1 : 1;
5611 let abs = val * sign;
5612
5613 if (abs > 0.0031308) {
5614 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
5615 }
5616
5617 return 12.92 * val;
5618 });
5619 },
5620 toBase: rgb => {
5621 // convert an array of sRGB values in the range 0.0 - 1.0
5622 // to linear light (un-companded) form.
5623 // https://en.wikipedia.org/wiki/SRGB
5624 return rgb.map(val => {
5625 let sign = val < 0 ? -1 : 1;
5626 let abs = val * sign;
5627
5628 if (abs <= 0.04045) {
5629 return val / 12.92;
5630 }
5631
5632 return sign * ((abs + 0.055) / 1.055) ** 2.4;
5633 });
5634 },
5635 formats: {
5636 rgb: {
5637 coords: coordGrammar,
5638 },
5639 rgb_number: {
5640 name: "rgb",
5641 commas: true,
5642 coords: coordGrammarNumber,
5643 alpha: false,
5644 },
5645 color: {
5646 /* use defaults */
5647 },
5648 rgba: {
5649 coords: coordGrammar,
5650 commas: true,
5651 alpha: true,
5652 },
5653 rgba_number: {
5654 name: "rgba",
5655 commas: true,
5656 coords: coordGrammarNumber,
5657 },
5658 hex: {
5659 type: "custom",
5660 toGamut: true,
5661 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
5662 parse (str) {
5663 if (str.length <= 5) {
5664 // #rgb or #rgba, duplicate digits
5665 str = str.replace(/[a-f0-9]/gi, "$&$&");
5666 }
5667
5668 /** @type {number[]} */
5669 let rgba = [];
5670 // @ts-expect-error Type 'void' is not assignable to type 'string'
5671 str.replace(/[a-f0-9]{2}/gi, component => {
5672 rgba.push(parseInt(component, 16) / 255);
5673 });
5674
5675 return {
5676 spaceId: "srgb",
5677 coords: /** @type {Coords} */ (rgba.slice(0, 3)),
5678 alpha: /** @type {number} */ (rgba.slice(3)[0]),
5679 };
5680 },
5681 serialize: (
5682 coords,
5683 alpha,
5684 {
5685 collapse = true, // collapse to 3-4 digit hex when possible?
5686 alpha: alphaFormat,
5687 } = {},
5688 ) => {
5689 if ((alphaFormat !== false && alpha < 1) || alphaFormat === true) {
5690 coords.push(alpha);
5691 }
5692
5693 coords = /** @type {[number, number, number]} */ (
5694 coords.map(c => Math.round(c * 255))
5695 );
5696
5697 let collapsible = collapse && coords.every(c => c % 17 === 0);
5698
5699 let hex = coords
5700 .map(c => {
5701 if (collapsible) {
5702 return (c / 17).toString(16);
5703 }
5704
5705 return c.toString(16).padStart(2, "0");
5706 })
5707 .join("");
5708
5709 return "#" + hex;
5710 },
5711 },
5712 keyword: {
5713 type: "custom",
5714 test: str => /^[a-z]+$/i.test(str),
5715 parse (str) {
5716 str = str.toLowerCase();
5717 let ret = { spaceId: "srgb", coords: null, alpha: 1 };
5718
5719 if (str === "transparent") {
5720 ret.coords = KEYWORDS.black;
5721 ret.alpha = 0;
5722 }
5723 else {
5724 ret.coords = KEYWORDS[str];
5725 }
5726
5727 if (ret.coords) {
5728 return ret;
5729 }
5730 },
5731 },
5732 },
5733 });
5734
5735 var P3 = new RGBColorSpace({
5736 id: "p3",
5737 cssId: "display-p3",
5738 name: "P3",
5739 base: P3Linear,
5740 linearGamut: P3Linear,
5741 // Gamma encoding/decoding is the same as sRGB
5742 fromBase: sRGB.fromBase,
5743 toBase: sRGB.toBase,
5744 });
5745
5746 /** @import ColorSpace from "./ColorSpace.js" */
5747 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
5748
5749 // Type re-exports
5750 /** @typedef {import("./types.js").Display} Display */
5751
5752 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
5753 defaults.display_space = sRGB;
5754
5755 let supportsNone;
5756
5757 if (typeof CSS !== "undefined" && CSS.supports) {
5758 // Find widest supported color space for CSS
5759 for (let space of [lab, REC2020, P3]) {
5760 let coords = space.getMinCoords();
5761 let color = { space, coords, alpha: 1 };
5762 let str = serialize(color);
5763
5764 if (CSS.supports("color", str)) {
5765 defaults.display_space = space;
5766 break;
5767 }
5768 }
5769 }
5770
5771 /**
5772 * Returns a serialization of the color that can actually be displayed in the browser.
5773 * If the default serialization can be displayed, it is returned.
5774 * Otherwise, if a `space` is given, the color is converted directly to it.
5775 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
5776 * else the closest supported space in its base color space chain (which preserves its gamut),
5777 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
5778 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
5779 * @param {ColorTypes} color
5780 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
5781 * @returns {Display} String object containing the serialized color
5782 * with a color property containing the converted color (or the original, if no conversion was necessary)
5783 */
5784 function display (
5785 color,
5786 { space, supports = globalThis.CSS?.supports, ...options } = {},
5787 ) {
5788 color = getColor(color);
5789
5790 let ret = /** @type {Display} */ (serialize(color, options));
5791
5792 if (!supports || supports("color", /** @type {string} */ (ret)) || !defaults.display_space) {
5793 ret = /** @type {Display} */ (new String(ret));
5794 ret.color = /** @type {PlainColorObject} */ (color);
5795 }
5796 else {
5797 // If we're here, what we were about to output is not supported
5798 let fallbackColor = /** @type {PlainColorObject} */ (color);
5799
5800 // First, check if the culprit is none values
5801 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
5802
5803 if (hasNone) {
5804 // Does the browser support none values?
5805 if (!(supportsNone ??= supports("color", "hsl(none 50% 50%)"))) {
5806 // Nope, try again without none
5807 fallbackColor = clone(/** @type {PlainColorObject} */ (color));
5808 fallbackColor.coords = /** @type {[number, number, number]} */ (
5809 fallbackColor.coords.map(skipNone)
5810 );
5811 fallbackColor.alpha = skipNone(fallbackColor.alpha);
5812
5813 // @ts-expect-error This is set to the correct type later
5814 ret = serialize(fallbackColor, options);
5815
5816 if (supports("color", /** @type {string} */ (ret))) {
5817 // We're done, now it's supported
5818 ret = /** @type {Display} */ (new String(ret));
5819 ret.color = fallbackColor;
5820 return ret;
5821 }
5822 }
5823 }
5824
5825 // If we're here, the color function is not supported.
5826 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
5827 // color space chain (closest first, skipping XYZ connection spaces), and use the first
5828 // space the browser supports, before falling back to the default space.
5829 if (space === undefined) {
5830 space = fallbackColor.space;
5831 let candidates = space.displaySpaces ?? space.bases;
5832
5833 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
5834 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
5835 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
5836 }
5837
5838 for (let candidate of candidates) {
5839 let candidateColor = to(fallbackColor, candidate);
5840 let str = serialize(candidateColor, options);
5841
5842 if (supports("color", /** @type {string} */ (str))) {
5843 ret = /** @type {Display} */ (new String(str));
5844 ret.color = candidateColor;
5845 return ret;
5846 }
5847 }
5848
5849 space = defaults.display_space;
5850 }
5851
5852 // Fall back to fallback space
5853 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */ (space));
5854 ret = /** @type {Display} */ (new String(serialize(fallbackColor, options)));
5855 ret.color = fallbackColor;
5856 }
5857
5858 return ret;
5859 }
5860
5861 /** @import { ColorTypes } from "./types.js" */
5862
5863 // Type re-exports
5864 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
5865
5866 /**
5867 * Get color differences per-component, on any color space
5868 * @param {ColorTypes} c1
5869 * @param {ColorTypes} c2
5870 * @param {object} options
5871 * @param {string | ColorSpace} [options.space=c1.space] - The color space to use for the delta calculation. Defaults to the color space of the first color.
5872 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
5873 * @returns {DeltasReturn}
5874 */
5875 function deltas (c1, c2, { space, hue = "shorter" } = {}) {
5876 c1 = getColor(c1);
5877 space ||= c1.space;
5878 space = ColorSpace.get(space);
5879 let spaceCoords = Object.values(space.coords);
5880
5881 [c1, c2] = [c1, c2].map(c => to(c, space));
5882 let [coords1, coords2] = [c1, c2].map(c => c.coords);
5883
5884 let coords = /** @type {[number, number, number]} */ (
5885 coords1.map((coord1, i) => {
5886 let coordMeta = spaceCoords[i];
5887 let coord2 = coords2[i];
5888
5889 if (coordMeta.type === "angle") {
5890 [coord1, coord2] = adjust(hue, [coord1, coord2]);
5891 }
5892
5893 return subtractCoords(coord1, coord2);
5894 })
5895 );
5896
5897 let alpha = subtractCoords(c1.alpha, c2.alpha);
5898
5899 return { space: /** @type {ColorSpace} */ (space), coords, alpha };
5900 }
5901
5902 function subtractCoords (c1, c2) {
5903 if (isNone(c1) || isNone(c2)) {
5904 return c1 === c2 ? null : 0;
5905 }
5906
5907 return c1 - c2;
5908 }
5909
5910 /** @import { ColorTypes } from "./types.js" */
5911
5912 /**
5913 * @param {ColorTypes} color1
5914 * @param {ColorTypes} color2
5915 * @returns {boolean}
5916 */
5917 function equals (color1, color2) {
5918 color1 = getColor(color1);
5919 color2 = getColor(color2);
5920
5921 return (
5922 color1.space === color2.space &&
5923 color1.alpha === color2.alpha &&
5924 color1.coords.every((c, i) => c === color2.coords[i])
5925 );
5926 }
5927
5928 /**
5929 * Relative luminance
5930 */
5931
5932 /** @import { ColorTypes } from "./types.js" */
5933
5934 /**
5935 *
5936 * @param {ColorTypes} color
5937 * @returns {number}
5938 */
5939 function getLuminance (color) {
5940 // Assume getColor() is called on color in get()
5941 return get(color, [XYZ_D65, "y"]);
5942 }
5943
5944 /**
5945 * @param {ColorTypes} color
5946 * @param {number | ((coord: number) => number)} value
5947 */
5948 function setLuminance (color, value) {
5949 // Assume getColor() is called on color in set()
5950 set(color, [XYZ_D65, "y"], value);
5951 }
5952
5953 /**
5954 * @param {typeof import("./color.js").default} Color
5955 */
5956 function register$2 (Color) {
5957 Object.defineProperty(Color.prototype, "luminance", {
5958 get () {
5959 return getLuminance(this);
5960 },
5961 set (value) {
5962 setLuminance(this, value);
5963 },
5964 });
5965 }
5966
5967 var luminance = /*#__PURE__*/Object.freeze({
5968 __proto__: null,
5969 getLuminance: getLuminance,
5970 register: register$2,
5971 setLuminance: setLuminance
5972 });
5973
5974 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
5975 // Simple contrast, with fixed 5% viewing flare contribution
5976 // Symmetric, does not matter which is foreground and which is background
5977
5978
5979 /**
5980 * @param {import("../types.js").ColorTypes} color1
5981 * @param {import("../types.js").ColorTypes} color2
5982 * @returns {number}
5983 */
5984 function contrastWCAG21 (color1, color2) {
5985 color1 = getColor(color1);
5986 color2 = getColor(color2);
5987
5988 let Y1 = Math.max(getLuminance(color1), 0);
5989 let Y2 = Math.max(getLuminance(color2), 0);
5990
5991 if (Y2 > Y1) {
5992 [Y1, Y2] = [Y2, Y1];
5993 }
5994
5995 return (Y1 + 0.05) / (Y2 + 0.05);
5996 }
5997
5998 // APCA 0.0.98G
5999 // https://github.com/Myndex/apca-w3
6000 // see also https://github.com/w3c/silver/issues/643
6001
6002
6003 // exponents
6004 const normBG = 0.56;
6005 const normTXT = 0.57;
6006 const revTXT = 0.62;
6007 const revBG = 0.65;
6008
6009 // clamps
6010 const blkThrs = 0.022;
6011 const blkClmp = 1.414;
6012 const loClip = 0.1;
6013 const deltaYmin = 0.0005;
6014
6015 // scalers
6016 // see https://github.com/w3c/silver/issues/645
6017 const scaleBoW = 1.14;
6018 const loBoWoffset = 0.027;
6019 const scaleWoB = 1.14;
6020
6021 function fclamp (Y) {
6022 if (Y >= blkThrs) {
6023 return Y;
6024 }
6025 return Y + (blkThrs - Y) ** blkClmp;
6026 }
6027
6028 function linearize (val) {
6029 let sign = val < 0 ? -1 : 1;
6030 let abs = Math.abs(val);
6031 return sign * Math.pow(abs, 2.4);
6032 }
6033
6034 /**
6035 * Not symmetric, requires a foreground (text) color, and a background color
6036 * @param {import("../types.js").ColorTypes} background
6037 * @param {import("../types.js").ColorTypes} foreground
6038 * @returns {number}
6039 */
6040 function contrastAPCA (background, foreground) {
6041 foreground = getColor(foreground);
6042 background = getColor(background);
6043
6044 let S;
6045 let C;
6046 let Sapc;
6047
6048 // Myndex as-published, assumes sRGB inputs
6049 let R, G, B;
6050
6051 foreground = to(foreground, "srgb");
6052 // Should these be clamped to in-gamut values?
6053
6054 // Calculates "screen luminance" with non-standard simple gamma EOTF
6055 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
6056 [R, G, B] = foreground.coords.map(c => {
6057 return isNone(c) ? 0 : c;
6058 });
6059 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
6060
6061 background = to(background, "srgb");
6062 [R, G, B] = background.coords.map(c => {
6063 return isNone(c) ? 0 : c;
6064 });
6065 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
6066
6067 // toe clamping of very dark values to account for flare
6068 let Ytxt = fclamp(lumTxt);
6069 let Ybg = fclamp(lumBg);
6070
6071 // are we "Black on White" (dark on light), or light on dark?
6072 let BoW = Ybg > Ytxt;
6073
6074 // why is this a delta, when Y is not perceptually uniform?
6075 // Answer: it is a noise gate, see
6076 // https://github.com/LeaVerou/color.js/issues/208
6077 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
6078 C = 0;
6079 }
6080 else {
6081 if (BoW) {
6082 // dark text on light background
6083 S = Ybg ** normBG - Ytxt ** normTXT;
6084 C = S * scaleBoW;
6085 }
6086 else {
6087 // light text on dark background
6088 S = Ybg ** revBG - Ytxt ** revTXT;
6089 C = S * scaleWoB;
6090 }
6091 }
6092 if (Math.abs(C) < loClip) {
6093 Sapc = 0;
6094 }
6095 else if (C > 0) {
6096 // not clear whether Woffset is loBoWoffset or loWoBoffset
6097 // but they have the same value
6098 Sapc = C - loBoWoffset;
6099 }
6100 else {
6101 Sapc = C + loBoWoffset;
6102 }
6103
6104 return Sapc * 100;
6105 }
6106
6107 // Michelson luminance contrast
6108 // the relation between the spread and the sum of the two luminances
6109 // Symmetric, does not matter which is foreground and which is background
6110 // No black level compensation for flare.
6111
6112
6113 /**
6114 * @param {import("../types.js").ColorTypes} color1
6115 * @param {import("../types.js").ColorTypes} color2
6116 * @returns {number}
6117 */
6118 function contrastMichelson (color1, color2) {
6119 color1 = getColor(color1);
6120 color2 = getColor(color2);
6121
6122 let Y1 = Math.max(getLuminance(color1), 0);
6123 let Y2 = Math.max(getLuminance(color2), 0);
6124
6125 if (Y2 > Y1) {
6126 [Y1, Y2] = [Y2, Y1];
6127 }
6128
6129 let denom = Y1 + Y2;
6130 return denom === 0 ? 0 : (Y1 - Y2) / denom;
6131 }
6132
6133 // Weber luminance contrast
6134 // The difference between the two luminances divided by the lower luminance
6135 // Symmetric, does not matter which is foreground and which is background
6136 // No black level compensation for flare.
6137
6138
6139 // the darkest sRGB color above black is #000001 and this produces
6140 // a plain Weber contrast of ~45647.
6141 // So, setting the divide-by-zero result at 50000 is a reasonable
6142 // max clamp for the plain Weber
6143 const max = 50000;
6144
6145 /**
6146 * @param {import("../types.js").ColorTypes} color1
6147 * @param {import("../types.js").ColorTypes} color2
6148 * @returns {number}
6149 */
6150 function contrastWeber (color1, color2) {
6151 color1 = getColor(color1);
6152 color2 = getColor(color2);
6153
6154 let Y1 = Math.max(getLuminance(color1), 0);
6155 let Y2 = Math.max(getLuminance(color2), 0);
6156
6157 if (Y2 > Y1) {
6158 [Y1, Y2] = [Y2, Y1];
6159 }
6160
6161 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
6162 }
6163
6164 // CIE Lightness difference, as used by Google Material Design
6165 // Google HCT Tone is the same as CIE Lightness
6166 // https://material.io/blog/science-of-color-design
6167
6168
6169 /**
6170 * @param {import("../types.js").ColorTypes} color1
6171 * @param {import("../types.js").ColorTypes} color2
6172 * @returns {number}
6173 */
6174 function contrastLstar (color1, color2) {
6175 color1 = getColor(color1);
6176 color2 = getColor(color2);
6177
6178 let L1 = get(color1, [lab, "l"]);
6179 let L2 = get(color2, [lab, "l"]);
6180
6181 return Math.abs(L1 - L2);
6182 }
6183
6184 // κ * ε = 2^3 = 8
6185 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6186 const ε3 = 24 / 116;
6187 const κ$2 = 24389 / 27; // 29^3/3^3
6188
6189 let white$1 = WHITES.D65;
6190
6191 var lab_d65 = new ColorSpace({
6192 id: "lab-d65",
6193 name: "Lab D65",
6194 coords: {
6195 l: {
6196 refRange: [0, 100],
6197 name: "Lightness",
6198 },
6199 a: {
6200 refRange: [-125, 125],
6201 },
6202 b: {
6203 refRange: [-125, 125],
6204 },
6205 },
6206
6207 // Assuming XYZ is relative to D65, convert to CIE Lab
6208 // from CIE standard, which now defines these as a rational fraction
6209 white: white$1,
6210
6211 base: XYZ_D65,
6212 // Convert D65-adapted XYZ to Lab
6213 // CIE 15.3:2004 section 8.2.1.1
6214 fromBase (XYZ) {
6215 // compute xyz, which is XYZ scaled relative to reference white
6216 let xyz = XYZ.map((value, i) => value / white$1[i]);
6217
6218 // now compute f
6219 let f = xyz.map(value => (value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116));
6220
6221 return [
6222 116 * f[1] - 16, // L
6223 500 * (f[0] - f[1]), // a
6224 200 * (f[1] - f[2]), // b
6225 ];
6226 },
6227 // Convert Lab to D65-adapted XYZ
6228 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
6229 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
6230 toBase (Lab) {
6231 // compute f, starting with the luminance-related term
6232 let f = [];
6233 f[1] = (Lab[0] + 16) / 116;
6234 f[0] = Lab[1] / 500 + f[1];
6235 f[2] = f[1] - Lab[2] / 200;
6236
6237 // compute xyz
6238 let xyz = [
6239 f[0] > ε3 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$2,
6240 Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$2,
6241 f[2] > ε3 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$2,
6242 ];
6243
6244 // Compute XYZ by scaling xyz by reference white
6245 return xyz.map((value, i) => value * white$1[i]);
6246 },
6247
6248 formats: {
6249 "lab-d65": {
6250 coords: [
6251 "<number> | <percentage>",
6252 "<number> | <percentage>",
6253 "<number> | <percentage>",
6254 ],
6255 },
6256 },
6257 });
6258
6259 // Delta Phi Star perceptual lightness contrast
6260 // See https://github.com/Myndex/deltaphistar
6261 // The (difference between two Lstars each raised to phi) raised to (1/phi)
6262 // Symmetric, does not matter which is foreground and which is background
6263
6264
6265 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
6266
6267 /**
6268 * @param {import("../types.js").ColorTypes} color1
6269 * @param {import("../types.js").ColorTypes} color2
6270 * @returns {number}
6271 */
6272 function contrastDeltaPhi (color1, color2) {
6273 color1 = getColor(color1);
6274 color2 = getColor(color2);
6275
6276 let Lstr1 = get(color1, [lab_d65, "l"]);
6277 let Lstr2 = get(color2, [lab_d65, "l"]);
6278
6279 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
6280
6281 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
6282
6283 return contrast < 7.5 ? 0.0 : contrast;
6284 }
6285
6286 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
6287
6288 var contrastMethods = /*#__PURE__*/Object.freeze({
6289 __proto__: null,
6290 contrastAPCA: contrastAPCA,
6291 contrastDeltaPhi: contrastDeltaPhi,
6292 contrastLstar: contrastLstar,
6293 contrastMichelson: contrastMichelson,
6294 contrastWCAG21: contrastWCAG21,
6295 contrastWeber: contrastWeber
6296 });
6297
6298 /** @import { ColorTypes } from "./types.js" */
6299
6300 // Type re-exports
6301 /** @typedef {import("./types.js").Algorithms} Algorithms */
6302
6303 /**
6304 *
6305 * @param {ColorTypes} background
6306 * @param {ColorTypes} foreground
6307 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
6308 * Algorithm to use as well as any other options to pass to the contrast function
6309 * @returns {number}
6310 * @throws {TypeError} Unknown or unspecified algorithm
6311 */
6312 function contrast (background, foreground, o) {
6313 if (isString(o)) {
6314 o = { algorithm: o };
6315 }
6316
6317 let { algorithm, ...rest } = o || {};
6318
6319 if (!algorithm) {
6320 let algorithms = Object.keys(contrastMethods)
6321 .map(a => a.replace(/^contrast/, ""))
6322 .join(", ");
6323 throw new TypeError(
6324 `contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`,
6325 );
6326 }
6327
6328 background = getColor(background);
6329 foreground = getColor(foreground);
6330
6331 for (let a in contrastMethods) {
6332 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
6333 return contrastMethods[a](background, foreground, rest);
6334 }
6335 }
6336
6337 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
6338 }
6339
6340 /** @import Color, { ColorTypes } from "./color.js" */
6341
6342 // Chromaticity coordinates
6343 /**
6344 * @param {ColorTypes} color
6345 * @returns {[number, number]}
6346 */
6347 function uv (color) {
6348 // Assumes getAll() calls getColor() on color
6349 let [X, Y, Z] = getAll(color, XYZ_D65);
6350 let denom = X + 15 * Y + 3 * Z;
6351 return [(4 * X) / denom, (9 * Y) / denom];
6352 }
6353
6354 /**
6355 * @param {ColorTypes} color
6356 * @returns {[number, number]}
6357 */
6358 function xy (color) {
6359 // Assumes getAll() calls getColor() on color
6360 let [X, Y, Z] = getAll(color, XYZ_D65);
6361 let sum = X + Y + Z;
6362 return [X / sum, Y / sum];
6363 }
6364
6365 /**
6366 * @param {typeof Color} Color
6367 */
6368 function register$1 (Color) {
6369 // no setters, as lightness information is lost
6370 // when converting color to chromaticity
6371 Object.defineProperty(Color.prototype, "uv", {
6372 get () {
6373 return uv(this);
6374 },
6375 });
6376
6377 Object.defineProperty(Color.prototype, "xy", {
6378 get () {
6379 return xy(this);
6380 },
6381 });
6382 }
6383
6384 var chromaticity = /*#__PURE__*/Object.freeze({
6385 __proto__: null,
6386 register: register$1,
6387 uv: uv,
6388 xy: xy
6389 });
6390
6391 /** @import { ColorTypes } from "./types.js" */
6392
6393 // Type re-exports
6394 /** @typedef {import("./types.js").Methods} Methods */
6395
6396 /**
6397 *
6398 * @param {ColorTypes} c1
6399 * @param {ColorTypes} c2
6400 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
6401 * deltaE method to use as well as any other options to pass to the deltaE function
6402 * @returns {number}
6403 * @throws {TypeError} Unknown or unspecified method
6404 */
6405 function deltaE (c1, c2, o = {}) {
6406 if (isString(o)) {
6407 o = { method: o };
6408 }
6409
6410 let { method = defaults.deltaE, ...rest } = o;
6411
6412 for (let m in deltaEMethods) {
6413 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
6414 return deltaEMethods[m](c1, c2, rest);
6415 }
6416 }
6417
6418 throw new TypeError(`Unknown deltaE method: ${method}`);
6419 }
6420
6421 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
6422
6423 /**
6424 * @param {ColorTypes} color
6425 * @param {number} amount
6426 * @returns {PlainColorObject}
6427 */
6428 function lighten (color, amount = 0.25) {
6429 let space = ColorSpace.get("oklch", "lch");
6430 let /** @type {Ref} */ lightness = [space, "l"];
6431 return set(color, lightness, l => l * (1 + amount));
6432 }
6433
6434 /**
6435 * @param {ColorTypes} color
6436 * @param {number} amount
6437 * @returns {PlainColorObject}
6438 */
6439 function darken (color, amount = 0.25) {
6440 let space = ColorSpace.get("oklch", "lch");
6441 let /** @type {Ref} */ lightness = [space, "l"];
6442 return set(color, lightness, l => l * (1 - amount));
6443 }
6444
6445 /** @type {"color"} */
6446 lighten.returns = "color";
6447
6448 /** @type {"color"} */
6449 darken.returns = "color";
6450
6451 var variations = /*#__PURE__*/Object.freeze({
6452 __proto__: null,
6453 darken: darken,
6454 lighten: lighten
6455 });
6456
6457 /**
6458 * Functions related to color interpolation
6459 */
6460
6461 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
6462
6463 // Type re-exports
6464 /** @typedef {import("./types.js").MixOptions} MixOptions */
6465 /** @typedef {import("./types.js").Range} Range */
6466 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
6467 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
6468
6469 /**
6470 * Return an intermediate color between two colors
6471 * @overload
6472 * @param {ColorTypes} c1
6473 * @param {ColorTypes} c2
6474 * @param {MixOptions} [options]
6475 * @returns {PlainColorObject}
6476 */
6477 /**
6478 * @overload
6479 * @param {ColorTypes} c1
6480 * @param {ColorTypes} c2
6481 * @param {number} [p=0.5]
6482 * @param {MixOptions} [options]
6483 * @returns {PlainColorObject}
6484 */
6485 function mix (c1, c2, p, o = {}) {
6486 [c1, c2] = [getColor(c1), getColor(c2)];
6487
6488 if (type(p) === "object") {
6489 [p, o] = [0.5, p];
6490 }
6491
6492 let r = range(c1, c2, o);
6493 return r(p ?? 0.5); // why not give p a default value like we do for options? Overloading doesn't work, and TS complains
6494 }
6495
6496 /**
6497 * Get an array of discrete steps
6498 * @overload
6499 * @param {ColorTypes} c1
6500 * @param {ColorTypes} c2
6501 * @param {StepsOptions} [options]
6502 * @returns {PlainColorObject[]}
6503 */
6504 /**
6505 * @overload
6506 * @param {Range} range
6507 * @param {StepsOptions} [options]
6508 * @returns {PlainColorObject[]}
6509 */
6510 function steps (c1, c2, options = {}) {
6511 let colorRange;
6512
6513 if (isRange(c1)) {
6514 // Tweaking existing range
6515 [colorRange, options] = [c1, c2];
6516 [c1, c2] = colorRange.rangeArgs.colors;
6517 }
6518
6519 let { maxDeltaE, deltaEMethod, steps = 2, maxSteps = 1000, ...rangeOptions } = options;
6520
6521 if (!colorRange) {
6522 [c1, c2] = [getColor(c1), getColor(c2)];
6523 colorRange = range(c1, c2, rangeOptions);
6524 }
6525
6526 let totalDelta = deltaE(c1, c2, deltaEMethod);
6527 let actualSteps =
6528 maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
6529 let ret = [];
6530
6531 if (maxSteps !== undefined) {
6532 actualSteps = Math.min(actualSteps, maxSteps);
6533 }
6534
6535 if (actualSteps === 1) {
6536 ret = [{ p: 0.5, color: colorRange(0.5) }];
6537 }
6538 else {
6539 let step = 1 / (actualSteps - 1);
6540 ret = Array.from({ length: actualSteps }, (_, i) => {
6541 let p = i * step;
6542 return { p, color: colorRange(p) };
6543 });
6544 }
6545
6546 if (maxDeltaE > 0) {
6547 // Iterate over all stops and find max deltaE
6548 let maxDelta = ret.reduce((acc, cur, i) => {
6549 if (i === 0) {
6550 return 0;
6551 }
6552
6553 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
6554 return Math.max(acc, ΔΕ);
6555 }, 0);
6556
6557 while (maxDelta > maxDeltaE) {
6558 // Insert intermediate stops and measure maxDelta again
6559 // We need to do this for all pairs, otherwise the midpoint shifts
6560 maxDelta = 0;
6561
6562 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
6563 let prev = ret[i - 1];
6564 let cur = ret[i];
6565
6566 let p = (cur.p + prev.p) / 2;
6567 let color = colorRange(p);
6568 maxDelta = Math.max(
6569 maxDelta,
6570 deltaE(color, prev.color, deltaEMethod),
6571 deltaE(color, cur.color, deltaEMethod),
6572 );
6573 ret.splice(i, 0, { p, color: colorRange(p) });
6574 i++;
6575 }
6576 }
6577 }
6578
6579 ret = ret.map(a => a.color);
6580
6581 return ret;
6582 }
6583
6584 /**
6585 * Creates a function that accepts a number and returns a color.
6586 * For numbers in the range 0 to 1, the function interpolates;
6587 * for numbers outside that range, the function extrapolates
6588 * (and thus may not return the results you expect)
6589 * @overload
6590 * @param {Range} range
6591 * @param {RangeOptions} [options]
6592 * @returns {Range}
6593 */
6594 /**
6595 * @overload
6596 * @param {ColorTypes} color1
6597 * @param {ColorTypes} color2
6598 * @param {RangeOptions & Record<string, any>} [options]
6599 * @returns {Range}
6600 */
6601 function range (color1, color2, options = {}) {
6602 if (isRange(color1)) {
6603 // Tweaking existing range
6604 let [r, options] = [color1, color2];
6605
6606 return range(...r.rangeArgs.colors, { ...r.rangeArgs.options, ...options });
6607 }
6608
6609 let { space, outputSpace, progression, premultiplied } = options;
6610
6611 color1 = getColor(color1);
6612 color2 = getColor(color2);
6613
6614 // Make sure we're working on copies of these colors
6615 color1 = clone(color1);
6616 color2 = clone(color2);
6617
6618 let rangeArgs = { colors: [color1, color2], options };
6619
6620 if (space) {
6621 space = ColorSpace.get(space);
6622 }
6623 else {
6624 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
6625 }
6626
6627 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
6628
6629 color1 = to(color1, space);
6630 color2 = to(color2, space);
6631
6632 // Gamut map to avoid areas of flat color
6633 color1 = toGamut(color1);
6634 color2 = toGamut(color2);
6635
6636 // The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz)
6637 let hueId = space.hueId;
6638 let hueIndex = space.hueIndex;
6639
6640 // Handle hue interpolation
6641 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
6642 if (hueId) {
6643 let arc = (options.hue = options.hue || "shorter");
6644
6645 let /** @type {Ref} */ hue = [space, hueId];
6646 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
6647 // Undefined hues must be evaluated before hue fix-up to properly
6648 // calculate hue arcs between undefined and defined hues.
6649 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
6650 if (isNone(θ1) && !isNone(θ2)) {
6651 θ1 = θ2;
6652 }
6653 else if (isNone(θ2) && !isNone(θ1)) {
6654 θ2 = θ1;
6655 }
6656 [θ1, θ2] = adjust(arc, [θ1, θ2]);
6657 set(color1, hue, θ1);
6658 set(color2, hue, θ2);
6659 }
6660
6661 // An undefined alpha takes the other color's alpha, and premultiplication must use
6662 // that carried forward value, rather than the zero it would otherwise be treated as.
6663 // If both alphas are undefined, they stay that way, and no premultiplication happens.
6664 // See https://drafts.csswg.org/css-color-4/#interpolation-missing
6665 if (isNone(color1.alpha) && !isNone(color2.alpha)) {
6666 color1.alpha = color2.alpha;
6667 }
6668 else if (isNone(color2.alpha) && !isNone(color1.alpha)) {
6669 color2.alpha = color1.alpha;
6670 }
6671
6672 if (premultiplied) {
6673 color1.coords = premultiply(color1.coords, color1.alpha, hueIndex);
6674 color2.coords = premultiply(color2.coords, color2.alpha, hueIndex);
6675 }
6676
6677 return Object.assign(
6678 p => {
6679 p = progression ? progression(p) : p;
6680 let coords = color1.coords.map((start, i) => {
6681 let end = color2.coords[i];
6682 return interpolate(start, end, p);
6683 });
6684
6685 let alpha = interpolate(color1.alpha, color2.alpha, p);
6686 let ret = { space, coords, alpha };
6687
6688 if (premultiplied) {
6689 // Undo premultiplication, again leaving any hue angle untouched
6690 ret.coords = premultiply(ret.coords, alpha, hueIndex, true);
6691 }
6692
6693 if (outputSpace !== space) {
6694 ret = to(ret, outputSpace);
6695 }
6696
6697 return ret;
6698 },
6699 {
6700 rangeArgs,
6701 },
6702 );
6703 }
6704
6705 /**
6706 * Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it.
6707 * Per CSS Color 4, the hue angle of a polar space is never premultiplied,
6708 * `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all,
6709 * and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero.
6710 * See https://drafts.csswg.org/css-color-4/#interpolation-alpha
6711 * @param {(number | null)[]} coords
6712 * @param {number | null} alpha
6713 * @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none
6714 * @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it
6715 * @returns {[number, number, number]}
6716 */
6717 function premultiply (coords, alpha, hueIndex, undo = false) {
6718 if (isNone(alpha) || (undo && alpha === 0)) {
6719 // The (un-)premultiplied value is the value itself
6720 return /** @type {[number, number, number]} */ (coords);
6721 }
6722
6723 return /** @type {[number, number, number]} */ (
6724 coords.map((c, i) => {
6725 if (i === hueIndex || isNone(c)) {
6726 return c;
6727 }
6728
6729 return undo ? c / alpha : c * alpha;
6730 })
6731 );
6732 }
6733
6734 /**
6735 * @param {any} val
6736 * @returns {val is Range}
6737 */
6738 function isRange (val) {
6739 return type(val) === "function" && !!val.rangeArgs;
6740 }
6741
6742 defaults.interpolationSpace = "lab";
6743
6744 /**
6745 * @param {typeof import("./color.js").default} Color
6746 */
6747 function register (Color) {
6748 Color.defineFunction("mix", mix, { returns: "color" });
6749 Color.defineFunction("range", range, { returns: "function<color>" });
6750 Color.defineFunction("steps", steps, { returns: "array<color>" });
6751 }
6752
6753 var interpolation = /*#__PURE__*/Object.freeze({
6754 __proto__: null,
6755 isRange: isRange,
6756 mix: mix,
6757 range: range,
6758 register: register,
6759 steps: steps
6760 });
6761
6762 var HSL = new ColorSpace({
6763 id: "hsl",
6764 name: "HSL",
6765 coords: {
6766 h: {
6767 refRange: [0, 360],
6768 type: "angle",
6769 name: "Hue",
6770 },
6771 s: {
6772 range: [0, 100],
6773 name: "Saturation",
6774 },
6775 l: {
6776 range: [0, 100],
6777 name: "Lightness",
6778 },
6779 },
6780
6781 base: sRGB,
6782 rgbGamut: sRGB,
6783
6784 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
6785 fromBase: rgb => {
6786 let max = Math.max(...rgb);
6787 let min = Math.min(...rgb);
6788 let [r, g, b] = rgb;
6789 let [h, s, l] = [null, 0, (min + max) / 2];
6790 let d = max - min;
6791
6792 if (d !== 0) {
6793 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
6794
6795 switch (max) {
6796 case r:
6797 h = (g - b) / d + (g < b ? 6 : 0);
6798 break;
6799 case g:
6800 h = (b - r) / d + 2;
6801 break;
6802 case b:
6803 h = (r - g) / d + 4;
6804 }
6805
6806 h = h * 60;
6807 }
6808
6809 // Very out of gamut colors can produce negative saturation
6810 // If so, just rotate the hue by 180 and use a positive saturation
6811 // see https://github.com/w3c/csswg-drafts/issues/9222
6812 if (s < 0) {
6813 h += 180;
6814 s = Math.abs(s);
6815 }
6816
6817 if (h >= 360) {
6818 h -= 360;
6819 }
6820
6821 return [h, s * 100, l * 100];
6822 },
6823
6824 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
6825 toBase: hsl => {
6826 let [h, s, l] = hsl;
6827 h = h % 360;
6828
6829 if (h < 0) {
6830 h += 360;
6831 }
6832
6833 s /= 100;
6834 l /= 100;
6835
6836 function f (n) {
6837 let k = (n + h / 30) % 12;
6838 let a = s * Math.min(l, 1 - l);
6839 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
6840 }
6841
6842 return [f(0), f(8), f(4)];
6843 },
6844
6845 formats: {
6846 hsl: {
6847 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
6848 },
6849 hsla: {
6850 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
6851 commas: true,
6852 alpha: true,
6853 },
6854 }
6855 });
6856
6857 var hslP3 = new ColorSpace({
6858 id: "hsl-p3",
6859 cssId: "--hsl-p3",
6860 name: "HSL P3",
6861 coords: {
6862 h: {
6863 refRange: [0, 360],
6864 type: "angle",
6865 name: "Hue",
6866 },
6867 s: {
6868 range: [0, 100],
6869 name: "Saturation",
6870 },
6871 l: {
6872 range: [0, 100],
6873 name: "Lightness",
6874 },
6875 },
6876
6877 base: P3,
6878 rgbGamut: P3,
6879 fromBase: HSL.fromBase,
6880 toBase: HSL.toBase,
6881 });
6882
6883 var hslRec2020 = new ColorSpace({
6884 id: "hsl-rec2020",
6885 cssId: "--hsl-rec2020",
6886 name: "HSL Rec.2020",
6887 coords: {
6888 h: {
6889 refRange: [0, 360],
6890 type: "angle",
6891 name: "Hue",
6892 },
6893 s: {
6894 range: [0, 100],
6895 name: "Saturation",
6896 },
6897 l: {
6898 range: [0, 100],
6899 name: "Lightness",
6900 },
6901 },
6902
6903 base: REC2020,
6904 rgbGamut: REC2020,
6905 fromBase: HSL.fromBase,
6906 toBase: HSL.toBase,
6907 });
6908
6909 // Note that, like HSL, calculations are done directly on
6910 // gamma-corrected sRGB values rather than linearising them first.
6911
6912 var HSV = new ColorSpace({
6913 id: "hsv",
6914 name: "HSV",
6915 coords: {
6916 h: {
6917 refRange: [0, 360],
6918 type: "angle",
6919 name: "Hue",
6920 },
6921 s: {
6922 range: [0, 100],
6923 name: "Saturation",
6924 },
6925 v: {
6926 range: [0, 100],
6927 name: "Value",
6928 },
6929 },
6930
6931 base: sRGB,
6932 rgbGamut: sRGB,
6933 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
6934 fromBase (rgb) {
6935 let max = Math.max(...rgb);
6936 let min = Math.min(...rgb);
6937 let [r, g, b] = rgb;
6938 let [h, s, v] = [null, 0, max];
6939 let d = max - min;
6940
6941 if (d !== 0) {
6942 switch (max) {
6943 case r:
6944 h = (g - b) / d + (g < b ? 6 : 0);
6945 break;
6946 case g:
6947 h = (b - r) / d + 2;
6948 break;
6949 case b:
6950 h = (r - g) / d + 4;
6951 }
6952
6953 h = h * 60;
6954 }
6955
6956 if (v) {
6957 s = d / v;
6958 }
6959
6960 if (h >= 360) {
6961 h -= 360;
6962 }
6963
6964 return [h, s * 100, v * 100];
6965 },
6966 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
6967 toBase (hsv) {
6968 let [h, s, v] = hsv;
6969 h = h % 360;
6970
6971 if (h < 0) {
6972 h += 360;
6973 }
6974
6975 s /= 100;
6976 v /= 100;
6977
6978 function f (n) {
6979 let k = (n + h / 60) % 6;
6980 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
6981 }
6982
6983 return [f(5), f(3), f(1)];
6984 },
6985
6986 formats: {
6987 color: {
6988 id: "--hsv",
6989 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
6990 },
6991 },
6992 });
6993
6994 // The Hue, Whiteness Blackness (HWB) colorspace
6995 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
6996 // Note that, like HSL, calculations are done directly on
6997 // gamma-corrected sRGB values rather than linearising them first.
6998
6999 var hwb = new ColorSpace({
7000 id: "hwb",
7001 name: "HWB",
7002 coords: {
7003 h: {
7004 refRange: [0, 360],
7005 type: "angle",
7006 name: "Hue",
7007 },
7008 w: {
7009 range: [0, 100],
7010 name: "Whiteness",
7011 },
7012 b: {
7013 range: [0, 100],
7014 name: "Blackness",
7015 },
7016 },
7017
7018 base: HSV,
7019 rgbGamut: sRGB,
7020 fromBase (hsv) {
7021 let [h, s, v] = hsv;
7022
7023 return [h, (v * (100 - s)) / 100, 100 - v];
7024 },
7025 toBase (hwb) {
7026 let [h, w, b] = hwb;
7027
7028 // Now convert percentages to [0..1]
7029 w /= 100;
7030 b /= 100;
7031
7032 // Achromatic check (white plus black >= 1)
7033 let sum = w + b;
7034 if (sum >= 1) {
7035 let gray = w / sum;
7036 return [h, 0, gray * 100];
7037 }
7038
7039 let v = 1 - b;
7040 let s = v === 0 ? 0 : 1 - w / v;
7041 return [h, s * 100, v * 100];
7042 },
7043
7044 formats: {
7045 hwb: {
7046 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
7047 },
7048 },
7049 });
7050
7051 /** @import { Matrix3x3 } from "../types.js" */
7052
7053 // convert an array of linear-light a98-rgb values to CIE XYZ
7054 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
7055 // has greater numerical precision than section 4.3.5.3 of
7056 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
7057 // but the values below were calculated from first principles
7058 // from the chromaticity coordinates of R G B W
7059
7060 /**
7061 * Matrices used by this color space, also available as `A98RGB_Linear.M`
7062 * @type {Record<string, Matrix3x3>}
7063 */
7064 // prettier-ignore
7065 const M$5 = {
7066 toXYZ: [
7067 [ 0.5766690429101305, 0.1855582379065463, 0.1882286462349947 ],
7068 [ 0.29734497525053605, 0.6273635662554661, 0.07529145849399788 ],
7069 [ 0.02703136138641234, 0.07068885253582723, 0.9913375368376388 ],
7070 ],
7071 fromXYZ: [
7072 [ 2.0415879038107465, -0.5650069742788596, -0.34473135077832956 ],
7073 [ -0.9692436362808795, 1.8759675015077202, 0.04155505740717557 ],
7074 [ 0.013444280632031142, -0.11836239223101838, 1.0151749943912054 ],
7075 ],
7076 };
7077
7078 var A98Linear = new RGBColorSpace({
7079 id: "a98rgb-linear",
7080 cssId: "--a98-rgb-linear",
7081 name: "Linear Adobe® 98 RGB compatible",
7082 white: "D65",
7083 M: M$5,
7084 });
7085
7086 var a98rgb = new RGBColorSpace({
7087 id: "a98rgb",
7088 cssId: "a98-rgb",
7089 name: "Adobe® 98 RGB compatible",
7090 base: A98Linear,
7091 linearGamut: A98Linear,
7092 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
7093 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val)),
7094 });
7095
7096 /** @import { Matrix3x3 } from "../types.js" */
7097
7098 /**
7099 * Matrices used by this color space, also available as `ProPhoto_Linear.M`.
7100 * Uses D50 (so no chromatic adaptation needed afterwards). The matrix cannot
7101 * be expressed in rational form, but is calculated to 64 bit accuracy.
7102 * see https://github.com/w3c/csswg-drafts/issues/7675
7103 * @type {Record<string, Matrix3x3>}
7104 */
7105 // prettier-ignore
7106 const M$4 = {
7107 toXYZ: [
7108 [ 0.79776664490064230, 0.13518129740053308, 0.03134773412839220 ],
7109 [ 0.28807482881940130, 0.71183523424187300, 0.00008993693872564 ],
7110 [ 0.00000000000000000, 0.00000000000000000, 0.82510460251046020 ],
7111 ],
7112 fromXYZ: [
7113 [ 1.34578688164715830, -0.25557208737979464, -0.05110186497554526 ],
7114 [ -0.54463070512490190, 1.50824774284514680, 0.02052744743642139 ],
7115 [ 0.00000000000000000, 0.00000000000000000, 1.21196754563894520 ],
7116 ],
7117 };
7118
7119 var ProPhotoLinear = new RGBColorSpace({
7120 id: "prophoto-linear",
7121 cssId: "--prophoto-rgb-linear",
7122 name: "Linear ProPhoto",
7123 white: "D50",
7124 base: XYZ_D50,
7125 M: M$4,
7126 });
7127
7128 const Et = 1 / 512;
7129 const Et2 = 16 / 512;
7130
7131 var prophoto = new RGBColorSpace({
7132 id: "prophoto",
7133 cssId: "prophoto-rgb",
7134 name: "ProPhoto",
7135 base: ProPhotoLinear,
7136 linearGamut: ProPhotoLinear,
7137 toBase (RGB) {
7138 // Transfer curve is gamma 1.8 with a small linear portion
7139 return RGB.map(v => {
7140 let sign = v < 0 ? -1 : 1;
7141 let abs = v * sign;
7142
7143 if (abs < Et2) {
7144 return v / 16;
7145 }
7146
7147 return sign * abs ** 1.8;
7148 });
7149 },
7150 fromBase (RGB) {
7151 return RGB.map(v => {
7152 let sign = v < 0 ? -1 : 1;
7153 let abs = v * sign;
7154
7155 if (abs >= Et) {
7156 return sign * abs ** (1 / 1.8);
7157 }
7158
7159 return 16 * v;
7160 });
7161 },
7162 });
7163
7164 // import sRGB from "./srgb.js";
7165
7166 const α = 1.09929682680944;
7167 const β = 0.018053968510807;
7168
7169 var rec2020Oetf = new RGBColorSpace({
7170 id: "--rec2020-oetf",
7171 name: "REC.2020_Scene_Referred",
7172 base: REC2020Linear,
7173 linearGamut: REC2020Linear,
7174 referred: "scene",
7175 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
7176 toBase (RGB) {
7177 return RGB.map(function (val) {
7178 let sign = val < 0 ? -1 : 1;
7179 let abs = val * sign;
7180
7181 if (abs < β * 4.5) {
7182 return val / 4.5;
7183 }
7184
7185 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
7186 });
7187 },
7188 fromBase (RGB) {
7189 return RGB.map(function (val) {
7190 let sign = val < 0 ? -1 : 1;
7191 let abs = val * sign;
7192
7193 if (abs >= β) {
7194 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
7195 }
7196
7197 return 4.5 * val;
7198 });
7199 },
7200 });
7201
7202 var oklchP3 = new GamutRelativeColorSpace({
7203 id: "oklch-p3",
7204 cssId: "--oklch-p3",
7205 name: "OKLCh P3",
7206 base: OKLCH,
7207 gamutSpace: P3,
7208 });
7209
7210 var oklchSrgb = new GamutRelativeColorSpace({
7211 id: "oklch-srgb",
7212 cssId: "--oklch-srgb",
7213 name: "OKLCh sRGB",
7214 base: OKLCH,
7215 gamutSpace: sRGB,
7216 });
7217
7218 var oklchRec2020 = new GamutRelativeColorSpace({
7219 id: "oklch-rec2020",
7220 cssId: "--oklch-rec2020",
7221 name: "OKLCh Rec.2020",
7222 base: OKLCH,
7223 gamutSpace: REC2020,
7224 });
7225
7226 var lchP3 = new GamutRelativeColorSpace({
7227 id: "lch-p3",
7228 cssId: "--lch-p3",
7229 name: "LCH P3",
7230 base: lch,
7231 gamutSpace: P3,
7232 });
7233
7234 var lchSrgb = new GamutRelativeColorSpace({
7235 id: "lch-srgb",
7236 cssId: "--lch-srgb",
7237 name: "LCH sRGB",
7238 base: lch,
7239 gamutSpace: sRGB,
7240 });
7241
7242 var lchRec2020 = new GamutRelativeColorSpace({
7243 id: "lch-rec2020",
7244 cssId: "--lch-rec2020",
7245 name: "LCH Rec.2020",
7246 base: lch,
7247 gamutSpace: REC2020,
7248 });
7249
7250 // Okhsl class.
7251 //
7252 // ---- License ----
7253 //
7254 // Copyright (c) 2021 Björn Ottosson
7255 //
7256 // Permission is hereby granted, free of charge, to any person obtaining a copy of
7257 // this software and associated documentation files (the "Software"), to deal in
7258 // the Software without restriction, including without limitation the rights to
7259 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7260 // of the Software, and to permit persons to whom the Software is furnished to do
7261 // so, subject to the following conditions:
7262 //
7263 // The above copyright notice and this permission notice shall be included in all
7264 // copies or substantial portions of the Software.
7265 //
7266 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7267 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7268 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7269 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
7270 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
7271 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
7272 // SOFTWARE.
7273
7274 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7275
7276 // Type re-exports
7277 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
7278
7279 const tau = 2 * Math.PI;
7280
7281 /**
7282 * Matrices used by this color space (Oklab's, plus its own),
7283 * also available as `Okhsl.M`
7284 * @type {Record<string, Matrix3x3>}
7285 */
7286 // prettier-ignore
7287 const M$3 = {
7288 ...Oklab.M,
7289 toLMS: [
7290 [0.4122214694707629, 0.5363325372617349, 0.0514459932675022],
7291 [0.2119034958178251, 0.6806995506452344, 0.1073969535369405],
7292 [0.0883024591900564, 0.2817188391361215, 0.6299787016738222],
7293 ],
7294 toSRGBLinear: [
7295 [ 4.0767416360759583, -3.3077115392580629, 0.2309699031821043],
7296 [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570],
7297 [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117],
7298 ],
7299 };
7300
7301 /** @type {OKCoeff} */
7302 const RGBCoeff = [
7303 // Red
7304 [
7305 // Limit
7306 [-1.8817031, -0.80936501],
7307 // `Kn` coefficients
7308 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245],
7309 ],
7310 // Green
7311 [
7312 // Limit
7313 [1.8144408, -1.19445267],
7314 // `Kn` coefficients
7315 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204],
7316 ],
7317 // Blue
7318 [
7319 // Limit
7320 [0.13110758, 1.81333971],
7321 // `Kn` coefficients
7322 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167],
7323 ],
7324 ];
7325
7326 const floatMax = Number.MAX_VALUE;
7327 const K1 = 0.206;
7328 const K2 = 0.03;
7329 const K3 = (1.0 + K1) / (1.0 + K2);
7330
7331 function vdot (a, b) {
7332 // Dot two vectors
7333
7334 let l = a.length;
7335 if (l !== b.length) {
7336 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
7337 }
7338
7339 let s = 0.0;
7340 a.forEach((c, i) => {
7341 s += c * b[i];
7342 });
7343
7344 return s;
7345 }
7346
7347 /**
7348 * Toe function for L_r
7349 * @param {number} x
7350 */
7351 function toe (x) {
7352 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
7353 }
7354
7355 /**
7356 * Inverse toe function for L_r
7357 * @param {number} x
7358 */
7359 function toeInv (x) {
7360 return (x ** 2 + K1 * x) / (K3 * (x + K2));
7361 }
7362
7363 /**
7364 * @param {readonly [number, number]} cusp
7365 * @returns {[number, number]}
7366 */
7367 function toSt (cusp) {
7368 // To ST.
7369
7370 let [l, c] = cusp;
7371 return [c / l, c / (1 - l)];
7372 }
7373
7374 function getStMid (a, b) {
7375 // Returns a smooth approximation of the location of the cusp.
7376 //
7377 // This polynomial was created by an optimization process.
7378 // It has been designed so that S_mid < S_max and T_mid < T_max.
7379
7380 // prettier-ignore
7381 let s = 0.11516993 + 1.0 / (
7382 7.44778970 + 4.15901240 * b +
7383 a * (
7384 -2.19557347 + 1.75198401 * b +
7385 a * (
7386 -2.13704948 - 10.02301043 * b +
7387 a * (
7388 -4.24894561 + 5.38770819 * b + 4.69891013 * a
7389 )
7390 )
7391 )
7392 );
7393
7394 // prettier-ignore
7395 let t = 0.11239642 + 1.0 / (
7396 1.61320320 - 0.68124379 * b +
7397 a * (
7398 0.40370612 + 0.90148123 * b +
7399 a * (
7400 -0.27087943 + 0.61223990 * b +
7401 a * (
7402 0.00299215 - 0.45399568 * b - 0.14661872 * a
7403 )
7404 )
7405 )
7406 );
7407
7408 return [s, t];
7409 }
7410
7411 /**
7412 * @param {Vector3} lab
7413 * @param {Matrix3x3} lmsToRgb
7414 */
7415 function oklabToLinearRGB (lab, lmsToRgb) {
7416 // Convert from Oklab to linear RGB.
7417 //
7418 // Can be any gamut as long as `lmsToRgb` is a matrix
7419 // that transform the LMS values to the linear RGB space.
7420
7421 let lms = multiply_v3_m3x3(lab, M$3.LabtoLMS);
7422
7423 lms[0] = lms[0] ** 3;
7424 lms[1] = lms[1] ** 3;
7425 lms[2] = lms[2] ** 3;
7426
7427 return multiply_v3_m3x3(lms, lmsToRgb, lms);
7428 }
7429
7430 /**
7431 * @param {number} a
7432 * @param {number} b
7433 * @param {Matrix3x3} lmsToRgb
7434 * @param {OKCoeff} okCoeff
7435 * @returns {[number, number]}
7436 * @todo Could probably make these types more specific/better-documented if desired
7437 */
7438 function findCusp (a, b, lmsToRgb, okCoeff) {
7439 // Finds L_cusp and C_cusp for a given hue.
7440 //
7441 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
7442
7443 // First, find the maximum saturation (saturation `S = C/L`)
7444 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
7445
7446 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
7447 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
7448 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
7449 let cCusp = lCusp * sCusp;
7450
7451 return [lCusp, cCusp];
7452 }
7453
7454 /**
7455 * @param {number} a
7456 * @param {number} b
7457 * @param {number} l1
7458 * @param {number} c1
7459 * @param {number} l0
7460 * @param {Matrix3x3} lmsToRgb
7461 * @param {OKCoeff} okCoeff
7462 * @param {[number, number]} cusp
7463 * @returns {Number}
7464 * @todo Could probably make these types more specific/better-documented if desired
7465 */
7466 function findGamutIntersection (a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
7467 // Finds intersection of the line.
7468 //
7469 // Defined by the following:
7470 //
7471 // ```
7472 // L = L0 * (1 - t) + t * L1
7473 // C = t * C1
7474 // ```
7475 //
7476 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
7477
7478 let t;
7479
7480 if (cusp === undefined) {
7481 cusp = findCusp(a, b, lmsToRgb, okCoeff);
7482 }
7483
7484 // Find the intersection for upper and lower half separately
7485 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
7486 // Lower half
7487 t = (cusp[1] * l0) / (c1 * cusp[0] + cusp[1] * (l0 - l1));
7488 }
7489 else {
7490 // Upper half
7491
7492 // First intersect with triangle
7493 t = (cusp[1] * (l0 - 1.0)) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
7494
7495 // Then one step Halley's method
7496 let dl = l1 - l0;
7497 let dc = c1;
7498
7499 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
7500 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
7501 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
7502
7503 let ldt_ = dl + dc * kl;
7504 let mdt_ = dl + dc * km;
7505 let sdt_ = dl + dc * ks;
7506
7507 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
7508 let L = l0 * (1.0 - t) + t * l1;
7509 let C = t * c1;
7510
7511 let l_ = L + C * kl;
7512 let m_ = L + C * km;
7513 let s_ = L + C * ks;
7514
7515 let l = l_ ** 3;
7516 let m = m_ ** 3;
7517 let s = s_ ** 3;
7518
7519 let ldt = 3 * ldt_ * l_ ** 2;
7520 let mdt = 3 * mdt_ * m_ ** 2;
7521 let sdt = 3 * sdt_ * s_ ** 2;
7522
7523 let ldt2 = 6 * ldt_ ** 2 * l_;
7524 let mdt2 = 6 * mdt_ ** 2 * m_;
7525 let sdt2 = 6 * sdt_ ** 2 * s_;
7526
7527 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
7528 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
7529 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
7530
7531 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
7532 let tr = -r_ * ur;
7533
7534 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
7535 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
7536 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
7537
7538 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
7539 let tg = -g_ * ug;
7540
7541 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
7542 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
7543 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
7544
7545 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
7546 let tb = -b_ * ub;
7547
7548 tr = ur >= 0.0 ? tr : floatMax;
7549 tg = ug >= 0.0 ? tg : floatMax;
7550 tb = ub >= 0.0 ? tb : floatMax;
7551
7552 t += Math.min(tr, Math.min(tg, tb));
7553 }
7554
7555 return t;
7556 }
7557
7558 function getCs (lab, lmsToRgb, okCoeff) {
7559 // Get Cs
7560
7561 let [l, a, b] = lab;
7562
7563 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
7564
7565 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
7566 let stMax = toSt(cusp);
7567
7568 // Scale factor to compensate for the curved part of gamut shape:
7569 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
7570
7571 let stMid = getStMid(a, b);
7572
7573 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
7574 let ca = l * stMid[0];
7575 let cb = (1.0 - l) * stMid[1];
7576 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
7577
7578 // For `C_0`, the shape is independent of hue, so `ST` are constant.
7579 // Values picked to roughly be the average values of `ST`.
7580 ca = l * 0.4;
7581 cb = (1.0 - l) * 0.8;
7582
7583 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
7584 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
7585
7586 return [c0, cMid, cMax];
7587 }
7588
7589 function computeMaxSaturation (a, b, lmsToRgb, okCoeff) {
7590 // Finds the maximum saturation possible for a given hue that fits in RGB.
7591 //
7592 // Saturation here is defined as `S = C/L`.
7593 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
7594
7595 // Max saturation will be when one of r, g or b goes below zero.
7596
7597 // Select different coefficients depending on which component goes below zero first.
7598
7599 let k0, k1, k2, k3, k4, wl, wm, ws;
7600
7601 if (vdot(okCoeff[0][0], [a, b]) > 1) {
7602 // Red component
7603 [k0, k1, k2, k3, k4] = okCoeff[0][1];
7604 [wl, wm, ws] = lmsToRgb[0];
7605 }
7606 else if (vdot(okCoeff[1][0], [a, b]) > 1) {
7607 // Green component
7608 [k0, k1, k2, k3, k4] = okCoeff[1][1];
7609 [wl, wm, ws] = lmsToRgb[1];
7610 }
7611 else {
7612 // Blue component
7613 [k0, k1, k2, k3, k4] = okCoeff[2][1];
7614 [wl, wm, ws] = lmsToRgb[2];
7615 }
7616
7617 // Approximate max saturation using a polynomial:
7618 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
7619
7620 // Do one step Halley's method to get closer.
7621 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
7622 // This should be sufficient for most applications, otherwise do two/three steps.
7623
7624 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
7625 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
7626 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
7627
7628 let l_ = 1.0 + sat * kl;
7629 let m_ = 1.0 + sat * km;
7630 let s_ = 1.0 + sat * ks;
7631
7632 let l = l_ ** 3;
7633 let m = m_ ** 3;
7634 let s = s_ ** 3;
7635
7636 let lds = 3.0 * kl * l_ ** 2;
7637 let mds = 3.0 * km * m_ ** 2;
7638 let sds = 3.0 * ks * s_ ** 2;
7639
7640 let lds2 = 6.0 * kl ** 2 * l_;
7641 let mds2 = 6.0 * km ** 2 * m_;
7642 let sds2 = 6.0 * ks ** 2 * s_;
7643
7644 let f = wl * l + wm * m + ws * s;
7645 let f1 = wl * lds + wm * mds + ws * sds;
7646 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
7647
7648 sat = sat - (f * f1) / (f1 ** 2 - 0.5 * f * f2);
7649
7650 return sat;
7651 }
7652
7653 function okhslToOklab (hsl, lmsToRgb, okCoeff) {
7654 // Convert Okhsl to Oklab.
7655
7656 let [h, s, l] = hsl;
7657 let L = toeInv(l);
7658 let a = null;
7659 let b = null;
7660 h = constrain(h) / 360.0;
7661
7662 if (L !== 0.0 && L !== 1.0 && s !== 0) {
7663 let a_ = Math.cos(tau * h);
7664 let b_ = Math.sin(tau * h);
7665
7666 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
7667
7668 // Interpolate the three values for C so that:
7669 // ```
7670 // At s=0: dC/ds = C_0, C=0
7671 // At s=0.8: C=C_mid
7672 // At s=1.0: C=C_max
7673 // ```
7674
7675 let mid = 0.8;
7676 let midInv = 1.25;
7677 let t, k0, k1, k2;
7678
7679 if (s < mid) {
7680 t = midInv * s;
7681 k0 = 0.0;
7682 k1 = mid * c0;
7683 k2 = 1.0 - k1 / cMid;
7684 }
7685 else {
7686 t = 5 * (s - 0.8);
7687 k0 = cMid;
7688 k1 = (0.2 * cMid ** 2 * 1.25 ** 2) / c0;
7689 k2 = 1.0 - k1 / (cMax - cMid);
7690 }
7691
7692 let c = k0 + (t * k1) / (1.0 - k2 * t);
7693
7694 a = c * a_;
7695 b = c * b_;
7696 }
7697
7698 return [L, a, b];
7699 }
7700
7701 function oklabToOkhsl (lab, lmsToRgb, okCoeff) {
7702 // Oklab to Okhsl.
7703
7704 // Epsilon for lightness should approach close to 32 bit lightness
7705 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
7706 let εL = 1e-7;
7707 let εS = 1e-4;
7708 let L = lab[0];
7709 let s = 0.0;
7710 let l = toe(L);
7711
7712 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
7713 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
7714
7715 if (l !== 0.0 && l !== 1.0 && c !== 0) {
7716 let a_ = lab[1] / c;
7717 let b_ = lab[2] / c;
7718
7719 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
7720
7721 let mid = 0.8;
7722 let midInv = 1.25;
7723 let k0, k1, k2, t;
7724
7725 if (c < cMid) {
7726 k1 = mid * c0;
7727 k2 = 1.0 - k1 / cMid;
7728
7729 t = c / (k1 + k2 * c);
7730 s = t * mid;
7731 }
7732 else {
7733 k0 = cMid;
7734 k1 = (0.2 * cMid ** 2 * midInv ** 2) / c0;
7735 k2 = 1.0 - k1 / (cMax - cMid);
7736
7737 t = (c - k0) / (k1 + k2 * (c - k0));
7738 s = mid + 0.2 * t;
7739 }
7740 }
7741
7742 const achromatic = Math.abs(s) < εS;
7743 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
7744 h = null;
7745 // Due to floating point imprecision near lightness of 1, we can end up
7746 // with really high around white, this is to provide consistency as
7747 // saturation can be really high for white due this imprecision.
7748 if (!achromatic) {
7749 s = 0.0;
7750 }
7751 }
7752 else {
7753 h = constrain(h * 360);
7754 }
7755
7756 return [h, s, l];
7757 }
7758
7759 const Okhsl = new ColorSpace({
7760 id: "okhsl",
7761 name: "Okhsl",
7762 coords: {
7763 h: {
7764 refRange: [0, 360],
7765 type: "angle",
7766 name: "Hue",
7767 },
7768 s: {
7769 range: [0, 1],
7770 name: "Saturation",
7771 },
7772 l: {
7773 range: [0, 1],
7774 name: "Lightness",
7775 },
7776 },
7777
7778 base: Oklab,
7779 gamutSpace: "self",
7780
7781 M: M$3,
7782
7783 // Convert Oklab to Okhsl
7784 fromBase (lab) {
7785 return oklabToOkhsl(lab, M$3.toSRGBLinear, RGBCoeff);
7786 },
7787
7788 // Convert Okhsl to Oklab
7789 toBase (hsl) {
7790 return okhslToOklab(hsl, M$3.toSRGBLinear, RGBCoeff);
7791 },
7792
7793 formats: {
7794 color: {
7795 id: "--okhsl",
7796 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
7797 },
7798 },
7799 });
7800
7801 Okhsl.rgbGamut = new RGBColorSpace({
7802 id: "okhsl-prism",
7803 cssId: "--okhsl-prism",
7804 name: "Okhsl Prism",
7805 base: Okhsl,
7806 fromBase (hsl) {
7807 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
7808 },
7809 toBase (rgb) {
7810 const hsl = HSL.fromBase(rgb);
7811 hsl[1] /= 100;
7812 hsl[2] /= 100;
7813 return hsl;
7814 },
7815 });
7816
7817 var OKLrab = new ColorSpace({
7818 id: "oklrab",
7819 name: "Oklrab",
7820 coords: {
7821 l: {
7822 refRange: [0, 1],
7823 name: "Lightness",
7824 },
7825 a: {
7826 refRange: [-0.4, 0.4],
7827 },
7828 b: {
7829 refRange: [-0.4, 0.4],
7830 },
7831 },
7832
7833 // Note that XYZ is relative to D65
7834 white: "D65",
7835
7836 base: Oklab,
7837 fromBase (oklab) {
7838 return [toe(oklab[0]), oklab[1], oklab[2]];
7839 },
7840 toBase (oklrab) {
7841 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
7842 },
7843
7844 formats: {
7845 color: {
7846 coords: [
7847 "<percentage> | <number>",
7848 "<number> | <percentage>[-1,1]",
7849 "<number> | <percentage>[-1,1]",
7850 ],
7851 },
7852 },
7853 });
7854
7855 var oklrch = new ColorSpace({
7856 id: "oklrch",
7857 name: "Oklrch",
7858 coords: {
7859 l: {
7860 refRange: [0, 1],
7861 name: "Lightness",
7862 },
7863 c: {
7864 refRange: [0, 0.4],
7865 name: "Chroma",
7866 },
7867 h: {
7868 refRange: [0, 360],
7869 type: "angle",
7870 name: "Hue",
7871 },
7872 },
7873 white: "D65",
7874
7875 base: OKLrab,
7876 fromBase: lch.fromBase,
7877 toBase: lch.toBase,
7878
7879 formats: {
7880 color: {
7881 coords: [
7882 "<percentage> | <number>",
7883 "<number> | <percentage>[0,1]",
7884 "<number> | <angle>",
7885 ],
7886 },
7887 },
7888 });
7889
7890 // Okhsv class.
7891 //
7892 // ---- License ----
7893 //
7894 // Copyright (c) 2021 Björn Ottosson
7895 //
7896 // Permission is hereby granted, free of charge, to any person obtaining a copy of
7897 // this software and associated documentation files (the "Software"), to deal in
7898 // the Software without restriction, including without limitation the rights to
7899 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7900 // of the Software, and to permit persons to whom the Software is furnished to do
7901 // so, subject to the following conditions:
7902 //
7903 // The above copyright notice and this permission notice shall be included in all
7904 // copies or substantial portions of the Software.
7905 //
7906 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7907 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7908 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7909 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
7910 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
7911 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
7912 // SOFTWARE.
7913
7914 /**
7915 * Matrices used by this color space (reused from Okhsl), also available as `Okhsv.M`
7916 * @type {Record<string, Matrix3x3>}
7917 */
7918 const M$2 = { toSRGBLinear: Okhsl.M.toSRGBLinear };
7919
7920 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
7921
7922 /**
7923 *
7924 * @param {Vector3} hsv
7925 * @param {Matrix3x3} lmsToRgb
7926 * @param {OKCoeff} okCoeff
7927 * @returns {Coords}
7928 */
7929 function okhsvToOklab (hsv, lmsToRgb, okCoeff) {
7930 // Convert from Okhsv to Oklab."""
7931
7932 let [h, s, v] = hsv;
7933 h = constrain(h) / 360.0;
7934
7935 let l = toeInv(v);
7936 let a = null;
7937 let b = null;
7938
7939 // Avoid processing gray or colors with undefined hues
7940 if (l !== 0.0 && s !== 0.0) {
7941 let a_ = Math.cos(tau * h);
7942 let b_ = Math.sin(tau * h);
7943
7944 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
7945 let [sMax, tMax] = toSt(cusp);
7946 let s0 = 0.5;
7947 let k = 1 - s0 / sMax;
7948
7949 // first we compute L and V as if the gamut is a perfect triangle:
7950
7951 // L, C when v==1:
7952 let lv = 1 - (s * s0) / (s0 + tMax - tMax * k * s);
7953 let cv = (s * tMax * s0) / (s0 + tMax - tMax * k * s);
7954
7955 l = v * lv;
7956 let c = v * cv;
7957
7958 // then we compensate for both toe and the curved top part of the triangle:
7959 let lvt = toeInv(lv);
7960 let cvt = (cv * lvt) / lv;
7961
7962 let lNew = toeInv(l);
7963 c = (c * lNew) / l;
7964 l = lNew;
7965
7966 // RGB scale
7967 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
7968 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
7969
7970 l = l * scaleL;
7971 c = c * scaleL;
7972
7973 a = c * a_;
7974 b = c * b_;
7975 }
7976
7977 return [l, a, b];
7978 }
7979
7980 /**
7981 *
7982 * @param {Vector3} lab
7983 * @param {Matrix3x3} lmsToRgb
7984 * @param {OKCoeff} okCoeff
7985 * @returns {Coords}
7986 */
7987 function oklabToOkhsv (lab, lmsToRgb, okCoeff) {
7988 // Oklab to Okhsv.
7989
7990 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
7991 let ε = 1e-4;
7992 let l = lab[0];
7993 let s = 0.0;
7994 let v = toe(l);
7995 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
7996 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
7997
7998 if (l !== 0.0 && l !== 1 && c !== 0.0) {
7999 let a_ = lab[1] / c;
8000 let b_ = lab[2] / c;
8001
8002 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
8003 let [sMax, tMax] = toSt(cusp);
8004 let s0 = 0.5;
8005 let k = 1 - s0 / sMax;
8006
8007 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
8008 let t = tMax / (c + l * tMax);
8009 let lv = t * l;
8010 let cv = t * c;
8011
8012 let lvt = toeInv(lv);
8013 let cvt = (cv * lvt) / lv;
8014
8015 // we can then use these to invert the step that compensates
8016 // for the toe and the curved top part of the triangle:
8017 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
8018 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
8019
8020 l = l / scaleL;
8021 c = c / scaleL;
8022
8023 c = (c * toe(l)) / l;
8024 l = toe(l);
8025
8026 // we can now compute v and s:
8027 v = l / lv;
8028 s = ((s0 + tMax) * cv) / (tMax * s0 + tMax * k * cv);
8029 }
8030
8031 if (Math.abs(s) < ε || v === 0.0) {
8032 h = null;
8033 }
8034 else {
8035 h = constrain(h * 360);
8036 }
8037
8038 return [h, s, v];
8039 }
8040
8041 const Okhsv = new ColorSpace({
8042 id: "okhsv",
8043 name: "Okhsv",
8044 coords: {
8045 h: {
8046 refRange: [0, 360],
8047 type: "angle",
8048 name: "Hue",
8049 },
8050 s: {
8051 range: [0, 1],
8052 name: "Saturation",
8053 },
8054 v: {
8055 range: [0, 1],
8056 name: "Value",
8057 },
8058 },
8059
8060 base: Oklab,
8061 gamutSpace: "self",
8062
8063 M: M$2,
8064
8065 // Convert Oklab to Okhsl
8066 fromBase (lab) {
8067 return oklabToOkhsv(lab, M$2.toSRGBLinear, RGBCoeff);
8068 },
8069
8070 // Convert Okhsl to Oklab
8071 toBase (hsl) {
8072 return okhsvToOklab(hsl, M$2.toSRGBLinear, RGBCoeff);
8073 },
8074
8075 formats: {
8076 color: {
8077 id: "--okhsv",
8078 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
8079 },
8080 },
8081 });
8082
8083 Okhsv.rgbGamut = new RGBColorSpace({
8084 id: "okhsv-prism",
8085 cssId: "--okhsv-prism",
8086 name: "Okhsv Prism",
8087 base: Okhsv,
8088 fromBase (hsl) {
8089 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
8090 },
8091 toBase (rgb) {
8092 const hsl = HSL.fromBase(rgb);
8093 hsl[1] /= 100;
8094 hsl[2] /= 100;
8095 return hsl;
8096 },
8097 });
8098
8099 let white = WHITES.D65;
8100
8101 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
8102 const κ$1 = 24389 / 27; // 29^3/3^3
8103 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({ space: XYZ_D65, coords: white });
8104
8105 var Luv = new ColorSpace({
8106 id: "luv",
8107 name: "Luv",
8108 coords: {
8109 l: {
8110 refRange: [0, 100],
8111 name: "Lightness",
8112 },
8113 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
8114 u: {
8115 refRange: [-215, 215],
8116 },
8117 v: {
8118 refRange: [-215, 215],
8119 },
8120 },
8121
8122 white: white,
8123 base: XYZ_D65,
8124
8125 // Convert D65-adapted XYZ to Luv
8126 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
8127 fromBase (XYZ) {
8128 let xyz = /** @type {[number, number, number]} */ ([
8129 skipNone(XYZ[0]),
8130 skipNone(XYZ[1]),
8131 skipNone(XYZ[2]),
8132 ]);
8133 let y = xyz[1];
8134
8135 let [up, vp] = uv({ space: XYZ_D65, coords: xyz });
8136
8137 // Protect against XYZ of [0, 0, 0]
8138 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
8139 return [0, 0, 0];
8140 }
8141
8142 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
8143 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
8144 },
8145
8146 // Convert Luv to D65-adapted XYZ
8147 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
8148 toBase (Luv) {
8149 let [L, u, v] = Luv;
8150
8151 // Protect against division by zero and none Lightness
8152 if (L === 0 || isNone(L)) {
8153 return [0, 0, 0];
8154 }
8155
8156 u = skipNone(u);
8157 v = skipNone(v);
8158
8159 let up = u / (13 * L) + U_PRIME_WHITE;
8160 let vp = v / (13 * L) + V_PRIME_WHITE;
8161
8162 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
8163
8164 return [y * ((9 * up) / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
8165 },
8166
8167 formats: {
8168 color: {
8169 id: "--luv",
8170 coords: [
8171 "<number> | <percentage>",
8172 "<number> | <percentage>",
8173 "<number> | <percentage>",
8174 ],
8175 },
8176 },
8177 });
8178
8179 var LCHuv = new ColorSpace({
8180 id: "lchuv",
8181 name: "LChuv",
8182 coords: {
8183 l: {
8184 refRange: [0, 100],
8185 name: "Lightness",
8186 },
8187 c: {
8188 refRange: [0, 220],
8189 name: "Chroma",
8190 },
8191 h: {
8192 refRange: [0, 360],
8193 type: "angle",
8194 name: "Hue",
8195 },
8196 },
8197
8198 base: Luv,
8199 fromBase: lch.fromBase,
8200 toBase: lch.toBase,
8201
8202 formats: {
8203 color: {
8204 id: "--lchuv",
8205 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"],
8206 },
8207 },
8208 });
8209
8210 /*
8211 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
8212
8213 Copyright (c) 2012-2022 Alexei Boronine
8214
8215 Permission is hereby granted, free of charge, to any person obtaining a copy
8216 of this software and associated documentation files (the "Software"), to deal
8217 in the Software without restriction, including without limitation the rights
8218 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8219 copies of the Software, and to permit persons to whom the Software is
8220 furnished to do so, subject to the following conditions:
8221
8222 The above copyright notice and this permission notice shall be included in all
8223 copies or substantial portions of the Software.
8224
8225 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8226 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8227 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8228 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8229 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
8230 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
8231 SOFTWARE.
8232 */
8233
8234
8235 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
8236 const κ = 24389 / 27; // 29^3/3^3
8237
8238 const fromXYZ_M$1 = M$6.fromXYZ;
8239 const m_r0 = fromXYZ_M$1[0][0];
8240 const m_r1 = fromXYZ_M$1[0][1];
8241 const m_r2 = fromXYZ_M$1[0][2];
8242 const m_g0 = fromXYZ_M$1[1][0];
8243 const m_g1 = fromXYZ_M$1[1][1];
8244 const m_g2 = fromXYZ_M$1[1][2];
8245 const m_b0 = fromXYZ_M$1[2][0];
8246 const m_b1 = fromXYZ_M$1[2][1];
8247 const m_b2 = fromXYZ_M$1[2][2];
8248
8249 function distanceFromOriginAngle (slope, intercept, angle) {
8250 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
8251 return d < 0 ? Infinity : d;
8252 }
8253
8254 /**
8255 * @param {number} l
8256 */
8257 function calculateBoundingLines (l) {
8258 const sub1 = Math.pow(l + 16, 3) / 1560896;
8259 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
8260 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
8261 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
8262 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
8263 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
8264 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
8265 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
8266 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
8267 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
8268 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
8269
8270 return {
8271 r0s: s1r / s3r,
8272 r0i: (s2r * l) / s3r,
8273 r1s: s1r / (s3r + 126452),
8274 r1i: ((s2r - 769860) * l) / (s3r + 126452),
8275 g0s: s1g / s3g,
8276 g0i: (s2g * l) / s3g,
8277 g1s: s1g / (s3g + 126452),
8278 g1i: ((s2g - 769860) * l) / (s3g + 126452),
8279 b0s: s1b / s3b,
8280 b0i: (s2b * l) / s3b,
8281 b1s: s1b / (s3b + 126452),
8282 b1i: ((s2b - 769860) * l) / (s3b + 126452),
8283 };
8284 }
8285
8286 function calcMaxChromaHsluv (lines, h) {
8287 const hueRad = (h / 360) * Math.PI * 2;
8288 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
8289 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
8290 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
8291 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
8292 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
8293 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
8294
8295 return Math.min(r0, r1, g0, g1, b0, b1);
8296 }
8297
8298 var hsluv = new ColorSpace({
8299 id: "hsluv",
8300 name: "HSLuv",
8301 coords: {
8302 h: {
8303 refRange: [0, 360],
8304 type: "angle",
8305 name: "Hue",
8306 },
8307 s: {
8308 range: [0, 100],
8309 name: "Saturation",
8310 },
8311 l: {
8312 range: [0, 100],
8313 name: "Lightness",
8314 },
8315 },
8316
8317 base: LCHuv,
8318 gamutSpace: sRGB,
8319 rgbGamut: sRGB,
8320
8321 // Convert LCHuv to HSLuv
8322 fromBase (lch) {
8323 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
8324 let s;
8325
8326 if (l > 99.9999999) {
8327 s = 0;
8328 l = 100;
8329 }
8330 else if (l < 0.00000001) {
8331 s = 0;
8332 l = 0;
8333 }
8334 else {
8335 let lines = calculateBoundingLines(l);
8336 let max = calcMaxChromaHsluv(lines, h);
8337 s = (c / max) * 100;
8338 }
8339
8340 return [h, s, l];
8341 },
8342
8343 // Convert HSLuv to LCHuv
8344 toBase (hsl) {
8345 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
8346 let c;
8347
8348 if (l > 99.9999999) {
8349 l = 100;
8350 c = 0;
8351 }
8352 else if (l < 0.00000001) {
8353 l = 0;
8354 c = 0;
8355 }
8356 else {
8357 let lines = calculateBoundingLines(l);
8358 let max = calcMaxChromaHsluv(lines, h);
8359 c = (max / 100) * s;
8360 }
8361
8362 return [l, c, h];
8363 },
8364
8365 formats: {
8366 color: {
8367 id: "--hsluv",
8368 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
8369 },
8370 },
8371 });
8372
8373 /*
8374 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
8375
8376 Copyright (c) 2012-2022 Alexei Boronine
8377
8378 Permission is hereby granted, free of charge, to any person obtaining a copy
8379 of this software and associated documentation files (the "Software"), to deal
8380 in the Software without restriction, including without limitation the rights
8381 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8382 copies of the Software, and to permit persons to whom the Software is
8383 furnished to do so, subject to the following conditions:
8384
8385 The above copyright notice and this permission notice shall be included in all
8386 copies or substantial portions of the Software.
8387
8388 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8389 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8390 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8391 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8392 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
8393 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
8394 SOFTWARE.
8395 */
8396
8397
8398 const fromXYZ_M = M$6.fromXYZ;
8399 fromXYZ_M[0][0];
8400 fromXYZ_M[0][1];
8401 fromXYZ_M[0][2];
8402 fromXYZ_M[1][0];
8403 fromXYZ_M[1][1];
8404 fromXYZ_M[1][2];
8405 fromXYZ_M[2][0];
8406 fromXYZ_M[2][1];
8407 fromXYZ_M[2][2];
8408
8409 function distanceFromOrigin (slope, intercept) {
8410 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
8411 }
8412
8413 function calcMaxChromaHpluv (lines) {
8414 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
8415 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
8416 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
8417 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
8418 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
8419 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
8420
8421 return Math.min(r0, r1, g0, g1, b0, b1);
8422 }
8423
8424 const HPLuv = new ColorSpace({
8425 id: "hpluv",
8426 name: "HPLuv",
8427 coords: {
8428 h: {
8429 refRange: [0, 360],
8430 type: "angle",
8431 name: "Hue",
8432 },
8433 s: {
8434 range: [0, 100],
8435 name: "Saturation",
8436 },
8437 l: {
8438 range: [0, 100],
8439 name: "Lightness",
8440 },
8441 },
8442
8443 base: LCHuv,
8444 gamutSpace: "self",
8445
8446 // Convert LCHuv to HPLuv
8447 fromBase (lch) {
8448 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
8449 let s;
8450
8451 if (l > 99.9999999) {
8452 s = 0;
8453 l = 100;
8454 }
8455 else if (l < 0.00000001) {
8456 s = 0;
8457 l = 0;
8458 }
8459 else {
8460 let lines = calculateBoundingLines(l);
8461 let max = calcMaxChromaHpluv(lines);
8462 s = (c / max) * 100;
8463 }
8464 return [h, s, l];
8465 },
8466
8467 // Convert HPLuv to LCHuv
8468 toBase (hsl) {
8469 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
8470 let c;
8471
8472 if (l > 99.9999999) {
8473 l = 100;
8474 c = 0;
8475 }
8476 else if (l < 0.00000001) {
8477 l = 0;
8478 c = 0;
8479 }
8480 else {
8481 let lines = calculateBoundingLines(l);
8482 let max = calcMaxChromaHpluv(lines);
8483 c = (max / 100) * s;
8484 }
8485
8486 return [l, c, h];
8487 },
8488
8489 formats: {
8490 color: {
8491 id: "--hpluv",
8492 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
8493 },
8494 },
8495 });
8496
8497 HPLuv.rgbGamut = new RGBColorSpace({
8498 id: "hpluv-prism",
8499 cssId: "--hpluv-prism",
8500 name: "HPLuv Prism",
8501 base: HPLuv,
8502 fromBase (hsl) {
8503 return HSL.toBase(hsl);
8504 },
8505 toBase (rgb) {
8506 return HSL.fromBase(rgb);
8507 },
8508 });
8509
8510 /**
8511 * Helmlab GenSpace — generation-optimized color space for interpolation.
8512 *
8513 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
8514 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
8515 * PW_L → L-gated hue enrichment → Lab
8516 *
8517 * Optimized for perceptually uniform gradients, palette generation,
8518 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
8519 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
8520 *
8521 * Key properties:
8522 * - Depressed cubic: y³ + αy = x, finite derivative at zero
8523 * - Chroma power (0.978): improves gradient CV uniformity
8524 * - L-gated hue enrichment: fixes blue→white purple shift
8525 * - Structurally achromatic: a=b≈0 for all grays
8526 *
8527 * Note on blue-region gamut fold:
8528 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
8529 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
8530 * mixing LMS channels before applying a power-like transfer: the inverse
8531 * creates a cubic polynomial that can have two positive roots in the blue
8532 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
8533 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
8534 *
8535 * Reference: arXiv:2602.23010
8536 * @see https://github.com/Grkmyldz148/helmlab
8537 */
8538
8539 /** @import { Matrix3x3 } from "../types.js" */
8540
8541 // ── Depressed cubic parameter ──────────────────────────────────────
8542 const ALPHA = 0.021;
8543 const S = Math.sqrt(ALPHA / 3);
8544 const S3 = S * S * S;
8545
8546 // ── Chroma power ───────────────────────────────────────────────────
8547 const CP = 0.978;
8548
8549 // ── L-gated hue enrichment parameters ──────────────────────────────
8550 const ENR_AMP = 0.058;
8551 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
8552 const ENR_SIGMA = 0.7;
8553 const ENR_LLO = 0.37;
8554 const ENR_LHI = 1.0;
8555
8556 // ── Core matrices (v0.11.1) ────────────────────────────────────────
8557
8558 /**
8559 * Matrices used by this color space, also available as `HelmGen.M`
8560 * @type {Record<string, Matrix3x3>}
8561 */
8562 // prettier-ignore
8563 const M$1 = {
8564 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
8565 M1: [
8566 [ 8.1548321559412884e-01, 3.6033406153856506e-01, -1.2434135574228214e-01],
8567 [ 3.3010083527450780e-02, 9.2928650570661686e-01, 3.6121927165754429e-02],
8568 [ 4.8188273564568611e-02, 2.6428415753384238e-01, 6.3349717841955344e-01],
8569 ],
8570 M1_INV: [
8571 [ 1.2325947975032656e+00, -5.5575902392875232e-01, 2.7362015347715829e-01],
8572 [-4.0801327874216024e-02, 1.1122288637386530e+00, -7.1427535864437813e-02],
8573 [-7.6738259283377658e-02, -4.2172784577108585e-01, 1.5875238558143416e+00],
8574 ],
8575 M2: [
8576 [ 0.21193779684470104, 0.7992121834263127, -0.00410075161564345],
8577 [ 2.4672018828033475, -2.9877348024830788, 0.520532919679731],
8578 [-0.11390787868068575, 1.3932982808117473, -1.279390402131062],
8579 ],
8580 M2_INV: [
8581 [ 0.9930001151336143, 0.32599327253052285, 0.12945085631713921],
8582 [ 0.9930001151336139, -0.08708353111074627, -0.03861361743004929],
8583 [ 0.9930001151336136, -0.12386097008215022, -0.8351991365871061],
8584 ],
8585 };
8586
8587 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
8588 // prettier-ignore
8589 const PW_L_IN = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0];
8590 // prettier-ignore
8591 const PW_L_OUT = [0, 0.009494013522189627, 0.02564569838030986, 0.055259661658689105, 0.10574901531227408, 0.16055853320726027, 0.21405964892993756, 0.26786230508811226, 0.3220435246104499, 0.3739052098520243, 0.43020997780918835, 0.4835465162128873, 0.5399824670411353, 0.5956710081330342, 0.6542161666450478, 0.7115380216519989, 0.7702762412711669, 0.8293313467712837, 0.889406386197059, 0.9462829573474728, 1.0];
8592 const PW_N = PW_L_IN.length;
8593
8594 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
8595
8596 function depcubicFwd (x) {
8597 let t = x / (2 * S3);
8598 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
8599 // Halley refinement
8600 let f = y * y * y + ALPHA * y - x;
8601 let fp = 3 * y * y + ALPHA;
8602 let fpp = 6 * y;
8603 let denom = 2 * fp * fp - f * fpp;
8604 if (Math.abs(denom) > 1e-30) {
8605 y -= 2 * f * fp / denom;
8606 }
8607 return y;
8608 }
8609
8610 function depcubicInv (y) {
8611 return y * y * y + ALPHA * y;
8612 }
8613
8614 // ── L-gated hue enrichment ─────────────────────────────────────────
8615
8616 function enrichGate (L) {
8617 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
8618 return Math.sin(Math.PI * t) ** 2;
8619 }
8620
8621 function enrichFwd (L, a, b) {
8622 let C = Math.sqrt(a * a + b * b);
8623 if (C < 1e-12) {
8624 return [a, b];
8625 }
8626 let gate = enrichGate(L);
8627 if (gate < 1e-12) {
8628 return [a, b];
8629 }
8630 let h = Math.atan2(b, a);
8631 let dh = h - ENR_CENTER;
8632 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
8633 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
8634 let hNew = h + ENR_AMP * gate * gauss;
8635 return [C * Math.cos(hNew), C * Math.sin(hNew)];
8636 }
8637
8638 function enrichInv (L, a, b) {
8639 let C = Math.sqrt(a * a + b * b);
8640 if (C < 1e-12) {
8641 return [a, b];
8642 }
8643 let gate = enrichGate(L);
8644 if (gate < 1e-12) {
8645 return [a, b];
8646 }
8647 let hTarget = Math.atan2(b, a);
8648 let sig2 = ENR_SIGMA * ENR_SIGMA;
8649 let ag = ENR_AMP * gate;
8650 let h = hTarget;
8651 for (let i = 0; i < 8; i++) {
8652 let dh = h - ENR_CENTER;
8653 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
8654 let gauss = Math.exp(-0.5 * dh * dh / sig2);
8655 let F = h + ag * gauss - hTarget;
8656 let Fp = 1 + ag * gauss * (-dh / sig2);
8657 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
8658 let den = 2 * Fp * Fp - F * Fpp;
8659 if (Math.abs(den) > 1e-30) {
8660 h -= 2 * F * Fp / den;
8661 }
8662 }
8663 return [C * Math.cos(h), C * Math.sin(h)];
8664 }
8665
8666 // ── PW L correction ───────────────────────────────────────────────
8667
8668 function pwLForward (L) {
8669 if (L <= 0 || L >= 1) {
8670 return L;
8671 }
8672 let lo = 0, hi = PW_N - 1;
8673 while (hi - lo > 1) {
8674 let mid = (lo + hi) >> 1;
8675 if (PW_L_IN[mid] <= L) {
8676 lo = mid;
8677 }
8678 else {
8679 hi = mid;
8680 }
8681 }
8682 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
8683 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
8684 }
8685
8686 function pwLInverse (L) {
8687 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
8688 return L;
8689 }
8690 let lo = 0, hi = PW_N - 1;
8691 while (hi - lo > 1) {
8692 let mid = (lo + hi) >> 1;
8693 if (PW_L_OUT[mid] <= L) {
8694 lo = mid;
8695 }
8696 else {
8697 hi = mid;
8698 }
8699 }
8700 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
8701 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
8702 }
8703
8704 // ── Color space definition ─────────────────────────────────────────
8705
8706 var HelmGen = new ColorSpace({
8707 id: "helmgen",
8708 name: "HelmGen",
8709 cssId: "--helmgen",
8710 coords: {
8711 l: {
8712 refRange: [0, 1],
8713 name: "Lightness",
8714 },
8715 a: {
8716 refRange: [-0.6, 0.6],
8717 },
8718 b: {
8719 refRange: [-0.6, 0.6],
8720 },
8721 },
8722 white: "D65",
8723 base: XYZ_D65,
8724
8725 M: M$1,
8726
8727 fromBase (xyz) {
8728 // Stage 1: XYZ → LMS (M1)
8729 let lms = multiply_v3_m3x3(xyz, M$1.M1);
8730
8731 // Stage 2: Depressed cubic transfer (y³ + αy = x)
8732 let c0 = depcubicFwd(Math.max(lms[0], 0));
8733 let c1 = depcubicFwd(Math.max(lms[1], 0));
8734 let c2 = depcubicFwd(Math.max(lms[2], 0));
8735
8736 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
8737 {
8738 let mean = (c0 + c1 + c2) / 3;
8739 let mx = Math.max(c0, c1, c2);
8740 let mn = Math.min(c0, c1, c2);
8741 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
8742 let w = Math.exp(-((spread / 1e-5) ** 2));
8743 c0 += w * (mean - c0);
8744 c1 += w * (mean - c1);
8745 c2 += w * (mean - c2);
8746 }
8747
8748 // Stage 3: LMS_c → Lab (M2)
8749 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$1.M2);
8750
8751 // Stage 3.5: Chroma power (cp=0.978)
8752 {
8753 let C = Math.sqrt(a * a + b * b);
8754 if (C > 1e-12) {
8755 let Cnew = Math.pow(C, CP);
8756 let s = Cnew / C;
8757 a *= s;
8758 b *= s;
8759 }
8760 }
8761
8762 // Stage 4: Piecewise-linear L correction
8763 L = pwLForward(L);
8764
8765 // Stage 5: L-gated hue enrichment
8766 [a, b] = enrichFwd(L, a, b);
8767
8768 return [L, a, b];
8769 },
8770
8771 toBase (lab) {
8772 let [L, a, b] = lab;
8773
8774 // Undo Stage 5: L-gated hue enrichment
8775 [a, b] = enrichInv(L, a, b);
8776
8777 // Undo Stage 4: PW L correction
8778 L = pwLInverse(L);
8779
8780 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
8781 {
8782 let C = Math.sqrt(a * a + b * b);
8783 if (C > 1e-12) {
8784 let Corig = Math.pow(C, 1 / CP);
8785 let s = Corig / C;
8786 a *= s;
8787 b *= s;
8788 }
8789 }
8790
8791 // Undo Stage 3: Lab → LMS_c (M2_inv)
8792 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$1.M2_INV);
8793
8794 // Undo Stage 2.5: Smooth neutral blend
8795 {
8796 let mean = (lc0 + lc1 + lc2) / 3;
8797 let mx = Math.max(lc0, lc1, lc2);
8798 let mn = Math.min(lc0, lc1, lc2);
8799 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
8800 let w = Math.exp(-((spread / 1e-5) ** 2));
8801 lc0 += w * (mean - lc0);
8802 lc1 += w * (mean - lc1);
8803 lc2 += w * (mean - lc2);
8804 }
8805
8806 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
8807 let l0 = depcubicInv(lc0);
8808 let l1 = depcubicInv(lc1);
8809 let l2 = depcubicInv(lc2);
8810
8811 // Undo Stage 1: LMS → XYZ (M1_inv)
8812 return multiply_v3_m3x3([l0, l1, l2], M$1.M1_INV);
8813 },
8814 });
8815
8816 /**
8817 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
8818 *
8819 * Converts GenSpace's rectangular (L, a, b) coordinates to
8820 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
8821 * like gradients and color-mix where hue angle matters.
8822 *
8823 * @see https://github.com/Grkmyldz148/helmlab
8824 */
8825
8826 var helmgenlch = new ColorSpace({
8827 id: "helmgenlch",
8828 name: "HelmGenLCh",
8829 cssId: "--helmgenlch",
8830 coords: {
8831 l: {
8832 refRange: [0, 1],
8833 name: "Lightness",
8834 },
8835 c: {
8836 refRange: [0, 0.65],
8837 name: "Chroma",
8838 },
8839 h: {
8840 refRange: [0, 360],
8841 type: "angle",
8842 name: "Hue",
8843 },
8844 },
8845 white: "D65",
8846
8847 base: HelmGen,
8848 fromBase: lch.fromBase,
8849 toBase: lch.toBase,
8850 });
8851
8852 var REC_2100_Linear = new RGBColorSpace({
8853 id: "rec2100-linear",
8854 name: "Linear REC.2100",
8855 white: "D65",
8856 M: M$8,
8857 });
8858
8859 const Yw = 203; // absolute luminance of media white, cd/m²
8860 const n = 2610 / 2 ** 14;
8861 const ninv = 2 ** 14 / 2610;
8862 const m = 2523 / 2 ** 5;
8863 const minv = 2 ** 5 / 2523;
8864 const c1 = 3424 / 2 ** 12;
8865 const c2 = 2413 / 2 ** 7;
8866 const c3 = 2392 / 2 ** 7;
8867
8868 var rec2100Pq = new RGBColorSpace({
8869 id: "rec2100pq",
8870 cssId: "rec2100-pq",
8871 name: "REC.2100-PQ",
8872 base: REC_2100_Linear,
8873 linearGamut: REC_2100_Linear,
8874 toBase (RGB) {
8875 // given PQ encoded component in range [0, 1]
8876 // return media-white relative linear-light
8877 return RGB.map(function (val) {
8878 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
8879 return (x * 10000) / Yw; // luminance relative to diffuse white, [0, 70 or so].
8880 });
8881 },
8882 fromBase (RGB) {
8883 // given media-white relative linear-light
8884 // returnPQ encoded component in range [0, 1]
8885 return RGB.map(function (val) {
8886 let x = Math.max((val * Yw) / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
8887 let num = c1 + c2 * x ** n;
8888 let denom = 1 + c3 * x ** n;
8889
8890 return (num / denom) ** m;
8891 });
8892 },
8893 });
8894
8895 const a = 0.17883277;
8896 const b = 0.28466892; // 1 - (4 * a)
8897 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
8898
8899 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
8900
8901 var rec2100Hlg = new RGBColorSpace({
8902 id: "rec2100hlg",
8903 cssId: "rec2100-hlg",
8904 name: "REC.2100-HLG",
8905 referred: "scene",
8906
8907 base: REC_2100_Linear,
8908 linearGamut: REC_2100_Linear,
8909 toBase (RGB) {
8910 // given HLG encoded component in range [0, 1]
8911 // return media-white relative linear-light
8912 return RGB.map(function (val) {
8913 // first the HLG EOTF
8914 // ITU-R BT.2390-10 p.30 section
8915 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
8916 // Then scale by 3 so media white is 1.0
8917 if (val <= 0.5) {
8918 return (val ** 2 / 3) * scale;
8919 }
8920 return ((Math.exp((val - c) / a) + b) / 12) * scale;
8921 });
8922 },
8923 fromBase (RGB) {
8924 // given media-white relative linear-light
8925 // where diffuse white is 1.0,
8926 // return HLG encoded component in range [0, 1]
8927 return RGB.map(function (val) {
8928 // first scale to put linear-light media white at 1/3
8929 val /= scale;
8930 // now the HLG OETF
8931 // ITU-R BT.2390-10 p.23
8932 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
8933 if (val <= 1 / 12) {
8934 return spow(3 * val, 0.5);
8935 }
8936 return a * Math.log(12 * val - b) + c;
8937 });
8938 },
8939 });
8940
8941 /** @import { White } from "./types.js" */
8942
8943 // Type re-exports
8944 /** @typedef {import("./types.js").CAT} CAT */
8945
8946 /** @type {Record<string, CAT>} */
8947 const CATs = {};
8948
8949 hooks.add("chromatic-adaptation-start", env => {
8950 if (env.options.method) {
8951 env.M = adapt(env.W1, env.W2, env.options.method);
8952 }
8953 });
8954
8955 hooks.add("chromatic-adaptation-end", env => {
8956 if (!env.M) {
8957 env.M = adapt(env.W1, env.W2, env.options.method);
8958 }
8959 });
8960
8961 function defineCAT (/** @type {CAT} */ { id, toCone_M, fromCone_M }) {
8962 // Use id, toCone_M, fromCone_M like variables
8963 CATs[id] = arguments[0];
8964 }
8965
8966 /**
8967 *
8968 * @param {White} W1
8969 * @param {White} W2
8970 * @param {string} id
8971 * @returns {number[][]}
8972 */
8973 function adapt (W1, W2, id = "Bradford") {
8974 // adapt from a source whitepoint or illuminant W1
8975 // to a destination whitepoint or illuminant W2,
8976 // using the given chromatic adaptation transform (CAT)
8977 // debugger;
8978 let method = CATs[id];
8979
8980 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
8981 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
8982
8983 // all practical illuminants have non-zero XYZ so no division by zero can occur below
8984 // prettier-ignore
8985 let scale = [
8986 [ρd / ρs, 0, 0 ],
8987 [0, γd / γs, 0 ],
8988 [0, 0, βd / βs],
8989 ];
8990 // console.log({scale});
8991
8992 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
8993 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
8994 // console.log({scaled_cone_M, adapt_M});
8995 return adapt_M;
8996 }
8997
8998 // prettier-ignore
8999 defineCAT({
9000 id: "von Kries",
9001 toCone_M: [
9002 [ 0.4002400, 0.7076000, -0.0808100 ],
9003 [ -0.2263000, 1.1653200, 0.0457000 ],
9004 [ 0.0000000, 0.0000000, 0.9182200 ],
9005 ],
9006 fromCone_M: [
9007 [ 1.8599363874558397, -1.1293816185800916, 0.21989740959619328 ],
9008 [ 0.3611914362417676, 0.6388124632850422, -0.000006370596838649899 ],
9009 [ 0, 0, 1.0890636230968613 ],
9010 ],
9011 });
9012
9013 // prettier-ignore
9014 defineCAT({
9015 id: "Bradford",
9016 // Convert an array of XYZ values in the range 0.0 - 1.0
9017 // to cone fundamentals
9018 toCone_M: [
9019 [ 0.8951000, 0.2664000, -0.1614000 ],
9020 [ -0.7502000, 1.7135000, 0.0367000 ],
9021 [ 0.0389000, -0.0685000, 1.0296000 ],
9022 ],
9023 // and back
9024 fromCone_M: [
9025 [ 0.9869929054667121, -0.14705425642099013, 0.15996265166373122 ],
9026 [ 0.4323052697233945, 0.5183602715367774, 0.049291228212855594 ],
9027 [ -0.00852866457517732, 0.04004282165408486, 0.96848669578755 ],
9028 ],
9029 });
9030
9031 // prettier-ignore
9032 defineCAT({
9033 id: "CAT02",
9034 // with complete chromatic adaptation to W2, so D = 1.0
9035 toCone_M: [
9036 [ 0.7328000, 0.4296000, -0.1624000 ],
9037 [ -0.7036000, 1.6975000, 0.0061000 ],
9038 [ 0.0030000, 0.0136000, 0.9834000 ],
9039 ],
9040 fromCone_M: [
9041 [ 1.0961238208355142, -0.27886900021828726, 0.18274517938277307 ],
9042 [ 0.4543690419753592, 0.4735331543074117, 0.07209780371722911 ],
9043 [ -0.009627608738429355, -0.00569803121611342, 1.0153256399545427 ],
9044 ],
9045 });
9046
9047 // prettier-ignore
9048 defineCAT({
9049 id: "CAT16",
9050 toCone_M: [
9051 [ 0.401288, 0.650173, -0.051461 ],
9052 [ -0.250268, 1.204414, 0.045854 ],
9053 [ -0.002079, 0.048952, 0.953127 ],
9054 ],
9055 // the extra precision is needed to avoid roundtripping errors
9056 fromCone_M: [
9057 [ 1.862067855087233, -1.0112546305316845, 0.14918677544445172 ],
9058 [ 0.3875265432361372, 0.6214474419314753, -0.008973985167612521 ],
9059 [ -0.01584149884933386, -0.03412293802851557, 1.0499644368778496 ],
9060 ],
9061 });
9062
9063 // prettier-ignore
9064 Object.assign(WHITES, {
9065 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
9066 // all normalized to Y (luminance) = 1.00000
9067 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
9068 A: [1.09850, 1.00000, 0.35585],
9069
9070 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
9071 C: [0.98074, 1.000000, 1.18232],
9072
9073 // The daylight series of illuminants simulate natural daylight.
9074 // The color temperature (in degrees Kelvin/100) ranges from
9075 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
9076 D55: [0.95682, 1.00000, 0.92149],
9077 D75: [0.94972, 1.00000, 1.22638],
9078
9079 // Equal-energy illuminant, used in two-stage CAT16
9080 E: [1.00000, 1.00000, 1.00000],
9081
9082 // The F series of illuminants represent fluorescent lights
9083 F2: [0.99186, 1.00000, 0.67393],
9084 F7: [0.95041, 1.00000, 1.08747],
9085 F11: [1.00962, 1.00000, 0.64350],
9086 });
9087
9088 /** @import { Matrix3x3 } from "../types.js" */
9089
9090 // The ACES whitepoint
9091 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
9092 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
9093 // Similar to D60
9094 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
9095
9096 /**
9097 * Matrices used by this color space, also available as `ACEScg.M`
9098 * @type {Record<string, Matrix3x3>}
9099 */
9100 // prettier-ignore
9101 const M = {
9102 // convert an array of linear-light ACEScg values to CIE XYZ
9103 toXYZ: [
9104 [ 0.6624541811085053, 0.13400420645643313, 0.1561876870049078 ],
9105 [ 0.27222871678091454, 0.6740817658111484, 0.05368951740793705 ],
9106 [ -0.005574649490394108, 0.004060733528982826, 1.0103391003129971 ],
9107 ],
9108 fromXYZ: [
9109 [ 1.6410233796943257, -0.32480329418479, -0.23642469523761225 ],
9110 [ -0.6636628587229829, 1.6153315916573379, 0.016756347685530137 ],
9111 [ 0.011721894328375376, -0.008284441996237409, 0.9883948585390215 ],
9112 ],
9113 };
9114
9115 var ACEScg = new RGBColorSpace({
9116 id: "acescg",
9117 cssId: "--acescg",
9118 name: "ACEScg",
9119
9120 // ACEScg – A scene-referred, linear-light encoding of ACES Data
9121 // https://docs.acescentral.com/specifications/acescg/
9122 // uses the AP1 primaries, see section 4.3.1 Color primaries
9123 coords: {
9124 r: {
9125 range: [0, 65504],
9126 name: "Red",
9127 },
9128 g: {
9129 range: [0, 65504],
9130 name: "Green",
9131 },
9132 b: {
9133 range: [0, 65504],
9134 name: "Blue",
9135 },
9136 },
9137
9138 referred: "scene",
9139
9140 white: WHITES.ACES,
9141
9142 M,
9143 });
9144
9145 // export default Color;
9146
9147 const ε = 2 ** -16;
9148
9149 // the smallest value which, in the 32bit IEEE 754 float encoding,
9150 // decodes as a non-negative value
9151 const ACES_min_nonzero = -0.35828683;
9152
9153 // brightest encoded value, decodes to 65504
9154 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
9155
9156 var acescc = new RGBColorSpace({
9157 id: "acescc",
9158 cssId: "--acescc",
9159 name: "ACEScc",
9160 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
9161 // https://docs.acescentral.com/specifications/acescc/
9162 // uses the AP1 primaries, see section 4.3.1 Color primaries
9163
9164 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
9165 // below 18% middle gray are encoded as negative ACEScc values.
9166 // These values should be preserved per the encoding in Section 4.4
9167 // so that all positive ACES values are maintained."
9168 coords: {
9169 r: {
9170 range: [ACES_min_nonzero, ACES_cc_max],
9171 name: "Red",
9172 },
9173 g: {
9174 range: [ACES_min_nonzero, ACES_cc_max],
9175 name: "Green",
9176 },
9177 b: {
9178 range: [ACES_min_nonzero, ACES_cc_max],
9179 name: "Blue",
9180 },
9181 },
9182 referred: "scene",
9183
9184 base: ACEScg,
9185 linearGamut: ACEScg,
9186 // from section 4.4.2 Decoding Function
9187 toBase (RGB) {
9188 const low = (9.72 - 15) / 17.52; // -0.3014
9189
9190 return RGB.map(function (val) {
9191 if (val <= low) {
9192 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
9193 }
9194 else if (val < ACES_cc_max) {
9195 return 2 ** (val * 17.52 - 9.72);
9196 }
9197 else {
9198 // val >= ACES_cc_max
9199 return 65504;
9200 }
9201 });
9202 },
9203
9204 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
9205 fromBase (RGB) {
9206 return RGB.map(function (val) {
9207 if (val <= 0) {
9208 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
9209 }
9210 else if (val < ε) {
9211 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
9212 }
9213 else {
9214 // val >= ε
9215 return (Math.log2(val) + 9.72) / 17.52;
9216 }
9217 });
9218 },
9219 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
9220 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
9221 });
9222
9223 /**
9224 * @packageDocumentation
9225 * Re-exports all the spaces built into Color.js.
9226 */
9227
9228 var spaces = /*#__PURE__*/Object.freeze({
9229 __proto__: null,
9230 A98RGB: a98rgb,
9231 A98RGB_Linear: A98Linear,
9232 ACEScc: acescc,
9233 ACEScg: ACEScg,
9234 CAM16_JMh: cam16,
9235 HCT: hct,
9236 HPLuv: HPLuv,
9237 HSL: HSL,
9238 HSL_P3: hslP3,
9239 HSL_REC2020: hslRec2020,
9240 HSLuv: hsluv,
9241 HSV: HSV,
9242 HWB: hwb,
9243 HelmGen: HelmGen,
9244 HelmGenLCh: helmgenlch,
9245 Helmlab: helmlab,
9246 ICTCP: ictcp,
9247 JzCzHz: jzczhz,
9248 Jzazbz: Jzazbz,
9249 LCH: lch,
9250 LCH_P3: lchP3,
9251 LCH_REC_2020: lchRec2020,
9252 LCH_sRGB: lchSrgb,
9253 LCHuv: LCHuv,
9254 Lab: lab,
9255 Lab_D65: lab_d65,
9256 Luv: Luv,
9257 OKLCH: OKLCH,
9258 OKLCH_P3: oklchP3,
9259 OKLCH_REC_2020: oklchRec2020,
9260 OKLCH_sRGB: oklchSrgb,
9261 OKLab: Oklab,
9262 OKLrCH: oklrch,
9263 OKLrab: OKLrab,
9264 Okhsl: Okhsl,
9265 Okhsv: Okhsv,
9266 P3: P3,
9267 P3_Linear: P3Linear,
9268 ProPhoto: prophoto,
9269 ProPhoto_Linear: ProPhotoLinear,
9270 REC_2020: REC2020,
9271 REC_2020_Linear: REC2020Linear,
9272 REC_2020_Scene_Referred: rec2020Oetf,
9273 REC_2100_HLG: rec2100Hlg,
9274 REC_2100_Linear: REC_2100_Linear,
9275 REC_2100_PQ: rec2100Pq,
9276 XYZ_ABS_D65: XYZ_Abs_D65,
9277 XYZ_D50: XYZ_D50,
9278 XYZ_D65: XYZ_D65,
9279 sRGB: sRGB,
9280 sRGB_Linear: sRGBLinear
9281 });
9282
9283 /**
9284 * @packageDocumentation
9285 * @class Color
9286 * Class that represents a single color.
9287 * All of Color.js’s tree-shakeable methods are also available as instance methods on this class,
9288 * as well as static methods that take the color as the first argument.
9289 */
9290
9291
9292 class Color {
9293 /**
9294 * Creates an instance of Color.
9295 * Signatures:
9296 * - `new Color(stringToParse)`
9297 * - `new Color(otherColor)`
9298 * - `new Color({space, coords, alpha})`
9299 * - `new Color(space, coords, alpha)`
9300 * - `new Color(spaceId, coords, alpha)`
9301 */
9302 constructor (...args) {
9303 let color;
9304
9305 if (args.length === 1) {
9306 let parseMeta = {};
9307 // Clone simple objects to avoid mutating original in getColor
9308 if (
9309 typeof args[0] === "object" &&
9310 Object.getPrototypeOf(args[0]).constructor === Object
9311 ) {
9312 args[0] = { ...args[0] };
9313 }
9314 color = getColor(args[0], { parseMeta });
9315
9316 if (parseMeta.format) {
9317 // Color actually came from a string
9318 this.parseMeta = parseMeta;
9319 }
9320 }
9321
9322 let space, coords, alpha;
9323
9324 if (color) {
9325 space = color.space || color.spaceId;
9326 coords = color.coords;
9327 alpha = color.alpha;
9328 }
9329 else {
9330 // default signature new Color(ColorSpace, array [, alpha])
9331 [space, coords, alpha] = args;
9332 }
9333
9334 Object.defineProperty(this, "space", {
9335 value: ColorSpace.get(space),
9336 writable: false,
9337 enumerable: true,
9338 configurable: true, // see note in https://262.ecma-international.org/8.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
9339 });
9340
9341 this.coords = coords ? coords.slice() : [0, 0, 0];
9342
9343 // Clamp alpha to [0, 1]
9344 this.alpha = isNone(alpha) ? alpha : alpha === undefined ? 1 : clamp(0, alpha, 1);
9345
9346 // Define getters and setters for each coordinate
9347 for (let id in this.space.coords) {
9348 Object.defineProperty(this, id, {
9349 get: () => this.get(id),
9350 set: value => this.set(id, value),
9351 });
9352 }
9353 }
9354
9355 get spaceId () {
9356 return this.space.id;
9357 }
9358
9359 clone () {
9360 return new Color(this.space, this.coords, this.alpha);
9361 }
9362
9363 toJSON () {
9364 return {
9365 spaceId: this.spaceId,
9366 coords: this.coords,
9367 alpha: this.alpha,
9368 };
9369 }
9370
9371 display (...args) {
9372 let ret = display(this, ...args);
9373
9374 // Convert color object to Color instance
9375 ret.color = new Color(ret.color);
9376
9377 return ret;
9378 }
9379
9380 /**
9381 * Get a color from the argument(s) passed
9382 * Basically gets us the same result as new Color(color) but doesn't clone an existing color object
9383 */
9384 static get (color, ...args) {
9385 if (isInstance(color, this)) {
9386 return color;
9387 }
9388
9389 return new Color(color, ...args);
9390 }
9391
9392 /**
9393 * Get a color instance from the argument passed or `null` if resolution fails (instead of throwing an error).
9394 * Additionally, it supports passing an element to resolve complex CSS colors through the DOM (slow).
9395 * @see {@link tryColor} for more details
9396 */
9397 static try (color, options) {
9398 if (isInstance(color, this)) {
9399 return color;
9400 }
9401
9402 let ret = tryColor(color, options);
9403
9404 if (ret) {
9405 return new Color(ret);
9406 }
9407
9408 return null;
9409 }
9410
9411 static defineFunction (name, code, o = code) {
9412 let { instance = true, returns } = o;
9413
9414 let func = function (...args) {
9415 let ret = code(...args);
9416
9417 if (returns === "color") {
9418 ret = Color.get(ret);
9419 }
9420 else if (returns === "function<color>") {
9421 let f = ret;
9422 ret = function (...args) {
9423 let ret = f(...args);
9424 return Color.get(ret);
9425 };
9426 // Copy any function metadata
9427 Object.assign(ret, f);
9428 }
9429 else if (returns === "array<color>") {
9430 ret = ret.map(c => Color.get(c));
9431 }
9432
9433 return ret;
9434 };
9435
9436 if (!(name in Color)) {
9437 Color[name] = func;
9438 }
9439
9440 if (instance) {
9441 Color.prototype[name] = function (...args) {
9442 return func(this, ...args);
9443 };
9444 }
9445 }
9446
9447 static defineFunctions (o) {
9448 for (let name in o) {
9449 Color.defineFunction(name, o[name], o[name]);
9450 }
9451 }
9452
9453 static extend (exports) {
9454 if (exports.register) {
9455 exports.register(Color);
9456 }
9457 else {
9458 // No register method, just add the module's functions
9459 for (let name in exports) {
9460 Color.defineFunction(name, exports[name]);
9461 }
9462 }
9463 }
9464 }
9465
9466 Color.defineFunctions({
9467 get,
9468 getAll,
9469 set,
9470 setAll,
9471 to,
9472 equals,
9473 inGamut,
9474 toGamut,
9475 distance,
9476 deltas,
9477 toString: serialize,
9478 });
9479
9480 Object.assign(Color, {
9481 util,
9482 hooks,
9483 WHITES,
9484 Space: ColorSpace,
9485 spaces: ColorSpace.registry,
9486 parse,
9487
9488 // Global defaults one may want to configure
9489 defaults,
9490 });
9491
9492 /**
9493 * @packageDocumentation
9494 * This module contains {@link spaces a namespace} with all the spaces built into Color.js.
9495 */
9496
9497 for (let key of Object.keys(spaces)) {
9498 ColorSpace.register(spaces[key]);
9499 }
9500
9501 /**
9502 * This plugin defines getters and setters for color[spaceId]
9503 * e.g. color.lch on *any* color gives us the lch coords
9504 */
9505
9506 // Add space accessors to existing color spaces
9507 for (let id in ColorSpace.registry) {
9508 addSpaceAccessors(id, ColorSpace.registry[id]);
9509 }
9510
9511 // Add space accessors to color spaces not yet created
9512 hooks.add("colorspace-init-end", space => {
9513 addSpaceAccessors(space.id, space);
9514 space.aliases?.forEach(alias => {
9515 addSpaceAccessors(alias, space);
9516 });
9517 });
9518
9519 function addSpaceAccessors (id, space) {
9520 let propId = id.replace(/-/g, "_");
9521
9522 Object.defineProperty(Color.prototype, propId, {
9523 // Convert coords to coords in another colorspace and return them
9524 // Source colorspace: this.spaceId
9525 // Target colorspace: id
9526 get () {
9527 let ret = this.getAll(id);
9528
9529 if (typeof Proxy === "undefined") {
9530 // If proxies are not supported, just return a static array
9531 return ret;
9532 }
9533
9534 // Enable color.spaceId.coordName syntax
9535 let proxy = new Proxy(ret, {
9536 has: /** @param {string} property */ (obj, property) => {
9537 try {
9538 ColorSpace.resolveCoord([space, property]);
9539 return true;
9540 }
9541 catch (e) {}
9542
9543 return Reflect.has(obj, property);
9544 },
9545 get: (obj, property, receiver) => {
9546 if (
9547 property &&
9548 typeof property !== "symbol" &&
9549 !(property in obj) &&
9550 property in proxy
9551 ) {
9552 let { index } = ColorSpace.resolveCoord([space, property]);
9553
9554 if (index >= 0) {
9555 return obj[index];
9556 }
9557 }
9558
9559 return Reflect.get(obj, property, receiver);
9560 },
9561 set: (obj, property, value, receiver) => {
9562 if (
9563 (property && typeof property !== "symbol" && !(property in obj)) ||
9564 Number(property) >= 0
9565 ) {
9566 let { index } = ColorSpace.resolveCoord([
9567 space,
9568 /** @type {string} */ (property),
9569 ]);
9570
9571 if (index >= 0) {
9572 obj[index] = value;
9573
9574 // Update color.coords
9575 this.setAll(id, obj);
9576
9577 return true;
9578 }
9579 }
9580
9581 return Reflect.set(obj, property, value, receiver);
9582 },
9583 });
9584
9585 return proxy;
9586 },
9587 // Convert coords in another colorspace to internal coords and set them
9588 // Target colorspace: this.spaceId
9589 // Source colorspace: id
9590 set (coords) {
9591 this.setAll(id, coords);
9592 },
9593 configurable: true,
9594 enumerable: true,
9595 });
9596 }
9597
9598 /**
9599 * Entry point for the OOP flavor of the API
9600 * Import as `colorjs.io`
9601 */
9602
9603 Color.extend(deltaEMethods);
9604 Color.extend({ deltaE });
9605 Object.assign(Color, { deltaEMethods });
9606 Color.extend(variations);
9607 Color.extend({ contrast });
9608 Color.extend(chromaticity);
9609 Color.extend(luminance);
9610 Color.extend(interpolation);
9611 Color.extend(contrastMethods);
9612
9613 exports.default = Color;
9614 //# sourceMappingURL=color.cjs.map