index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. const isNonNegativeInteger = require('../../utils/isNonNegativeInteger');
  3. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  4. const parseSelector = require('../../utils/parseSelector');
  5. const report = require('../../utils/report');
  6. const resolvedNestedSelector = require('postcss-resolve-nested-selector');
  7. const ruleMessages = require('../../utils/ruleMessages');
  8. const validateOptions = require('../../utils/validateOptions');
  9. const ruleName = 'selector-max-combinators';
  10. const messages = ruleMessages(ruleName, {
  11. expected: (selector, max) =>
  12. `Expected "${selector}" to have no more than ${max} ${
  13. max === 1 ? 'combinator' : 'combinators'
  14. }`,
  15. });
  16. const meta = {
  17. url: 'https://stylelint.io/user-guide/rules/list/selector-max-combinators',
  18. };
  19. /** @type {import('stylelint').Rule} */
  20. const rule = (primary) => {
  21. return (root, result) => {
  22. const validOptions = validateOptions(result, ruleName, {
  23. actual: primary,
  24. possible: isNonNegativeInteger,
  25. });
  26. if (!validOptions) {
  27. return;
  28. }
  29. /**
  30. * @param {import('postcss-selector-parser').Container<unknown>} selectorNode
  31. * @param {import('postcss').Rule} ruleNode
  32. */
  33. function checkSelector(selectorNode, ruleNode) {
  34. const count = selectorNode.reduce((total, childNode) => {
  35. // Only traverse inside actual selectors
  36. if (childNode.type === 'selector') {
  37. checkSelector(childNode, ruleNode);
  38. }
  39. if (childNode.type === 'combinator') total += 1;
  40. return total;
  41. }, 0);
  42. if (selectorNode.type !== 'root' && selectorNode.type !== 'pseudo' && count > primary) {
  43. const selector = selectorNode.toString();
  44. report({
  45. ruleName,
  46. result,
  47. node: ruleNode,
  48. message: messages.expected(selector, primary),
  49. word: selector,
  50. });
  51. }
  52. }
  53. root.walkRules((ruleNode) => {
  54. if (!isStandardSyntaxRule(ruleNode)) {
  55. return;
  56. }
  57. for (const selector of ruleNode.selectors) {
  58. for (const resolvedSelector of resolvedNestedSelector(selector, ruleNode)) {
  59. parseSelector(resolvedSelector, result, ruleNode, (container) =>
  60. checkSelector(container, ruleNode),
  61. );
  62. }
  63. }
  64. });
  65. };
  66. };
  67. rule.ruleName = ruleName;
  68. rule.messages = messages;
  69. rule.meta = meta;
  70. module.exports = rule;