/
cmyk.ts
43 lines (38 loc) 路 1.36 KB
/
cmyk.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { TInput, Irgba, TFormat, Icmyka } from "../types";
import { adjustAlpha, clamp } from "../utils/numeric";
import { isCMYKObject } from "../utils/typeGuards";
import { CMYKtoRGB } from "../conversions/cmyk";
/**
* device-cmyk( <number | percentage>{4} [ / <alpha-value> ]? )
* @see https://www.w3.org/TR/css-color-4/#device-cmyk
*/
const CMYKA_RE =
/device-cmyka?\s*\(\s*(\d*\.?\d+%?)\s*,?\s*(\d*\.?\d+%?)\s*,?\s*(\d*\.?\d+%?)\s*,?\s*(\d*\.?\d+%?),?\s*\/?\s*?(\d*\.?\d+%?)?\s*\)/gi;
function createReturnArr({ c, m, y, k, a }: Icmyka): [Irgba, TFormat] {
return [
CMYKtoRGB({
c: clamp(0, c, 100),
m: clamp(0, m, 100),
y: clamp(0, y, 100),
k: clamp(0, k, 100),
a: adjustAlpha(a)
}),
"cmyk"
];
}
export function cmykaParser(color: TInput): [Irgba, TFormat] {
if (color.constructor.name.toLowerCase() === "object" && isCMYKObject(color)) {
return createReturnArr(color as Icmyka);
} else if (typeof color === "string") {
CMYKA_RE.lastIndex = 0;
const matches = CMYKA_RE.exec(color);
if (matches) {
const [c, m, y, k, a] = matches
.filter((val) => val !== undefined)
.slice(1)
.map((elem, i) => (elem.includes("%") ? +elem.slice(0, -1) * (i < 4 ? 1 : 0.01) : +elem));
return createReturnArr({ c, m, y, k, a });
}
}
return [{ r: 0, g: 0, b: 0, a: 1 }, "invalid"];
}