-
-
Notifications
You must be signed in to change notification settings - Fork 929
/
index.js
91 lines (78 loc) · 2.64 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
"use strict";
const isLogicalCombination = require("../../utils/isLogicalCombination");
const isStandardSyntaxRule = require("../../utils/isStandardSyntaxRule");
const isStandardSyntaxSelector = require("../../utils/isStandardSyntaxSelector");
const parseSelector = require("../../utils/parseSelector");
const report = require("../../utils/report");
const resolvedNestedSelector = require("postcss-resolve-nested-selector");
const ruleMessages = require("../../utils/ruleMessages");
const validateOptions = require("../../utils/validateOptions");
const ruleName = "selector-max-compound-selectors";
const messages = ruleMessages(ruleName, {
expected: (selector, max) =>
`Expected "${selector}" to have no more than ${max} compound ${
max === 1 ? "selector" : "selectors"
}`
});
const rule = function(max) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: max,
possible: [
function(max) {
return typeof max === "number" && max > 0;
}
]
});
if (!validOptions) {
return;
}
// Finds actual selectors in selectorNode object and checks them
function checkSelector(selectorNode, rule) {
let compoundCount = 1;
selectorNode.each(childNode => {
// Only traverse inside actual selectors and logical combinations
if (childNode.type === "selector" || isLogicalCombination(childNode)) {
checkSelector(childNode, rule);
}
// Compound selectors are separated by combinators, so increase count when meeting one
if (childNode.type === "combinator") {
compoundCount++;
}
});
if (
selectorNode.type !== "root" &&
selectorNode.type !== "pseudo" &&
compoundCount > max
) {
report({
ruleName,
result,
node: rule,
message: messages.expected(selectorNode, max),
word: selectorNode
});
}
}
root.walkRules(rule => {
if (!isStandardSyntaxRule(rule)) {
return;
}
if (!isStandardSyntaxSelector(rule.selector)) {
return;
}
// Using `rule.selectors` gets us each selector if there is a comma separated set
rule.selectors.forEach(selector => {
resolvedNestedSelector(selector, rule).forEach(resolvedSelector => {
// Process each resolved selector with `checkSelector` via postcss-selector-parser
parseSelector(resolvedSelector, result, rule, s =>
checkSelector(s, rule)
);
});
});
});
};
};
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;