Debian Codegraph @

node/colorjs.io/dist/color.js

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