index.js 2.0 KB

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