forked from macropodhq/postcss-constants
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
79 lines (63 loc) · 2.25 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
var postcss = require('postcss');
var nodepath = require('path');
var assign = require('lodash/object/assign');
var resolve = require('resolve');
module.exports = postcss.plugin('postcss-constants', function (opts) {
var sets = opts && opts.defaults || {};
var globalNode;
var regex = /~([\w]+)\.([\w]+)/g;
var getConstants = function(name, path, directory) {
var res = resolve.sync(JSON.parse(path), { basedir: nodepath.dirname(directory) });
var requiredSet = name.replace(/~/g, '');
var constantSets = require(res);
if (constantSets[requiredSet]) {
if (sets[requiredSet]) {
sets[requiredSet] = assign({}, sets[requiredSet], constantSets[requiredSet]);
}
else {
sets[requiredSet] = constantSets[requiredSet];
}
}
};
var requiresAction = function(context) {
return !!context.match(regex);
};
var getValue = function(constant, parent) {
if (!sets[parent]) {
throw globalNode.error('No such set `' + parent + '`');
}
if (!sets[parent][constant]) {
throw globalNode.error('No such constant `' + constant + '` in `' + parent + '`');
}
return sets[parent][constant];
};
var strip = function(context) {
if (!requiresAction(context)) {
return context;
}
var requires = context.match(regex);
requires.forEach(function(require) {
var matches = regex.exec(require);
regex.lastIndex = 0;
var constant = matches[2];
var constantSet = matches[1];
context = context.replace(require, getValue(constant, constantSet));
});
return context;
};
return function (css) {
css.walk(function (node) {
globalNode = node;
if (node.prop && node.prop.indexOf('~') > -1) {
getConstants(node.prop, node.value, node.source.input.from);
node.remove();
}
if (node.type === 'decl') {
node.value = strip(node.value);
}
if (node.type === 'atrule') {
node.params = strip(node.params);
}
});
};
});