index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // @ts-nocheck
  2. 'use strict';
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const ruleMessages = require('../../utils/ruleMessages');
  5. const validateOptions = require('../../utils/validateOptions');
  6. const valueListCommaWhitespaceChecker = require('../valueListCommaWhitespaceChecker');
  7. const whitespaceChecker = require('../../utils/whitespaceChecker');
  8. const ruleName = 'value-list-comma-space-after';
  9. const messages = ruleMessages(ruleName, {
  10. expectedAfter: () => 'Expected single space after ","',
  11. rejectedAfter: () => 'Unexpected whitespace after ","',
  12. expectedAfterSingleLine: () => 'Expected single space after "," in a single-line list',
  13. rejectedAfterSingleLine: () => 'Unexpected whitespace after "," in a single-line list',
  14. });
  15. function rule(expectation, options, context) {
  16. const checker = whitespaceChecker('space', expectation, messages);
  17. return (root, result) => {
  18. const validOptions = validateOptions(result, ruleName, {
  19. actual: expectation,
  20. possible: ['always', 'never', 'always-single-line', 'never-single-line'],
  21. });
  22. if (!validOptions) {
  23. return;
  24. }
  25. let fixData;
  26. valueListCommaWhitespaceChecker({
  27. root,
  28. result,
  29. locationChecker: checker.after,
  30. checkedRuleName: ruleName,
  31. fix: context.fix
  32. ? (declNode, index) => {
  33. const valueIndex = declarationValueIndex(declNode);
  34. if (index <= valueIndex) {
  35. return false;
  36. }
  37. fixData = fixData || new Map();
  38. const commaIndices = fixData.get(declNode) || [];
  39. commaIndices.push(index);
  40. fixData.set(declNode, commaIndices);
  41. return true;
  42. }
  43. : null,
  44. });
  45. if (fixData) {
  46. fixData.forEach((commaIndices, decl) => {
  47. commaIndices
  48. .sort((a, b) => b - a)
  49. .forEach((index) => {
  50. const value = decl.raws.value ? decl.raws.value.raw : decl.value;
  51. const valueIndex = index - declarationValueIndex(decl);
  52. const beforeValue = value.slice(0, valueIndex + 1);
  53. let afterValue = value.slice(valueIndex + 1);
  54. if (expectation.startsWith('always')) {
  55. afterValue = afterValue.replace(/^\s*/, ' ');
  56. } else if (expectation.startsWith('never')) {
  57. afterValue = afterValue.replace(/^\s*/, '');
  58. }
  59. if (decl.raws.value) {
  60. decl.raws.value.raw = beforeValue + afterValue;
  61. } else {
  62. decl.value = beforeValue + afterValue;
  63. }
  64. });
  65. });
  66. }
  67. };
  68. }
  69. rule.ruleName = ruleName;
  70. rule.messages = messages;
  71. module.exports = rule;