index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const report = require('../../utils/report');
  3. const ruleMessages = require('../../utils/ruleMessages');
  4. const validateOptions = require('../../utils/validateOptions');
  5. const { isNumber } = require('../../utils/validateTypes');
  6. const ruleName = 'selector-max-empty-lines';
  7. const messages = ruleMessages(ruleName, {
  8. expected: (max) => `Expected no more than ${max} empty ${max === 1 ? 'line' : 'lines'}`,
  9. });
  10. const meta = {
  11. url: 'https://stylelint.io/user-guide/rules/list/selector-max-empty-lines',
  12. };
  13. /** @type {import('stylelint').Rule} */
  14. const rule = (primary, _secondaryOptions, context) => {
  15. const maxAdjacentNewlines = primary + 1;
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, {
  18. actual: primary,
  19. possible: isNumber,
  20. });
  21. if (!validOptions) {
  22. return;
  23. }
  24. const violatedCRLFNewLinesRegex = new RegExp(`(?:\r\n){${maxAdjacentNewlines + 1},}`);
  25. const violatedLFNewLinesRegex = new RegExp(`\n{${maxAdjacentNewlines + 1},}`);
  26. const allowedLFNewLinesString = context.fix ? '\n'.repeat(maxAdjacentNewlines) : '';
  27. const allowedCRLFNewLinesString = context.fix ? '\r\n'.repeat(maxAdjacentNewlines) : '';
  28. root.walkRules((ruleNode) => {
  29. const selector = ruleNode.raws.selector ? ruleNode.raws.selector.raw : ruleNode.selector;
  30. if (context.fix) {
  31. const newSelectorString = selector
  32. .replace(new RegExp(violatedLFNewLinesRegex, 'gm'), allowedLFNewLinesString)
  33. .replace(new RegExp(violatedCRLFNewLinesRegex, 'gm'), allowedCRLFNewLinesString);
  34. if (ruleNode.raws.selector) {
  35. ruleNode.raws.selector.raw = newSelectorString;
  36. } else {
  37. ruleNode.selector = newSelectorString;
  38. }
  39. } else if (
  40. violatedLFNewLinesRegex.test(selector) ||
  41. violatedCRLFNewLinesRegex.test(selector)
  42. ) {
  43. report({
  44. message: messages.expected(primary),
  45. node: ruleNode,
  46. index: 0,
  47. result,
  48. ruleName,
  49. });
  50. }
  51. });
  52. };
  53. };
  54. rule.ruleName = ruleName;
  55. rule.messages = messages;
  56. rule.meta = meta;
  57. module.exports = rule;