123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- 'use strict';
- const isNonNegativeInteger = require('../../utils/isNonNegativeInteger');
- const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
- 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-combinators';
- const messages = ruleMessages(ruleName, {
- expected: (selector, max) =>
- `Expected "${selector}" to have no more than ${max} ${
- max === 1 ? 'combinator' : 'combinators'
- }`,
- });
- const meta = {
- url: 'https://stylelint.io/user-guide/rules/list/selector-max-combinators',
- };
- /** @type {import('stylelint').Rule} */
- const rule = (primary) => {
- return (root, result) => {
- const validOptions = validateOptions(result, ruleName, {
- actual: primary,
- possible: isNonNegativeInteger,
- });
- if (!validOptions) {
- return;
- }
- /**
- * @param {import('postcss-selector-parser').Container<unknown>} selectorNode
- * @param {import('postcss').Rule} ruleNode
- */
- function checkSelector(selectorNode, ruleNode) {
- const count = selectorNode.reduce((total, childNode) => {
- // Only traverse inside actual selectors
- if (childNode.type === 'selector') {
- checkSelector(childNode, ruleNode);
- }
- if (childNode.type === 'combinator') total += 1;
- return total;
- }, 0);
- if (selectorNode.type !== 'root' && selectorNode.type !== 'pseudo' && count > primary) {
- const selector = selectorNode.toString();
- report({
- ruleName,
- result,
- node: ruleNode,
- message: messages.expected(selector, primary),
- word: selector,
- });
- }
- }
- root.walkRules((ruleNode) => {
- if (!isStandardSyntaxRule(ruleNode)) {
- return;
- }
- for (const selector of ruleNode.selectors) {
- for (const resolvedSelector of resolvedNestedSelector(selector, ruleNode)) {
- parseSelector(resolvedSelector, result, ruleNode, (container) =>
- checkSelector(container, ruleNode),
- );
- }
- }
- });
- };
- };
- rule.ruleName = ruleName;
- rule.messages = messages;
- rule.meta = meta;
- module.exports = rule;
|