-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
89 lines (71 loc) · 1.87 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
/**
* Module RGB(a)-HEX
* @type {"postcss"}
*/
//
// Module dependencies
var postcss = require('postcss');
var rgb2hex = require('rgb2hex');
var assign = require('object-assign'); // fixme: remove after postcss node 0.12 drop support
//
// RGB(a) regex
var rgbReg = /rgb\(\d+%?\s*,\s*\d+%?\s*,\s*\d+%?\s*(,\s*\d?.?\d+)?\)/g;
var rgbaReg = /rgba\(\d+%?\s*,\s*\d+%?\s*,\s*\d+%?\s*(,\s*\d?.?\d+)?\)/g;
var rgbRgbaReg = /rgba?\(\d+%?\s*,\s*\d+%?\s*,\s*\d+%?\s*(,\s*\d?.?\d+)?\)/g;
/**
* PostCSS plugin
* @type {*}
*/
module.exports = postcss.plugin('postcss-rgba-hex', function(options) {
var reg = rgbRgbaReg;
var o = assign({}, options);
if(o.rgbOnly && o.rgbaOnly) {
console.error('Invalid options');
return noop;
}
if(o.rgbOnly) {
reg = rgbReg;
}
if(o.rgbaOnly) {
reg = rgbaReg;
}
return function(style) {
style.walkDecls(function(decl) {
var val = decl.value;
// early return
if(!val) {
return;
}
// stripping values
var rgbValues = val.match(reg);
// converting values
if(rgbValues && rgbValues.length > 0) {
var newVal = val;
rgbValues.forEach(function(rgb) {
newVal = newVal.replace(rgb, rgbaToHex(rgb));
if (!o.silent) {
console.info('RGB(a) replaced: ' + rgb + ' -> ' + rgbaToHex(rgb));
}
});
decl.value = newVal;
}
});
};
});
/**
* RGBA(a) to hex transformer
* @param rgbaString
* @returns {string}
*/
function rgbaToHex(rgbaString) {
var hexString = '';
hexString = rgb2hex(rgbaString).hex;
return hexString;
}
/**
* function doing nothing
* @returns {boolean}
*/
function noop() {
return false;
}