-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcolor-mix.ts
More file actions
68 lines (54 loc) · 1.57 KB
/
color-mix.ts
File metadata and controls
68 lines (54 loc) · 1.57 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type { PlainColorObject } from "colorjs.io";
import {
ColorSpace,
to as convert,
mix,
OKLab,
P3,
parse,
sRGB,
type ColorConstructor,
} from "colorjs.io/fn";
import type { StyleFunctionResolver } from "../resolve";
ColorSpace.register(sRGB);
ColorSpace.register(P3);
ColorSpace.register(OKLab);
export const colorMix: StyleFunctionResolver = (resolveValue, value) => {
const args = resolveValue(value[2]);
if (!Array.isArray(args) || args.length < 3) {
return;
}
try {
const space = args.shift();
let left: ColorConstructor | PlainColorObject = parse(
args.shift() as string,
);
let next = args.shift();
if (typeof next === "string" && next.endsWith("%")) {
left.alpha = parseFloat(next) / 100;
next = args.shift();
}
if (next === undefined) {
if (left.spaceId !== "srgb") {
left = convert(left, "srgb");
}
return `rgba(${(left.coords[0] ?? 0) * 255}, ${(left.coords[1] ?? 0) * 255}, ${(left.coords[2] ?? 0) * 255}, ${left.alpha})`;
}
if (typeof next !== "string") {
return;
}
const right = parse(next);
next = args.shift();
if (next && typeof next === "string" && next.endsWith("%")) {
right.alpha = parseFloat(next) / 100;
}
const result = mix(left, right, {
space,
outputSpace: "srgb",
});
return `rgba(${(result.coords[0] ?? 0) * 255}, ${(result.coords[1] ?? 0) * 255}, ${(result.coords[2] ?? 0) * 255}, ${result.alpha})`;
} catch {
return;
}
};