index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  3. const parseSelector = require('../../utils/parseSelector');
  4. const report = require('../../utils/report');
  5. const ruleMessages = require('../../utils/ruleMessages');
  6. const validateOptions = require('../../utils/validateOptions');
  7. const ruleName = 'selector-descendant-combinator-no-non-space';
  8. const messages = ruleMessages(ruleName, {
  9. rejected: (nonSpaceCharacter) => `Unexpected "${nonSpaceCharacter}"`,
  10. });
  11. const meta = {
  12. url: 'https://stylelint.io/user-guide/rules/list/selector-descendant-combinator-no-non-space',
  13. };
  14. /** @type {import('stylelint').Rule} */
  15. const rule = (primary, _secondaryOptions, context) => {
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, {
  18. actual: primary,
  19. });
  20. if (!validOptions) {
  21. return;
  22. }
  23. root.walkRules((ruleNode) => {
  24. if (!isStandardSyntaxRule(ruleNode)) {
  25. return;
  26. }
  27. let hasFixed = false;
  28. const selector = ruleNode.raws.selector ? ruleNode.raws.selector.raw : ruleNode.selector;
  29. // Return early for selectors containing comments
  30. // TODO: renable when parser and stylelint are compatible
  31. if (selector.includes('/*')) return;
  32. const fixedSelector = parseSelector(selector, result, ruleNode, (fullSelector) => {
  33. fullSelector.walkCombinators((combinatorNode) => {
  34. if (combinatorNode.value !== ' ') {
  35. return;
  36. }
  37. const value = combinatorNode.toString();
  38. if (
  39. value.includes(' ') ||
  40. value.includes('\t') ||
  41. value.includes('\n') ||
  42. value.includes('\r')
  43. ) {
  44. if (context.fix && /^\s+$/.test(value)) {
  45. hasFixed = true;
  46. if (!combinatorNode.raws) combinatorNode.raws = {};
  47. combinatorNode.raws.value = ' ';
  48. combinatorNode.rawSpaceBefore = combinatorNode.rawSpaceBefore.replace(/^\s+/, '');
  49. combinatorNode.rawSpaceAfter = combinatorNode.rawSpaceAfter.replace(/\s+$/, '');
  50. return;
  51. }
  52. report({
  53. result,
  54. ruleName,
  55. message: messages.rejected(value),
  56. node: ruleNode,
  57. index: combinatorNode.sourceIndex,
  58. });
  59. }
  60. });
  61. });
  62. if (hasFixed && fixedSelector) {
  63. if (!ruleNode.raws.selector) {
  64. ruleNode.selector = fixedSelector;
  65. } else {
  66. ruleNode.raws.selector.raw = fixedSelector;
  67. }
  68. }
  69. });
  70. };
  71. };
  72. rule.ruleName = ruleName;
  73. rule.messages = messages;
  74. rule.meta = meta;
  75. module.exports = rule;