index.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. 'use strict';
  2. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  3. const isStandardSyntaxSelector = require('../../utils/isStandardSyntaxSelector');
  4. const keywordSets = require('../../reference/keywordSets');
  5. const optionsMatches = require('../../utils/optionsMatches');
  6. const parseSelector = require('../../utils/parseSelector');
  7. const report = require('../../utils/report');
  8. const resolvedNestedSelector = require('postcss-resolve-nested-selector');
  9. const ruleMessages = require('../../utils/ruleMessages');
  10. const specificity = require('specificity');
  11. const validateOptions = require('../../utils/validateOptions');
  12. const { isRegExp, isString } = require('../../utils/validateTypes');
  13. const ruleName = 'selector-max-specificity';
  14. const messages = ruleMessages(ruleName, {
  15. expected: (selector, max) => `Expected "${selector}" to have a specificity no more than "${max}"`,
  16. });
  17. const meta = {
  18. url: 'https://stylelint.io/user-guide/rules/list/selector-max-specificity',
  19. };
  20. /** @typedef {import('specificity').SpecificityArray} SpecificityArray */
  21. /**
  22. * Return an array representation of zero specificity. We need a new array each time so that it can mutated.
  23. *
  24. * @returns {SpecificityArray}
  25. */
  26. const zeroSpecificity = () => [0, 0, 0, 0];
  27. /**
  28. * Calculate the sum of given array of specificity arrays.
  29. *
  30. * @param {SpecificityArray[]} specificities
  31. */
  32. const specificitySum = (specificities) => {
  33. const sum = zeroSpecificity();
  34. for (const specificityArray of specificities) {
  35. for (const [i, value] of specificityArray.entries()) {
  36. sum[i] += value;
  37. }
  38. }
  39. return sum;
  40. };
  41. /** @type {import('stylelint').Rule} */
  42. const rule = (primary, secondaryOptions) => {
  43. return (root, result) => {
  44. const validOptions = validateOptions(
  45. result,
  46. ruleName,
  47. {
  48. actual: primary,
  49. possible: [
  50. // Check that the max specificity is in the form "a,b,c"
  51. (spec) => isString(spec) && /^\d+,\d+,\d+$/.test(spec),
  52. ],
  53. },
  54. {
  55. actual: secondaryOptions,
  56. possible: {
  57. ignoreSelectors: [isString, isRegExp],
  58. },
  59. optional: true,
  60. },
  61. );
  62. if (!validOptions) {
  63. return;
  64. }
  65. /**
  66. * Calculate the specificity of a simple selector (type, attribute, class, ID, or pseudos's own value).
  67. *
  68. * @param {string} selector
  69. * @returns {SpecificityArray}
  70. */
  71. const simpleSpecificity = (selector) => {
  72. if (optionsMatches(secondaryOptions, 'ignoreSelectors', selector)) {
  73. return zeroSpecificity();
  74. }
  75. return specificity.calculate(selector)[0].specificityArray;
  76. };
  77. /**
  78. * Calculate the the specificity of the most specific direct child.
  79. *
  80. * @param {import('postcss-selector-parser').Container<unknown>} node
  81. * @returns {SpecificityArray}
  82. */
  83. const maxChildSpecificity = (node) =>
  84. node.reduce((maxSpec, child) => {
  85. const childSpecificity = nodeSpecificity(child); // eslint-disable-line no-use-before-define
  86. return specificity.compare(childSpecificity, maxSpec) === 1 ? childSpecificity : maxSpec;
  87. }, zeroSpecificity());
  88. /**
  89. * Calculate the specificity of a pseudo selector including own value and children.
  90. *
  91. * @param {import('postcss-selector-parser').Pseudo} node
  92. * @returns {SpecificityArray}
  93. */
  94. const pseudoSpecificity = (node) => {
  95. // `node.toString()` includes children which should be processed separately,
  96. // so use `node.value` instead
  97. const ownValue = node.value;
  98. const ownSpecificity =
  99. ownValue === ':not' || ownValue === ':matches'
  100. ? // :not and :matches don't add specificity themselves, but their children do
  101. zeroSpecificity()
  102. : simpleSpecificity(ownValue);
  103. return specificitySum([ownSpecificity, maxChildSpecificity(node)]);
  104. };
  105. /**
  106. * @param {import('postcss-selector-parser').Node} node
  107. * @returns {boolean}
  108. */
  109. const shouldSkipPseudoClassArgument = (node) => {
  110. // postcss-selector-parser includes the arguments to nth-child() functions
  111. // as "tags", so we need to ignore them ourselves.
  112. // The fake-tag's "parent" is actually a selector node, whose parent
  113. // should be the :nth-child pseudo node.
  114. const parentNode = node.parent && node.parent.parent;
  115. if (parentNode && parentNode.value) {
  116. const parentNodeValue = parentNode.value;
  117. const normalisedParentNode = parentNodeValue.toLowerCase().replace(/:+/, '');
  118. return (
  119. parentNode.type === 'pseudo' &&
  120. (keywordSets.aNPlusBNotationPseudoClasses.has(normalisedParentNode) ||
  121. keywordSets.linguisticPseudoClasses.has(normalisedParentNode))
  122. );
  123. }
  124. return false;
  125. };
  126. /**
  127. * Calculate the specificity of a node parsed by `postcss-selector-parser`.
  128. *
  129. * @param {import('postcss-selector-parser').Node} node
  130. * @returns {SpecificityArray}
  131. */
  132. const nodeSpecificity = (node) => {
  133. if (shouldSkipPseudoClassArgument(node)) {
  134. return zeroSpecificity();
  135. }
  136. switch (node.type) {
  137. case 'attribute':
  138. case 'class':
  139. case 'id':
  140. case 'tag':
  141. return simpleSpecificity(node.toString());
  142. case 'pseudo':
  143. return pseudoSpecificity(node);
  144. case 'selector':
  145. // Calculate the sum of all the direct children
  146. return specificitySum(node.map((n) => nodeSpecificity(n)));
  147. default:
  148. return zeroSpecificity();
  149. }
  150. };
  151. /** @type {[number, number, number]} */
  152. const primaryNumbers = primary
  153. .split(',')
  154. .map((/** @type {string} */ s) => Number.parseFloat(s));
  155. /** @type {SpecificityArray} */
  156. const maxSpecificityArray = [0, ...primaryNumbers];
  157. root.walkRules((ruleNode) => {
  158. if (!isStandardSyntaxRule(ruleNode)) {
  159. return;
  160. }
  161. // Using `.selectors` gets us each selector in the eventuality we have a comma separated set
  162. for (const selector of ruleNode.selectors) {
  163. for (const resolvedSelector of resolvedNestedSelector(selector, ruleNode)) {
  164. try {
  165. // Skip non-standard syntax selectors
  166. if (!isStandardSyntaxSelector(resolvedSelector)) {
  167. continue;
  168. }
  169. parseSelector(resolvedSelector, result, ruleNode, (selectorTree) => {
  170. // Check if the selector specificity exceeds the allowed maximum
  171. if (
  172. specificity.compare(maxChildSpecificity(selectorTree), maxSpecificityArray) === 1
  173. ) {
  174. report({
  175. ruleName,
  176. result,
  177. node: ruleNode,
  178. message: messages.expected(resolvedSelector, primary),
  179. word: selector,
  180. });
  181. }
  182. });
  183. } catch {
  184. result.warn('Cannot parse selector', {
  185. node: ruleNode,
  186. stylelintType: 'parseError',
  187. });
  188. }
  189. }
  190. }
  191. });
  192. };
  193. };
  194. rule.ruleName = ruleName;
  195. rule.messages = messages;
  196. rule.meta = meta;
  197. module.exports = rule;