/
colours.js
45 lines (37 loc) · 1.07 KB
/
colours.js
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
import { colord, extend } from 'colord';
import namesPlugin from 'colord/plugins/names';
import toShorthand from './lib/toShorthand';
extend([namesPlugin]);
export default (colour, isLegacy = false) => {
const parsed = colord(colour);
if (parsed.isValid()) {
const alpha = parsed.alpha();
if (alpha === 1) {
const toHex = toShorthand(parsed.toHex());
const toName = parsed.toName();
if (toName && toName.length < toHex.length) {
return toName;
} else {
return toHex;
}
} else {
const rgb = parsed.toRgb();
if (!isLegacy && !rgb.r && !rgb.g && !rgb.b && !alpha) {
return 'transparent';
}
let hsla = parsed.toHslString();
let rgba = parsed.toRgbString();
const shortestConversion = hsla.length < rgba.length ? hsla : rgba;
let result;
if (colour.length < shortestConversion.length) {
result = colour;
} else {
result = shortestConversion;
}
return result;
}
} else {
// Possibly malformed, so pass through
return colour;
}
};