-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
56 lines (48 loc) · 1.32 KB
/
parser.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
var css = require("css");
var _ = require("lodash");
function getStyles(decl) {
var stylesObj = {};
decl.forEach(function(obj) {
stylesObj[obj.property] = obj.value;
});
return stylesObj;
}
function normalizeParsedStyles(selectors, block, media) {
block.selectors.forEach(function(selector) {
var pseudo = selector.split(":")[1];
selector = selector.split(":")[0];
if (!selectors[selector]) {
selectors[selector] = {};
}
if (pseudo) {
selectors[selector][":" + pseudo] = _.assign(
selectors[selector][":" + pseudo],
getStyles(block.declarations)
);
} else if (media) {
selectors[selector]["@media " + media] = _.assign(
selectors[selector][media],
getStyles(block.declarations)
);
} else {
selectors[selector] = _.assign(
selectors[selector],
getStyles(block.declarations)
);
}
});
}
module.exports = function(source) {
var parsedStyles = css.parse(source).stylesheet.rules;
var selectors = {};
parsedStyles.forEach(function(block) {
if (block.type == "rule") {
normalizeParsedStyles(selectors, block);
} else if (block.type == "media") {
block.rules.forEach(function(rules) {
normalizeParsedStyles(selectors, rules, block.media);
});
}
});
return selectors;
};