index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. fixable: true,
  15. };
  16. /** @type {import('stylelint').Rule} */
  17. const rule = (primary, _secondaryOptions, context) => {
  18. const maxAdjacentNewlines = primary + 1;
  19. return (root, result) => {
  20. const validOptions = validateOptions(result, ruleName, {
  21. actual: primary,
  22. possible: isNumber,
  23. });
  24. if (!validOptions) {
  25. return;
  26. }
  27. const violatedCRLFNewLinesRegex = new RegExp(`(?:\r\n){${maxAdjacentNewlines + 1},}`);
  28. const violatedLFNewLinesRegex = new RegExp(`\n{${maxAdjacentNewlines + 1},}`);
  29. const allowedLFNewLinesString = context.fix ? '\n'.repeat(maxAdjacentNewlines) : '';
  30. const allowedCRLFNewLinesString = context.fix ? '\r\n'.repeat(maxAdjacentNewlines) : '';
  31. root.walkDecls((decl) => {
  32. const value = getDeclarationValue(decl);
  33. if (context.fix) {
  34. const newValueString = value
  35. .replace(new RegExp(violatedLFNewLinesRegex, 'gm'), allowedLFNewLinesString)
  36. .replace(new RegExp(violatedCRLFNewLinesRegex, 'gm'), allowedCRLFNewLinesString);
  37. setDeclarationValue(decl, newValueString);
  38. } else if (violatedLFNewLinesRegex.test(value) || violatedCRLFNewLinesRegex.test(value)) {
  39. report({
  40. message: messages.expected(primary),
  41. node: decl,
  42. index: 0,
  43. result,
  44. ruleName,
  45. });
  46. }
  47. });
  48. };
  49. };
  50. rule.ruleName = ruleName;
  51. rule.messages = messages;
  52. rule.meta = meta;
  53. module.exports = rule;