UNPKG

stylelint

Version:

A mighty CSS linter that helps you avoid errors and enforce conventions.

95 lines (79 loc) 2.53 kB
import getRuleSelector from '../../utils/getRuleSelector.mjs'; import getStrippedSelectorSource from '../../utils/getStrippedSelectorSource.mjs'; import isNonNegativeInteger from '../../utils/isNonNegativeInteger.mjs'; import isStandardSyntaxRule from '../../utils/isStandardSyntaxRule.mjs'; import { isString } from '../../utils/validateTypes.mjs'; import optionsMatches from '../../utils/optionsMatches.mjs'; import parseSelector from '../../utils/parseSelector.mjs'; import report from '../../utils/report.mjs'; import ruleMessages from '../../utils/ruleMessages.mjs'; import validateOptions from '../../utils/validateOptions.mjs'; const ruleName = 'selector-max-universal'; const messages = ruleMessages(ruleName, { expected: (selector, max) => `Expected "${selector}" to have no more than ${max} universal ${ max === 1 ? 'selector' : 'selectors' }`, }); const meta = { url: 'https://stylelint.io/user-guide/rules/selector-max-universal', }; /** @type {import('stylelint').CoreRules[ruleName]} */ const rule = (primary, secondaryOptions) => { return (root, result) => { const validOptions = validateOptions( result, ruleName, { actual: primary, possible: isNonNegativeInteger, }, { actual: secondaryOptions, possible: { ignoreAfterCombinators: [isString], }, optional: true, }, ); if (!validOptions) { return; } /** * @param {import('postcss-selector-parser').Selector} selectorNode * @param {import('postcss').Rule} ruleNode */ function checkSelector(selectorNode, ruleNode) { let count = 0; selectorNode.walkUniversals((childNode) => { const prevChildNode = childNode.prev(); const prevChildNodeValue = prevChildNode && prevChildNode.value; if (optionsMatches(secondaryOptions, 'ignoreAfterCombinators', prevChildNodeValue)) return; count += 1; }); if (count > primary) { const { index, endIndex, selector: selectorStr } = getStrippedSelectorSource(selectorNode); report({ ruleName, result, node: ruleNode, message: messages.expected, messageArgs: [selectorStr, primary], index, endIndex, }); } } root.walkRules((ruleNode) => { if (!isStandardSyntaxRule(ruleNode)) return; const selectors = parseSelector(getRuleSelector(ruleNode), result, ruleNode); selectors?.each((selector) => { checkSelector(selector, ruleNode); }); }); }; }; rule.ruleName = ruleName; rule.messages = messages; rule.meta = meta; export default rule;