/
index.js
97 lines (84 loc) · 2.45 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
'use strict';
const _ = require('lodash');
const isLogicalCombination = require('../../utils/isLogicalCombination');
const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
const optionsMatches = require('../../utils/optionsMatches');
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-attribute';
const messages = ruleMessages(ruleName, {
expected: (selector, max) =>
`Expected "${selector}" to have no more than ${max} attribute ${
max === 1 ? 'selector' : 'selectors'
}`,
});
function rule(max, options) {
return (root, result) => {
const validOptions = validateOptions(
result,
ruleName,
{
actual: max,
possible: [
function(max) {
return typeof max === 'number' && max >= 0;
},
],
},
{
actual: options,
possible: {
ignoreAttributes: [_.isString, _.isRegExp],
},
optional: true,
},
);
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);
}
if (childNode.type !== 'attribute') {
// Not an attribute node -> ignore
return total;
}
if (optionsMatches(options, 'ignoreAttributes', childNode.attribute)) {
// it's an attribute that is supposed to be ignored
return total;
}
return (total += 1);
}, 0);
if (selectorNode.type !== 'root' && selectorNode.type !== 'pseudo' && count > max) {
report({
ruleName,
result,
node: ruleNode,
message: messages.expected(selectorNode, max),
word: selectorNode,
});
}
}
root.walkRules((ruleNode) => {
if (!isStandardSyntaxRule(ruleNode)) {
return;
}
ruleNode.selectors.forEach((selector) => {
resolvedNestedSelector(selector, ruleNode).forEach((resolvedSelector) => {
parseSelector(resolvedSelector, result, ruleNode, (container) =>
checkSelector(container, ruleNode),
);
});
});
});
};
}
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;