1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const isLogicalCombination = require('../../utils/isLogicalCombination');
|
6 | const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
|
7 | const parseSelector = require('../../utils/parseSelector');
|
8 | const report = require('../../utils/report');
|
9 | const resolvedNestedSelector = require('postcss-resolve-nested-selector');
|
10 | const ruleMessages = require('../../utils/ruleMessages');
|
11 | const validateOptions = require('../../utils/validateOptions');
|
12 |
|
13 | const ruleName = 'selector-max-id';
|
14 |
|
15 | const messages = ruleMessages(ruleName, {
|
16 | expected: (selector, max) =>
|
17 | `Expected "${selector}" to have no more than ${max} ID ${max === 1 ? 'selector' : 'selectors'}`,
|
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 | function checkSelector(selectorNode, ruleNode) {
|
36 | const count = selectorNode.reduce((total, childNode) => {
|
37 |
|
38 | if (childNode.type === 'selector' || isLogicalCombination(childNode)) {
|
39 | checkSelector(childNode, ruleNode);
|
40 | }
|
41 |
|
42 | return (total += childNode.type === 'id' ? 1 : 0);
|
43 | }, 0);
|
44 |
|
45 | if (selectorNode.type !== 'root' && selectorNode.type !== 'pseudo' && count > max) {
|
46 | report({
|
47 | ruleName,
|
48 | result,
|
49 | node: ruleNode,
|
50 | message: messages.expected(selectorNode, max),
|
51 | word: selectorNode,
|
52 | });
|
53 | }
|
54 | }
|
55 |
|
56 | root.walkRules((ruleNode) => {
|
57 | if (!isStandardSyntaxRule(ruleNode)) {
|
58 | return;
|
59 | }
|
60 |
|
61 | ruleNode.selectors.forEach((selector) => {
|
62 | resolvedNestedSelector(selector, ruleNode).forEach((resolvedSelector) => {
|
63 | parseSelector(resolvedSelector, result, ruleNode, (container) =>
|
64 | checkSelector(container, ruleNode),
|
65 | );
|
66 | });
|
67 | });
|
68 | });
|
69 | };
|
70 | }
|
71 |
|
72 | rule.ruleName = ruleName;
|
73 | rule.messages = messages;
|
74 | module.exports = rule;
|