-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.js
executable file
·72 lines (65 loc) · 1.76 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
/**
* Module dependencies.
*/
var postcss = require("postcss")
var parser = require("postcss-value-parser")
var colorFn = require("css-color-function")
var helpers = require("postcss-message-helpers")
var defaultOptions = {
preserveCustomProps: true,
}
/**
* PostCSS plugin to transform color()
*/
module.exports = postcss.plugin("postcss-color-function", function(options) {
options = Object.assign({}, defaultOptions, options)
return function(style, result) {
style.walkDecls(function transformDecl(decl) {
if (!decl.value || decl.value.indexOf("color(") === -1) {
return
}
if (decl.value.indexOf("var(") !== -1) {
if (!options.preserveCustomProps) {
decl.remove()
return
}
result.messages.push({
plugin: "postcss-color-function",
type: "skipped-color-function-with-custom-property",
word: decl.value,
message:
"Skipped color function with custom property `" +
decl.value +
"`",
})
return
}
try {
decl.value = helpers.try(function transformColorValue() {
return transformColor(decl.value)
}, decl.source)
}
catch (error) {
decl.warn(result, error.message, {
word: decl.value,
index: decl.index,
})
}
})
}
})
/**
* Transform color() to rgb()
*
* @param {String} string declaration value
* @return {String} converted declaration value to rgba()
*/
function transformColor(string) {
return parser(string).walk(function(node) {
if (node.type !== "function" || node.value !== "color") {
return
}
node.value = colorFn.convert(parser.stringify(node))
node.type = "word"
}).toString()
}