forked from postcss/postcss-nested
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (85 loc) · 2.65 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
var postcss = require('postcss');
function selectors(parent, node) {
var result = [];
parent.selectors.forEach(function (i) {
node.selectors.forEach(function (j) {
if ( j.indexOf('&') === -1 ) {
result.push(i + ' ' + j);
} else {
result.push(j.replace(/&/g, i));
}
});
});
return result;
}
function pickComment(comment, after) {
if ( comment && comment.type === 'comment' ) {
return comment.moveAfter(after);
} else {
return after;
}
}
function atruleChilds(rule, atrule) {
var children = [];
atrule.each(function (child) {
if ( child.type === 'comment' ) {
children.push( child );
} if ( child.type === 'decl' ) {
children.push( child );
} else if ( child.type === 'rule' ) {
child.selectors = selectors(rule, child);
} else if ( child.type === 'atrule') {
if (/include/.test(child.name) && !child.nodes) {
children.push(child);
} else {
atruleChilds(rule, child);
}
}
});
if ( children.length ) {
var clone = rule.clone({ nodes: [] });
for ( var i = 0; i < children.length; i++ ) children[i].moveTo(clone);
atrule.prepend(clone);
}
}
function processRule(rule, bubble) {
var unwrapped = false;
var after = rule;
rule.each(function (child) {
if ( child.type === 'rule' ) {
unwrapped = true;
child.selectors = selectors(rule, child);
after = pickComment(child.prev(), after);
after = child.moveAfter(after);
} else if ( child.type === 'atrule' ) {
if ( bubble.indexOf(child.name) !== -1 ) {
unwrapped = true;
atruleChilds(rule, child);
after = pickComment(child.prev(), after);
after = child.moveAfter(after);
}
}
});
if ( unwrapped ) {
rule.raws.semicolon = true;
if ( rule.nodes.length === 0 ) rule.remove();
}
}
module.exports = postcss.plugin('postcss-nested', function (opts) {
var bubble = ['media', 'supports', 'document'];
if ( opts && opts.bubble ) {
bubble = bubble.concat(opts.bubble.map(function (i) {
return i.replace(/^@/, '');
}));
}
var process = function (node) {
node.each(function (child) {
if ( child.type === 'rule' ) {
processRule(child, bubble);
} else if ( child.type === 'atrule' ) {
process(child);
}
});
};
return process;
});