-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (48 loc) · 1.65 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
var postcss = require('postcss');
var helpers = require('postcss-message-helpers');
var reduceFunctionCall = require('reduce-function-call');
function parseRgbValues(str) {
var values = [];
var pos = 0;
var depth = 0;
str = str.trim();
str = str.replace(/\s+/g, ' ');
for (var i = 0, length = str.length; i < length; i++) {
var char = str[i];
if (char === '(') {
depth++;
} else if (char === ')') {
depth--;
} else if (!depth && ' ,/'.indexOf(char) !== -1) {
if (pos !== i) {
values.push(str.substring(pos, i));
}
pos = i + 1;
}
}
values.push(str.substring(pos));
return values;
}
module.exports = postcss.plugin('postcss-color-rgb', function () {
return function (css) {
css.walkDecls(function (decl) {
if (!decl.value || decl.value.search(/rgb[a]?\(/i) === -1) {
return;
}
decl.value = helpers.try(function () {
return reduceFunctionCall(decl.value, /(rgb[a]?)\(/, function (body, fn) {
var values = parseRgbValues(body);
if (values.length === 4) {
var alpha = values.pop();
if (alpha.indexOf('%') === alpha.length - 1) {
alpha = parseFloat(alpha) / 100;
}
values.push(alpha);
fn = 'rgba';
}
return fn + '(' + values.join(', ') + ')';
});
}, decl.source);
});
};
});