forked from stylelint/stylelint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (81 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
92
93
94
95
"use strict";
const isLogicalCombination = require("../../utils/isLogicalCombination");
const isStandardSyntaxRule = require("../../utils/isStandardSyntaxRule");
const isStandardSyntaxSelector = require("../../utils/isStandardSyntaxSelector");
const keywordSets = require("../../reference/keywordSets");
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-pseudo-class";
const messages = ruleMessages(ruleName, {
expected: (selector, max) =>
`Expected "${selector}" to have no more than ${max} pseudo-${
max === 1 ? "class" : "classes"
}`
});
function rule(max) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: max,
possible: [
function(max) {
return typeof max === "number" && max >= 0;
}
]
});
if (!validOptions) {
return;
}
function checkSelector(selectorNode, ruleNode) {
const count = selectorNode.reduce((total, childNode) => {
// Only traverse inside actual selectors and logical combinations
if (childNode.type === "selector" || isLogicalCombination(childNode)) {
checkSelector(childNode, ruleNode);
}
// Exclude pseudo elements from the count
if (
childNode.type === "pseudo" &&
(childNode.value.indexOf("::") !== -1 ||
keywordSets.levelOneAndTwoPseudoElements.has(
childNode.value.toLowerCase().slice(1)
))
) {
return total;
}
if (childNode.type === "pseudo") {
return (total += 1);
}
return total;
}, 0);
if (count > max) {
report({
ruleName,
result,
node: ruleNode,
message: messages.expected(selectorNode, max),
word: selectorNode
});
}
}
root.walkRules(ruleNode => {
if (!isStandardSyntaxRule(ruleNode)) {
return;
}
if (!isStandardSyntaxSelector(ruleNode.selector)) {
return;
}
ruleNode.selectors.forEach(selector => {
resolvedNestedSelector(selector, ruleNode).forEach(resolvedSelector => {
parseSelector(resolvedSelector, result, rule, selectorTree => {
checkSelector(selectorTree, ruleNode);
});
});
});
});
};
}
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;