index.cjs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // NOTICE: This file is generated by Rollup. To modify it,
  2. // please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
  3. 'use strict';
  4. const selectorParser = require('postcss-selector-parser');
  5. const flattenNestedSelectorsForRule = require('../../utils/flattenNestedSelectorsForRule.cjs');
  6. const getStrippedSelectorSource = require('../../utils/getStrippedSelectorSource.cjs');
  7. const isNonNegativeInteger = require('../../utils/isNonNegativeInteger.cjs');
  8. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule.cjs');
  9. const report = require('../../utils/report.cjs');
  10. const ruleMessages = require('../../utils/ruleMessages.cjs');
  11. const validateOptions = require('../../utils/validateOptions.cjs');
  12. const { isSelector } = selectorParser;
  13. const ruleName = 'selector-max-combinators';
  14. const messages = ruleMessages(ruleName, {
  15. expected: (selector, max) =>
  16. `Expected "${selector}" to have no more than ${max} ${
  17. max === 1 ? 'combinator' : 'combinators'
  18. }`,
  19. });
  20. const meta = {
  21. url: 'https://stylelint.io/user-guide/rules/selector-max-combinators',
  22. };
  23. /** @type {import('stylelint').CoreRules[ruleName]} */
  24. const rule = (primary) => {
  25. return (root, result) => {
  26. const validOptions = validateOptions(result, ruleName, {
  27. actual: primary,
  28. possible: isNonNegativeInteger,
  29. });
  30. if (!validOptions) {
  31. return;
  32. }
  33. /**
  34. * @param {import('postcss-selector-parser').Selector} resolvedSelectorNode
  35. * @param {import('postcss-selector-parser').Selector} selectorNode
  36. * @param {import('postcss').Rule} ruleNode
  37. */
  38. function checkSelector(resolvedSelectorNode, selectorNode, ruleNode) {
  39. const count = resolvedSelectorNode.reduce((total, childNode) => {
  40. if (childNode.type === 'combinator') total += 1;
  41. return total;
  42. }, 0);
  43. if (count > primary) {
  44. const { index, endIndex, selector: selectorStr } = getStrippedSelectorSource(selectorNode);
  45. report({
  46. ruleName,
  47. result,
  48. node: ruleNode,
  49. message: messages.expected,
  50. messageArgs: [selectorStr, primary],
  51. index,
  52. endIndex,
  53. });
  54. }
  55. }
  56. root.walkRules((ruleNode) => {
  57. if (!isStandardSyntaxRule(ruleNode)) return;
  58. flattenNestedSelectorsForRule(ruleNode, result).forEach(({ selector, resolvedSelectors }) => {
  59. resolvedSelectors.walk((childSelector) => {
  60. if (!isSelector(childSelector)) return;
  61. checkSelector(childSelector, selector, ruleNode);
  62. });
  63. });
  64. });
  65. };
  66. };
  67. rule.ruleName = ruleName;
  68. rule.messages = messages;
  69. rule.meta = meta;
  70. module.exports = rule;