-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (58 loc) · 2 KB
/
index.js
File metadata and controls
74 lines (58 loc) · 2 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
69
70
71
72
73
74
module.exports = shadesOf;
/**
* Generate Tailwind-compatible shades from a single color
* @param {string} hex The hex code to generate shades from
* @param {boolean} halfShades Generate additional shades, e.g. at 150
* @returns {{[key: number]: string}}
*/
function shadesOf(hex, halfShades = false) {
const baseColor = hexToRgbArray(hex);
const black = [0, 0, 0];
const white = [255, 255, 255];
let shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
if(halfShades) shades = [...shades, 150, 250, 350, 450, 550, 650, 750, 850].sort();
let result = {};
for(let shade of shades) {
const originalShade = shade;
if(shade === 500) {
result[shade] = hex;
continue;
}
let isDarkShade = shade > 500;
if(isDarkShade) shade -= 500;
const percentage = shade / 500;
const startColor = isDarkShade ? black : baseColor;
const endColor = isDarkShade ? baseColor : white;
result[originalShade] = getColor(percentage, startColor, endColor);
}
return result;
}
function hexToRgbArray(hex) {
const originalHex = hex;
hex = hex.replace('#', '');
if(hex.length === 3) hex = hex + hex;
const r = hex.substring(0, 2);
const g = hex.substring(2, 4);
const b = hex.substring(4, 6);
const rgb = [r, g, b].map(channel => {
try {
channel = parseInt(channel, 16);
if(channel < 0 || channel > 255) throw new Error;
return channel;
} catch {
throw new Error(`Invalid hex color provided: ${originalHex}`);
}
});
return rgb;
}
function getColor(percentage, start, end) {
const rgb = end.map((channel, index) => {
return Math.round(channel + percentage * (start[index] - channel));
});
const hex = '#' + rgb.map(channel => {
const component = channel.toString(16);
if(component.length === 1) return '0' + component;
return component;
}).join('');
return hex;
}