index.js 2.4 KB

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