-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (55 loc) · 1.76 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
var css = require('css'),
CLASS_REGEX = /\.[a-zA-Z](?:[0-9A-Za-z_-])*/g;
function flatten(prev, cur) {
prev.push.apply(prev, cur);
return prev;
}
function symdiffCSS(cssString) {
var ast;
try {
ast = css.parse(cssString);
} catch(e) {
return [];
}
if (!ast.stylesheet) {
return [];
}
return ast
.stylesheet
.rules
.map(function(rule) {
var selectors;
if (rule.type === 'rule') {
selectors = rule.selectors;
} else if (rule.type === 'media') {
selectors = rule
.rules
.map(function(r) {
return r.selectors;
})
.reduce(flatten, []);
} else {
return [];
}
return selectors
.map(function(selector) {
var matches = selector.match(CLASS_REGEX);
if (!matches) {
return;
}
return matches
.map(function(match) {
// remove leading dot
return match.substring(1);
});
});
})
// now flatten twice
.reduce(flatten, [])
.reduce(flatten, [])
// and remove duplicates
.filter(function(c, i, all) {
return all.lastIndexOf(c) === i;
});
}
module.exports = symdiffCSS;