/
index.js
103 lines (85 loc) · 2.3 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
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';
const beforeBlockString = require('../../utils/beforeBlockString');
const hasBlock = require('../../utils/hasBlock');
const optionsMatches = require('../../utils/optionsMatches');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const { isStylelintCommand } = require('../../utils/stylelintCommand');
const { isComment } = require('../../utils/typeGuards');
const validateOptions = require('../../utils/validateOptions');
const { isBoolean } = require('../../utils/validateTypes');
const ruleName = 'block-no-empty';
const messages = ruleMessages(ruleName, {
rejected: 'Unexpected empty block',
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/list/block-no-empty',
};
/** @type {import('stylelint').Rule} */
const rule = (primary, secondaryOptions) => {
return (root, result) => {
const validOptions = validateOptions(
result,
ruleName,
{
actual: primary,
possible: isBoolean,
},
{
actual: secondaryOptions,
possible: {
ignore: ['comments'],
},
optional: true,
},
);
if (!validOptions) {
return;
}
const ignoreComments = optionsMatches(secondaryOptions, 'ignore', 'comments');
// Check both kinds of statements: rules and at-rules
root.walkRules(check);
root.walkAtRules(check);
/** @typedef {import('postcss').Rule | import('postcss').AtRule} Statement */
/**
* @param {Statement} statement
*/
function check(statement) {
if (!hasBlock(statement)) {
return;
}
if (hasNotableChildren(statement)) {
return;
}
let index = beforeBlockString(statement, { noRawBefore: true }).length;
// For empty blocks when using SugarSS parser
if (statement.raws.between === undefined) {
index--;
}
report({
message: messages.rejected,
node: statement,
start: statement.positionBy({ index }),
result,
ruleName,
});
}
/**
* @param {Statement} statement
* @returns {boolean}
*/
function hasNotableChildren(statement) {
return statement.nodes.some((child) => {
if (isComment(child)) {
if (ignoreComments) return false;
if (isStylelintCommand(child)) return false;
}
return true;
});
}
};
};
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
module.exports = rule;