1 | 'use strict';
|
2 |
|
3 | const isLogicalCombination = require('../../utils/isLogicalCombination');
|
4 | const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
|
5 | const parseSelector = require('../../utils/parseSelector');
|
6 | const report = require('../../utils/report');
|
7 | const resolvedNestedSelector = require('postcss-resolve-nested-selector');
|
8 | const ruleMessages = require('../../utils/ruleMessages');
|
9 | const validateOptions = require('../../utils/validateOptions');
|
10 |
|
11 | const ruleName = 'selector-max-compound-selectors';
|
12 |
|
13 | const messages = ruleMessages(ruleName, {
|
14 | expected: (selector, max) =>
|
15 | `Expected "${selector}" to have no more than ${max} compound ${
|
16 | max === 1 ? 'selector' : 'selectors'
|
17 | }`,
|
18 | });
|
19 |
|
20 | function rule(max) {
|
21 | return (root, result) => {
|
22 | const validOptions = validateOptions(result, ruleName, {
|
23 | actual: max,
|
24 | possible: [
|
25 | function (max) {
|
26 | return typeof max === 'number' && max > 0;
|
27 | },
|
28 | ],
|
29 | });
|
30 |
|
31 | if (!validOptions) {
|
32 | return;
|
33 | }
|
34 |
|
35 |
|
36 | function checkSelector(selectorNode, rule) {
|
37 | let compoundCount = 1;
|
38 |
|
39 | selectorNode.each((childNode) => {
|
40 |
|
41 | if (childNode.type === 'selector' || isLogicalCombination(childNode)) {
|
42 | checkSelector(childNode, rule);
|
43 | }
|
44 |
|
45 |
|
46 | if (childNode.type === 'combinator') {
|
47 | compoundCount++;
|
48 | }
|
49 | });
|
50 |
|
51 | if (selectorNode.type !== 'root' && selectorNode.type !== 'pseudo' && compoundCount > max) {
|
52 | report({
|
53 | ruleName,
|
54 | result,
|
55 | node: rule,
|
56 | message: messages.expected(selectorNode, max),
|
57 | word: selectorNode,
|
58 | });
|
59 | }
|
60 | }
|
61 |
|
62 | root.walkRules((rule) => {
|
63 | if (!isStandardSyntaxRule(rule)) {
|
64 | return;
|
65 | }
|
66 |
|
67 |
|
68 | rule.selectors.forEach((selector) => {
|
69 | resolvedNestedSelector(selector, rule).forEach((resolvedSelector) => {
|
70 |
|
71 | parseSelector(resolvedSelector, result, rule, (s) => checkSelector(s, rule));
|
72 | });
|
73 | });
|
74 | });
|
75 | };
|
76 | }
|
77 |
|
78 | rule.ruleName = ruleName;
|
79 | rule.messages = messages;
|
80 | module.exports = rule;
|