-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
hsl.ts
61 lines (50 loc) 路 1.46 KB
/
hsl.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { InputObject, RgbaColor, HslaColor, HsvaColor } from "../types";
import { ALPHA_PRECISION } from "../constants";
import { clamp, clampHue, round, isPresent } from "../helpers";
import { hsvaToRgba, rgbaToHsva } from "./hsv";
export const clampHsla = (hsla: HslaColor): HslaColor => ({
h: clampHue(hsla.h),
s: clamp(hsla.s, 0, 100),
l: clamp(hsla.l, 0, 100),
a: clamp(hsla.a),
});
export const roundHsla = (hsla: HslaColor): HslaColor => ({
h: round(hsla.h),
s: round(hsla.s),
l: round(hsla.l),
a: round(hsla.a, ALPHA_PRECISION),
});
export const parseHsla = ({ h, s, l, a = 1 }: InputObject): RgbaColor | null => {
if (!isPresent(h) || !isPresent(s) || !isPresent(l)) return null;
const hsla = clampHsla({
h: Number(h),
s: Number(s),
l: Number(l),
a: Number(a),
});
return hslaToRgba(hsla);
};
export const hslaToHsva = ({ h, s, l, a }: HslaColor): HsvaColor => {
s *= (l < 50 ? l : 100 - l) / 100;
return {
h: h,
s: s > 0 ? ((2 * s) / (l + s)) * 100 : 0,
v: l + s,
a,
};
};
export const hsvaToHsla = ({ h, s, v, a }: HsvaColor): HslaColor => {
const hh = ((200 - s) * v) / 100;
return {
h,
s: hh > 0 && hh < 200 ? ((s * v) / 100 / (hh <= 100 ? hh : 200 - hh)) * 100 : 0,
l: hh / 2,
a,
};
};
export const hslaToRgba = (hsla: HslaColor): RgbaColor => {
return hsvaToRgba(hslaToHsva(hsla));
};
export const rgbaToHsla = (rgba: RgbaColor): HslaColor => {
return hsvaToHsla(rgbaToHsva(rgba));
};