Debian Codegraph @

node/colorjs.io/dist/color-fn.cjs

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