-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
hwb.ts
47 lines (40 loc) 路 1.27 KB
/
hwb.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
44
45
46
47
import { RgbaColor, HwbaColor, InputObject } from "../types";
import { ALPHA_PRECISION } from "../constants";
import { clamp, clampHue, round, isPresent } from "../helpers";
import { hsvaToRgba, rgbaToHsva } from "./hsv";
export const clampHwba = (hwba: HwbaColor): HwbaColor => ({
h: clampHue(hwba.h),
w: clamp(hwba.w, 0, 100),
b: clamp(hwba.b, 0, 100),
a: clamp(hwba.a),
});
export const roundHwba = (hwba: HwbaColor): HwbaColor => ({
h: round(hwba.h),
w: round(hwba.w),
b: round(hwba.b),
a: round(hwba.a, ALPHA_PRECISION),
});
export const rgbaToHwba = (rgba: RgbaColor): HwbaColor => {
const { h } = rgbaToHsva(rgba);
const w = (Math.min(rgba.r, rgba.g, rgba.b) / 255) * 100;
const b = 100 - (Math.max(rgba.r, rgba.g, rgba.b) / 255) * 100;
return { h, w, b, a: rgba.a };
};
export const hwbaToRgba = (hwba: HwbaColor): RgbaColor => {
return hsvaToRgba({
h: hwba.h,
s: hwba.b === 100 ? 0 : 100 - (hwba.w / (100 - hwba.b)) * 100,
v: 100 - hwba.b,
a: hwba.a,
});
};
export const parseHwba = ({ h, w, b, a = 1 }: InputObject): RgbaColor | null => {
if (!isPresent(h) || !isPresent(w) || !isPresent(b)) return null;
const hwba = clampHwba({
h: Number(h),
w: Number(w),
b: Number(b),
a: Number(a),
});
return hwbaToRgba(hwba);
};