-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (60 loc) · 1.6 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
/**
* External dependencies
*/
const tinycolor = require( 'tinycolor2' );
const { parse } = require( 'postcss-values-parser' );
/**
* Internal dependencies
*/
const { getClosestColor } = require( './lib' );
module.exports = ( options = {} ) => {
const colorList = options.colors || {};
function getReplacementColor( color ) {
const newColor = getClosestColor( color, colorList );
const alpha = tinycolor( color ).getAlpha();
if ( alpha !== 1 ) {
const newColorWithAlpha = tinycolor( newColor ).setAlpha( alpha );
return newColorWithAlpha.toString();
}
return newColor.toString();
}
return {
postcssPlugin: 'postcss-palettize-colors',
Once( root ) {
// No colors passed in.
if ( ! Object.values( colorList ).length ) {
return;
}
// If we find this directive, this file should be skipped.
if ( '@no-color-match' === root.first.text ) {
return;
}
root.walkRules( ( rule ) => {
rule.walkDecls( ( decl ) => {
let hasNewColor = false;
const valueAst = parse( decl.value );
valueAst.walkWords( ( node ) => {
if ( ! node.isColor ) {
return;
}
node.value = getReplacementColor( node.value );
hasNewColor = true;
} );
valueAst.walkFuncs( ( node ) => {
if ( ! node.isColor ) {
return;
}
const newColor = getReplacementColor( node.toString() );
const newNode = parse( newColor ).first;
node.replaceWith( newNode );
hasNewColor = true;
} );
if ( hasNewColor ) {
decl.value = valueAst.toString();
}
} );
} );
},
};
};
module.exports.postcss = true