Debian Codegraph @

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