Debian Codegraph @

node/colorjs.io/src/deltas.js

raw
1 import getColor from "./getColor.js";
2 import ColorSpace from "./ColorSpace.js";
3 import to from "./to.js";
4 import { adjust } from "./angles.js";
5 import { isNone } from "./util.js";
6
7 /** @import { ColorTypes } from "./types.js" */
8
9 // Type re-exports
10 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
11
12 /**
13 * Get color differences per-component, on any color space
14 * @param {ColorTypes} c1
15 * @param {ColorTypes} c2
16 * @param {object} options
17 * @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.
18 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
19 * @returns {DeltasReturn}
20 */
21 export default function deltas (c1, c2, { space, hue = "shorter" } = {}) {
22 c1 = getColor(c1);
23 space ||= c1.space;
24 space = ColorSpace.get(space);
25 let spaceCoords = Object.values(space.coords);
26
27 [c1, c2] = [c1, c2].map(c => to(c, space));
28 let [coords1, coords2] = [c1, c2].map(c => c.coords);
29
30 let coords = /** @type {[number, number, number]} */ (
31 coords1.map((coord1, i) => {
32 let coordMeta = spaceCoords[i];
33 let coord2 = coords2[i];
34
35 if (coordMeta.type === "angle") {
36 [coord1, coord2] = adjust(hue, [coord1, coord2]);
37 }
38
39 return subtractCoords(coord1, coord2);
40 })
41 );
42
43 let alpha = subtractCoords(c1.alpha, c2.alpha);
44
45 return { space: /** @type {ColorSpace} */ (space), coords, alpha };
46 }
47
48 function subtractCoords (c1, c2) {
49 if (isNone(c1) || isNone(c2)) {
50 return c1 === c2 ? null : 0;
51 }
52
53 return c1 - c2;
54 }