index.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. 'use strict';
  2. const resolvedNestedSelector = require('postcss-resolve-nested-selector');
  3. const { selectorSpecificity: calculate, compare } = require('@csstools/selector-specificity');
  4. const findAtRuleContext = require('../../utils/findAtRuleContext');
  5. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  6. const isStandardSyntaxSelector = require('../../utils/isStandardSyntaxSelector');
  7. const { pseudoElements } = require('../../reference/selectors');
  8. const nodeContextLookup = require('../../utils/nodeContextLookup');
  9. const optionsMatches = require('../../utils/optionsMatches');
  10. const parseSelector = require('../../utils/parseSelector');
  11. const report = require('../../utils/report');
  12. const ruleMessages = require('../../utils/ruleMessages');
  13. const validateOptions = require('../../utils/validateOptions');
  14. const { assert } = require('../../utils/validateTypes');
  15. const ruleName = 'no-descending-specificity';
  16. const messages = ruleMessages(ruleName, {
  17. rejected: (b, a) => `Expected selector "${b}" to come before selector "${a}"`,
  18. });
  19. const meta = {
  20. url: 'https://stylelint.io/user-guide/rules/no-descending-specificity',
  21. };
  22. /** @typedef {{ selector: string, specificity: import('@csstools/selector-specificity').Specificity }} Entry */
  23. /** @type {import('stylelint').Rule} */
  24. const rule = (primary, secondaryOptions) => {
  25. return (root, result) => {
  26. const validOptions = validateOptions(
  27. result,
  28. ruleName,
  29. {
  30. actual: primary,
  31. },
  32. {
  33. optional: true,
  34. actual: secondaryOptions,
  35. possible: {
  36. ignore: ['selectors-within-list'],
  37. },
  38. },
  39. );
  40. if (!validOptions) {
  41. return;
  42. }
  43. const ignoreSelectorsWithinList = optionsMatches(
  44. secondaryOptions,
  45. 'ignore',
  46. 'selectors-within-list',
  47. );
  48. const selectorContextLookup = nodeContextLookup();
  49. root.walkRules((ruleNode) => {
  50. // Ignore nested property `foo: {};`
  51. if (!isStandardSyntaxRule(ruleNode)) {
  52. return;
  53. }
  54. // Ignores selectors within list of selectors
  55. if (ignoreSelectorsWithinList && ruleNode.selectors.length > 1) {
  56. return;
  57. }
  58. /** @type {Map<string, Entry[]>} */
  59. const comparisonContext = selectorContextLookup.getContext(
  60. ruleNode,
  61. findAtRuleContext(ruleNode),
  62. );
  63. for (const selector of ruleNode.selectors) {
  64. const trimSelector = selector.trim();
  65. // Ignore `.selector, { }`
  66. if (trimSelector === '') {
  67. continue;
  68. }
  69. // Resolve any nested selectors before checking
  70. for (const resolvedSelector of resolvedNestedSelector(selector, ruleNode)) {
  71. parseSelector(resolvedSelector, result, ruleNode, (s) => {
  72. if (!isStandardSyntaxSelector(resolvedSelector)) {
  73. return;
  74. }
  75. checkSelector(s, ruleNode, comparisonContext);
  76. });
  77. }
  78. }
  79. });
  80. /**
  81. * @param {import('postcss-selector-parser').Root} selectorNode
  82. * @param {import('postcss').Rule} ruleNode
  83. * @param {Map<string, Entry[]>} comparisonContext
  84. */
  85. function checkSelector(selectorNode, ruleNode, comparisonContext) {
  86. const selector = selectorNode.toString();
  87. const referenceSelector = lastCompoundSelectorWithoutPseudoClasses(selectorNode);
  88. if (referenceSelector === undefined) return;
  89. const selectorSpecificity = calculate(selectorNode);
  90. const entry = { selector, specificity: selectorSpecificity };
  91. const priorComparableSelectors = comparisonContext.get(referenceSelector);
  92. if (priorComparableSelectors === undefined) {
  93. comparisonContext.set(referenceSelector, [entry]);
  94. return;
  95. }
  96. for (const priorEntry of priorComparableSelectors) {
  97. if (compare(selectorSpecificity, priorEntry.specificity) < 0) {
  98. report({
  99. ruleName,
  100. result,
  101. node: ruleNode,
  102. message: messages.rejected(selector, priorEntry.selector),
  103. word: selector,
  104. });
  105. }
  106. }
  107. priorComparableSelectors.push(entry);
  108. }
  109. };
  110. };
  111. /**
  112. * @param {import('postcss-selector-parser').Root} selectorNode
  113. * @returns {string | undefined}
  114. */
  115. function lastCompoundSelectorWithoutPseudoClasses(selectorNode) {
  116. const firstChild = selectorNode.nodes[0];
  117. assert(firstChild);
  118. const nodesByCombinator = firstChild.split((node) => node.type === 'combinator');
  119. const nodesAfterLastCombinator = nodesByCombinator[nodesByCombinator.length - 1];
  120. assert(nodesAfterLastCombinator);
  121. const nodesWithoutPseudoClasses = nodesAfterLastCombinator.filter((node) => {
  122. return (
  123. node.type !== 'pseudo' ||
  124. node.value.startsWith('::') ||
  125. pseudoElements.has(node.value.replace(/:/g, ''))
  126. );
  127. });
  128. if (nodesWithoutPseudoClasses.length === 0) return undefined;
  129. return nodesWithoutPseudoClasses.join('');
  130. }
  131. rule.ruleName = ruleName;
  132. rule.messages = messages;
  133. rule.meta = meta;
  134. module.exports = rule;