Skip to content

Commit b089f13

Browse files
committed
Fix adding empty lines between children rules if there are comments between them
1 parent 1991f1e commit b089f13

File tree

3 files changed

+87
-2
lines changed

3 files changed

+87
-2
lines changed

index.js

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,21 @@ function fetchAllCommentsAfterNode(comments, nextNode, node, currentInitialIndex
180180
return fetchAllCommentsAfterNode(comments.concat(nextNode), nextNode.next(), node, nextNode.initialIndex);
181181
}
182182

183+
function getApplicableNode(node) {
184+
// find if there any rules before, and skip the comments
185+
var prevNode = node.prev();
186+
187+
if (prevNode.type === 'rule') {
188+
return node;
189+
}
190+
191+
if (prevNode.type === 'comment') {
192+
return getApplicableNode(prevNode);
193+
}
194+
195+
return false;
196+
}
197+
183198
module.exports = postcss.plugin('postcss-sorting', function (opts) {
184199
// Verify options and use defaults if not specified
185200
opts = verifyOptions(opts);
@@ -258,8 +273,13 @@ module.exports = postcss.plugin('postcss-sorting', function (opts) {
258273
}
259274

260275
// Insert empty lines between children classes
261-
if (node.type === 'rule' && prevNode.type === 'rule' && linesBetweenChildrenRules > 0) {
262-
node.raws.before = createLineBreaks(linesBetweenChildrenRules) + node.raws.before;
276+
if (node.type === 'rule' && linesBetweenChildrenRules > 0) {
277+
// between child rules can be comments, so empty lines should be added to first comment between rules, rather than to rule
278+
var applicableNode = getApplicableNode(node);
279+
280+
if (applicableNode) {
281+
applicableNode.raws.before = createLineBreaks(linesBetweenChildrenRules) + applicableNode.raws.before;
282+
}
263283
}
264284
}
265285
});

test/fixtures/lines-between-children.css

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,36 @@
2727
flex: 0 0 auto;
2828
}
2929
}
30+
31+
.block {
32+
display: none;
33+
34+
div {}
35+
/* comment 1 */
36+
section {}
37+
38+
39+
40+
41+
article {}
42+
43+
44+
45+
/* comment 2 */
46+
.child {}
47+
}
48+
49+
.block {
50+
display: none;
51+
52+
div {}
53+
/* comment 1 */
54+
section {}
55+
56+
57+
58+
59+
/* comment 2 */
60+
/* comment 3 */
61+
.child {}
62+
}

test/fixtures/lines-between-children.expected.css

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,35 @@
2929
flex: 0 0 auto;
3030
}
3131
}
32+
33+
.block {
34+
display: none;
35+
36+
div {}
37+
38+
39+
/* comment 1 */
40+
section {}
41+
42+
43+
article {}
44+
45+
46+
/* comment 2 */
47+
.child {}
48+
}
49+
50+
.block {
51+
display: none;
52+
53+
div {}
54+
55+
56+
/* comment 1 */
57+
section {}
58+
59+
60+
/* comment 2 */
61+
/* comment 3 */
62+
.child {}
63+
}

0 commit comments

Comments
 (0)