1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const chroma = require('chroma-js');
|
14 | const {
|
15 | colorSpaces,
|
16 | createScale,
|
17 | } = require('./utils');
|
18 |
|
19 | class Color {
|
20 | constructor({ name, colorKeys, colorspace = 'RGB', ratios, smooth = false, output = 'HEX' }) {
|
21 | this._name = name;
|
22 | this._colorKeys = colorKeys;
|
23 | this._colorspace = colorspace;
|
24 | this._ratios = ratios;
|
25 | this._smooth = smooth;
|
26 | this._output = output;
|
27 | if (!this._name) {
|
28 | throw new Error('Color missing name');
|
29 | }
|
30 | if (!this._colorKeys) {
|
31 | throw new Error('Color Keys are undefined');
|
32 | }
|
33 | if (!colorSpaces[this._colorspace]) {
|
34 | throw new Error(`Colorspace “${colorspace}” not supported`);
|
35 | }
|
36 | if (!colorSpaces[this._output]) {
|
37 | throw new Error(`Output “${colorspace}” not supported`);
|
38 | }
|
39 |
|
40 | for (let i = 0; i < this._colorKeys.length; i++) {
|
41 | if (!chroma.valid(this._colorKeys[i])) {
|
42 | throw new Error(`Invalid Color Key “${this._colorKeys[i]}”`);
|
43 | }
|
44 | }
|
45 |
|
46 |
|
47 | this._colorScale = null;
|
48 | }
|
49 |
|
50 |
|
51 | set colorKeys(colorKeys) {
|
52 | this._colorKeys = colorKeys;
|
53 | this._colorScale = null;
|
54 | }
|
55 |
|
56 | get colorKeys() {
|
57 | return this._colorKeys;
|
58 | }
|
59 |
|
60 | set colorspace(colorspace) {
|
61 | this._colorspace = colorspace;
|
62 | this._colorScale = null;
|
63 | }
|
64 |
|
65 | get colorspace() {
|
66 | return this._colorspace;
|
67 | }
|
68 |
|
69 | set ratios(ratios) {
|
70 | this._ratios = ratios;
|
71 | }
|
72 |
|
73 | get ratios() {
|
74 | return this._ratios;
|
75 | }
|
76 |
|
77 | set name(name) {
|
78 | this._name = name;
|
79 | }
|
80 |
|
81 | get name() {
|
82 | return this._name;
|
83 | }
|
84 |
|
85 | set smooth(smooth) {
|
86 | this._smooth = smooth;
|
87 | this._colorScale = null;
|
88 | }
|
89 |
|
90 | get smooth() {
|
91 | return this._smooth;
|
92 | }
|
93 |
|
94 | set output(output) {
|
95 | this._output = output;
|
96 | this._colorScale = null;
|
97 | }
|
98 |
|
99 | get output() {
|
100 | return this._output;
|
101 | }
|
102 |
|
103 | get colorScale() {
|
104 | if (!this._colorScale) {
|
105 | this._generateColorScale();
|
106 | }
|
107 | return this._colorScale;
|
108 | }
|
109 |
|
110 | _generateColorScale() {
|
111 |
|
112 |
|
113 | this._colorScale = createScale({
|
114 | swatches: 3000,
|
115 | colorKeys: this._colorKeys,
|
116 | colorspace: this._colorspace,
|
117 | shift: 1,
|
118 | smooth: this._smooth,
|
119 | asFun: true,
|
120 | });
|
121 | }
|
122 | }
|
123 | module.exports = { Color };
|