Debian Codegraph @

node/colorjs.io/src/interpolation.js

raw
1 /**
2 * Functions related to color interpolation
3 */
4 import ColorSpace from "./ColorSpace.js";
5 import { type, interpolate, isNone } from "./util.js";
6 import getColor from "./getColor.js";
7 import clone from "./clone.js";
8 import to from "./to.js";
9 import toGamut from "./toGamut.js";
10 import get from "./get.js";
11 import set from "./set.js";
12 import defaults from "./defaults.js";
13 import * as angles from "./angles.js";
14 import deltaE from "./deltaE.js";
15
16 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
17
18 // Type re-exports
19 /** @typedef {import("./types.js").MixOptions} MixOptions */
20 /** @typedef {import("./types.js").Range} Range */
21 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
22 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
23
24 /**
25 * Return an intermediate color between two colors
26 * @overload
27 * @param {ColorTypes} c1
28 * @param {ColorTypes} c2
29 * @param {MixOptions} [options]
30 * @returns {PlainColorObject}
31 */
32 /**
33 * @overload
34 * @param {ColorTypes} c1
35 * @param {ColorTypes} c2
36 * @param {number} [p=0.5]
37 * @param {MixOptions} [options]
38 * @returns {PlainColorObject}
39 */
40 export function mix (c1, c2, p, o = {}) {
41 [c1, c2] = [getColor(c1), getColor(c2)];
42
43 if (type(p) === "object") {
44 [p, o] = [0.5, p];
45 }
46
47 let r = range(c1, c2, o);
48 return r(p ?? 0.5); // why not give p a default value like we do for options? Overloading doesn't work, and TS complains
49 }
50
51 /**
52 * Get an array of discrete steps
53 * @overload
54 * @param {ColorTypes} c1
55 * @param {ColorTypes} c2
56 * @param {StepsOptions} [options]
57 * @returns {PlainColorObject[]}
58 */
59 /**
60 * @overload
61 * @param {Range} range
62 * @param {StepsOptions} [options]
63 * @returns {PlainColorObject[]}
64 */
65 export function steps (c1, c2, options = {}) {
66 let colorRange;
67
68 if (isRange(c1)) {
69 // Tweaking existing range
70 [colorRange, options] = [c1, c2];
71 [c1, c2] = colorRange.rangeArgs.colors;
72 }
73
74 let { maxDeltaE, deltaEMethod, steps = 2, maxSteps = 1000, ...rangeOptions } = options;
75
76 if (!colorRange) {
77 [c1, c2] = [getColor(c1), getColor(c2)];
78 colorRange = range(c1, c2, rangeOptions);
79 }
80
81 let totalDelta = deltaE(c1, c2, deltaEMethod);
82 let actualSteps =
83 maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
84 let ret = [];
85
86 if (maxSteps !== undefined) {
87 actualSteps = Math.min(actualSteps, maxSteps);
88 }
89
90 if (actualSteps === 1) {
91 ret = [{ p: 0.5, color: colorRange(0.5) }];
92 }
93 else {
94 let step = 1 / (actualSteps - 1);
95 ret = Array.from({ length: actualSteps }, (_, i) => {
96 let p = i * step;
97 return { p, color: colorRange(p) };
98 });
99 }
100
101 if (maxDeltaE > 0) {
102 // Iterate over all stops and find max deltaE
103 let maxDelta = ret.reduce((acc, cur, i) => {
104 if (i === 0) {
105 return 0;
106 }
107
108 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
109 return Math.max(acc, ΔΕ);
110 }, 0);
111
112 while (maxDelta > maxDeltaE) {
113 // Insert intermediate stops and measure maxDelta again
114 // We need to do this for all pairs, otherwise the midpoint shifts
115 maxDelta = 0;
116
117 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
118 let prev = ret[i - 1];
119 let cur = ret[i];
120
121 let p = (cur.p + prev.p) / 2;
122 let color = colorRange(p);
123 maxDelta = Math.max(
124 maxDelta,
125 deltaE(color, prev.color, deltaEMethod),
126 deltaE(color, cur.color, deltaEMethod),
127 );
128 ret.splice(i, 0, { p, color: colorRange(p) });
129 i++;
130 }
131 }
132 }
133
134 ret = ret.map(a => a.color);
135
136 return ret;
137 }
138
139 /**
140 * Creates a function that accepts a number and returns a color.
141 * For numbers in the range 0 to 1, the function interpolates;
142 * for numbers outside that range, the function extrapolates
143 * (and thus may not return the results you expect)
144 * @overload
145 * @param {Range} range
146 * @param {RangeOptions} [options]
147 * @returns {Range}
148 */
149 /**
150 * @overload
151 * @param {ColorTypes} color1
152 * @param {ColorTypes} color2
153 * @param {RangeOptions & Record<string, any>} [options]
154 * @returns {Range}
155 */
156 export function range (color1, color2, options = {}) {
157 if (isRange(color1)) {
158 // Tweaking existing range
159 let [r, options] = [color1, color2];
160
161 return range(...r.rangeArgs.colors, { ...r.rangeArgs.options, ...options });
162 }
163
164 let { space, outputSpace, progression, premultiplied } = options;
165
166 color1 = getColor(color1);
167 color2 = getColor(color2);
168
169 // Make sure we're working on copies of these colors
170 color1 = clone(color1);
171 color2 = clone(color2);
172
173 let rangeArgs = { colors: [color1, color2], options };
174
175 if (space) {
176 space = ColorSpace.get(space);
177 }
178 else {
179 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
180 }
181
182 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
183
184 color1 = to(color1, space);
185 color2 = to(color2, space);
186
187 // Gamut map to avoid areas of flat color
188 color1 = toGamut(color1);
189 color2 = toGamut(color2);
190
191 // The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz)
192 let hueId = space.hueId;
193 let hueIndex = space.hueIndex;
194
195 // Handle hue interpolation
196 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
197 if (hueId) {
198 let arc = (options.hue = options.hue || "shorter");
199
200 let /** @type {Ref} */ hue = [space, hueId];
201 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
202 // Undefined hues must be evaluated before hue fix-up to properly
203 // calculate hue arcs between undefined and defined hues.
204 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
205 if (isNone(θ1) && !isNone(θ2)) {
206 θ1 = θ2;
207 }
208 else if (isNone(θ2) && !isNone(θ1)) {
209 θ2 = θ1;
210 }
211 [θ1, θ2] = angles.adjust(arc, [θ1, θ2]);
212 set(color1, hue, θ1);
213 set(color2, hue, θ2);
214 }
215
216 // An undefined alpha takes the other color's alpha, and premultiplication must use
217 // that carried forward value, rather than the zero it would otherwise be treated as.
218 // If both alphas are undefined, they stay that way, and no premultiplication happens.
219 // See https://drafts.csswg.org/css-color-4/#interpolation-missing
220 if (isNone(color1.alpha) && !isNone(color2.alpha)) {
221 color1.alpha = color2.alpha;
222 }
223 else if (isNone(color2.alpha) && !isNone(color1.alpha)) {
224 color2.alpha = color1.alpha;
225 }
226
227 if (premultiplied) {
228 color1.coords = premultiply(color1.coords, color1.alpha, hueIndex);
229 color2.coords = premultiply(color2.coords, color2.alpha, hueIndex);
230 }
231
232 return Object.assign(
233 p => {
234 p = progression ? progression(p) : p;
235 let coords = color1.coords.map((start, i) => {
236 let end = color2.coords[i];
237 return interpolate(start, end, p);
238 });
239
240 let alpha = interpolate(color1.alpha, color2.alpha, p);
241 let ret = { space, coords, alpha };
242
243 if (premultiplied) {
244 // Undo premultiplication, again leaving any hue angle untouched
245 ret.coords = premultiply(ret.coords, alpha, hueIndex, true);
246 }
247
248 if (outputSpace !== space) {
249 ret = to(ret, outputSpace);
250 }
251
252 return ret;
253 },
254 {
255 rangeArgs,
256 },
257 );
258 }
259
260 /**
261 * Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it.
262 * Per CSS Color 4, the hue angle of a polar space is never premultiplied,
263 * `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all,
264 * and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero.
265 * See https://drafts.csswg.org/css-color-4/#interpolation-alpha
266 * @param {(number | null)[]} coords
267 * @param {number | null} alpha
268 * @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none
269 * @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it
270 * @returns {[number, number, number]}
271 */
272 function premultiply (coords, alpha, hueIndex, undo = false) {
273 if (isNone(alpha) || (undo && alpha === 0)) {
274 // The (un-)premultiplied value is the value itself
275 return /** @type {[number, number, number]} */ (coords);
276 }
277
278 return /** @type {[number, number, number]} */ (
279 coords.map((c, i) => {
280 if (i === hueIndex || isNone(c)) {
281 return c;
282 }
283
284 return undo ? c / alpha : c * alpha;
285 })
286 );
287 }
288
289 /**
290 * @param {any} val
291 * @returns {val is Range}
292 */
293 export function isRange (val) {
294 return type(val) === "function" && !!val.rangeArgs;
295 }
296
297 defaults.interpolationSpace = "lab";
298
299 /**
300 * @param {typeof import("./color.js").default} Color
301 */
302 export function register (Color) {
303 Color.defineFunction("mix", mix, { returns: "color" });
304 Color.defineFunction("range", range, { returns: "function<color>" });
305 Color.defineFunction("steps", steps, { returns: "array<color>" });
306 }