-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
100 lines (88 loc) · 2.93 KB
/
index.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
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
97
98
99
100
const valueParser = require('postcss-values-parser');
const colors = require('color-name');
const {
convertingHEXColor,
convertingRGBColor,
convertingHSLColor,
convertingKeywordColor,
} = require('./src/converts');
const {
HEX_COLOR,
RGB_COLOR,
HSL_COLOR,
KEYWORD_COLOR,
} = require('./src/constants');
const colorNames = Object.keys(colors);
const colorFormats = [HEX_COLOR, RGB_COLOR, HSL_COLOR, KEYWORD_COLOR];
const propsWithColorRegExp = /(background|border|shadow|color|fill|outline|@|--|\$)/;
const ignoredValuesRegExp = /(url)/;
const specValuesInParamsRegExp = /(\$|calc|var)/;
const defaultOptions = {
outputColorFormat: '',
alwaysAlpha: false,
ignore: [],
};
module.exports = (options = {}) => {
const currentOptions = {
...defaultOptions,
...options,
};
if (!currentOptions.outputColorFormat) {
throw new Error(`'outputColorFormat' option is undefined.`)
}
if (!colorFormats.includes(currentOptions.outputColorFormat)) {
throw new Error(`The specified value of 'outputColorFormat' is not contained in [${colorFormats.join()}].`)
}
return {
postcssPlugin: 'postcss-color-converter',
Declaration (decl) {
if (
decl.prop && propsWithColorRegExp.test(decl.prop) && decl.value && !ignoredValuesRegExp.test(decl.value)
) {
let valueObj = valueParser.parse(decl.value, { ignoreUnknownWords: true });
valueObj.walk(node => {
if (node.isColor) {
if (
!currentOptions.ignore.includes(HEX_COLOR) &&
currentOptions.outputColorFormat !== HEX_COLOR &&
node.isHex
) {
node = convertingHEXColor(node, currentOptions);
} else if (
(
!currentOptions.ignore.includes(RGB_COLOR) &&
(
currentOptions.alwaysAlpha ||
currentOptions.outputColorFormat !== RGB_COLOR
)
) &&
(node.name === 'rgb' || node.name === 'rgba') &&
!specValuesInParamsRegExp.test(node.params)
) {
node = convertingRGBColor(node, currentOptions);
} else if (
(
!currentOptions.ignore.includes(HSL_COLOR) &&
(
currentOptions.alwaysAlpha ||
currentOptions.outputColorFormat !== HSL_COLOR
)
) &&
(node.name === 'hsl' || node.name === 'hsla') &&
!specValuesInParamsRegExp.test(node.params)
) {
node = convertingHSLColor(node, currentOptions);
} else if (
!currentOptions.ignore.includes(KEYWORD_COLOR) &&
colorNames.includes(node.value)
) {
node = convertingKeywordColor(node, currentOptions);
}
}
});
decl.value = valueObj.toString();
}
}
};
};
module.exports.postcss = true;