/
colours.js
34 lines (31 loc) · 958 Bytes
/
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
import { process, getFormat } from './lib/color';
import getShortestString from './lib/getShortestString';
export default (input, isLegacy = false) => {
const colour = input.toLowerCase();
const format = getFormat(colour);
if (format === 'rgb') {
/* check that it is a valid CSS value
https://www.w3.org/TR/css-color-4/#rgb-functions */
let percentCount = 0;
for (const c of colour) {
if (c === '%') {
percentCount++;
}
}
// rgb values should either be all percentages or all numbers
if (percentCount !== 3 && percentCount !== 0) {
return colour;
}
}
if (format) {
// Try to shorten the string if it was successfully parsed
// Fall back to the original input if it's smaller or has equal length
return getShortestString([
colour,
process(colour).toShortString({ isLegacy }),
]);
} else {
// Possibly malformed, so pass through
return input;
}
};