/
index.js
119 lines (96 loc) · 2.74 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import browserslist from 'browserslist';
import valueParser, { stringify } from 'postcss-value-parser';
import colormin from './colours';
function walk(parent, callback) {
parent.nodes.forEach((node, index) => {
const bubble = callback(node, index, parent);
if (node.nodes && bubble !== false) {
walk(node, callback);
}
});
}
/*
* IE 8 & 9 do not properly handle clicks on elements
* with a `transparent` `background-color`.
*
* https://developer.mozilla.org/en-US/docs/Web/Events/click#Internet_Explorer
*/
function hasTransparentBug(browser) {
return ~['ie 8', 'ie 9'].indexOf(browser);
}
function isMathFunctionNode(node) {
if (node.type !== 'function') {
return false;
}
return ['calc', 'min', 'max', 'clamp'].includes(node.value.toLowerCase());
}
function transform(value, isLegacy) {
const parsed = valueParser(value);
walk(parsed, (node, index, parent) => {
if (node.type === 'function') {
if (/^(rgb|hsl)a?$/i.test(node.value)) {
const { value: originalValue } = node;
node.value = colormin(stringify(node), isLegacy);
node.type = 'word';
const next = parent.nodes[index + 1];
if (
node.value !== originalValue &&
next &&
(next.type === 'word' || next.type === 'function')
) {
parent.nodes.splice(index + 1, 0, {
type: 'space',
value: ' ',
});
}
} else if (isMathFunctionNode(node)) {
return false;
}
} else if (node.type === 'word') {
node.value = colormin(node.value, isLegacy);
}
});
return parsed.toString();
}
function pluginCreator() {
return {
postcssPlugin: 'postcss-colormin',
prepare(result) {
const resultOpts = result.opts || {};
const browsers = browserslist(null, {
stats: resultOpts.stats,
path: __dirname,
env: resultOpts.env,
});
const isLegacy = browsers.some(hasTransparentBug);
const cache = {};
return {
OnceExit(css) {
css.walkDecls((decl) => {
if (
/^(composes|font|filter|-webkit-tap-highlight-color)/i.test(
decl.prop
)
) {
return;
}
const value = decl.value;
if (!value) {
return;
}
const cacheKey = value + '|' + isLegacy;
if (cache[cacheKey]) {
decl.value = cache[cacheKey];
return;
}
const newValue = transform(value, isLegacy);
decl.value = newValue;
cache[cacheKey] = newValue;
});
},
};
},
};
}
pluginCreator.postcss = true;
export default pluginCreator;