-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
41 lines (38 loc) · 1.32 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
const postcss = require('postcss');
const bgUrlRegex = /url\([\s'"]?(.*?)[\s'"]?\)/g;
// eslint-disable-next-line security/detect-unsafe-regex
const protocolRegex = /(https?:)?\/\/|data:/g;
module.exports = postcss.plugin('postcss-shopify-settings-variables', () => {
// Work with options here
return (root) => {
// Transform CSS AST here
root.walk(function (node) {
if (node.type === 'decl') {
while (node.value.includes('$(')) {
node.value = node.value.replace(
/^([^$]*)(\$\()([^)]+)(\))(.*)$/,
function (match, $1, $2, $3, $4, $5) {
return $1 + '{{ settings.' + $3 + ' }}' + $5;
},
);
}
if (bgUrlRegex.test(node.value) && !protocolRegex.test(node.value)) {
node.value = node.value.replace(bgUrlRegex, function (match, $1) {
let urlAndFilters = $1.split('|');
let newVal = 'url({{ "';
urlAndFilters.forEach(function (current, index) {
if (index === 0) {
newVal += current.replace(/'|"/g, '').trim();
newVal += '" | asset_url ';
} else {
newVal += '| ' + current.trim() + ' ';
}
});
newVal += '}})';
return newVal;
});
}
}
});
};
});