-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
85 lines (68 loc) · 1.89 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
'use strict';
const valueParser = require('postcss-value-parser');
const rgbShorthandRegex = /^([a-f\d])([a-f\d])([a-f\d])$/i;
const rgbRegex = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
/**
* Hex to RGB converter
* @param {string} hex hexadecimal string without #
* @return {array} RGB values
*/
function hexRgb(hex){
hex = hex.replace(rgbShorthandRegex, (m, r, g, b) => {
return r + r + g + g + b + b;
});
const rgb = hex.match(rgbRegex);
// Convert it
return rgb ? [
parseInt(rgb[1], 16),
parseInt(rgb[2], 16),
parseInt(rgb[3], 16)
] : false;
}
/**
* @typedef {{ colorFunctionNotation: 'legacy' | 'modern' }} Options
*/
/**
* CSS rule handler
* @param {string} decl CSS declaration
* @param {any} result PostCSS result
* @param {Options} options
*/
function ruleHandler(decl, result, options) {
const value = valueParser(decl.value).walk(node => {
if (node.type !== 'function' || node.value !== 'rgba') {
return;
}
const nodes = node.nodes;
// Check for the hex value
if (nodes[0].type !== 'word' || nodes[0].value.indexOf('#') !== 0) {
return;
}
const hex = nodes[0].value.replace('#', '');
const rgb = hexRgb(hex);
// If conversion fails, emit a warning
if (!rgb) {
result.warn('not a valid hex', { node: decl });
return;
}
// Replace hex value with rgb
nodes[0].value = options.colorFunctionNotation === 'modern' ? rgb.join(' ') : rgb.join(',');
}).toString();
decl.value = value;
}
/**
* @param {Options} [options]
*/
module.exports = (options = {}) => {
const colorFunctionNotation = options.colorFunctionNotation || 'legacy';
return {
postcssPlugin: 'postcss-hexrgba',
Declaration(decl, { result }) {
if (!decl.value.includes('rgba')) {
return;
}
ruleHandler(decl, result, { colorFunctionNotation });
},
};
};
module.exports.postcss = true;