/
hsl-space.ts
96 lines (87 loc) · 2.75 KB
/
hsl-space.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import HSLColorSpace from './types/hsl-color-space';
import hslConverter from '../utils/converter/hsl-converter';
import { setHueColorSpaceValue } from '../utils/hue-utils';
import AbstractSpace from '../abstract-space';
/**
* HSL wrapper which provides mutations and accessor functions for
* the HSL color space.
*
* @public
*/
export default class HSLSpace extends AbstractSpace<'hsl', HSLColorSpace> {
constructor(model: HSLColorSpace) {
super('hsl', model, hslConverter);
}
/**
* Retrieves the value of the hue channel for the current color space.
*
* @returns {number} the hue channel value of this color space
*/
public hue(): number {
return this.model.hue;
}
/**
* Retrieves the value of the saturation channel for the current color space.
*
* @returns {number} the saturation channel value of this color space
*/
public saturation(): number {
return this.model.saturation;
}
/**
* Retrieves the value of the lightness channel for the current color space.
*
* @returns {number} the lightness channel value of this color space
*/
public lightness(): number {
return this.model.lightness;
}
public setColor(color: keyof HSLColorSpace, value: number): HSLSpace {
const adjusted = setHueColorSpaceValue(this.model, color, value);
return this.applyModel(adjusted);
}
/**
* @inheritDoc
*/
public clone(): HSLSpace {
return new HSLSpace({ ...this.model });
}
/**
* Retrieves an array representing the HSL color space containing the primary colors.
*
* @remarks Array index is ordered logically [HSL]
*
* @return {[number, number, number]} the HSL color space values as an array
*/
public toArray(): [number, number, number] {
return [this.model.hue, this.model.saturation, this.model.lightness];
}
/**
* Prints valid CSS string value.
*
* @example
* Here's a simple usage example:
* ```ts
* color.toString() // hsl(25,40%,54%)
* ```
*
* @return {string} valid CSS color value.
*/
public toString(): string {
return `hsl(${parseFloat(this.model.hue.toFixed(1))},${parseFloat(
this.model.saturation.toFixed(1)
)}%,${parseFloat(this.model.lightness.toFixed(1))}%)`;
}
public applyModel(space: HSLColorSpace): HSLSpace {
this.model.hue = Math.min(Math.max(Math.floor(space.hue), 0), 360);
this.model.saturation = Math.min(
Math.max(Math.floor(space.saturation), 0),
100
);
this.model.lightness = Math.min(
Math.max(Math.floor(space.lightness), 0),
100
);
return this;
}
}