index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // @ts-nocheck
  2. 'use strict';
  3. const atRuleParamIndex = require('../../utils/atRuleParamIndex');
  4. const mediaQueryListCommaWhitespaceChecker = require('../mediaQueryListCommaWhitespaceChecker');
  5. const ruleMessages = require('../../utils/ruleMessages');
  6. const validateOptions = require('../../utils/validateOptions');
  7. const whitespaceChecker = require('../../utils/whitespaceChecker');
  8. const ruleName = 'media-query-list-comma-newline-after';
  9. const messages = ruleMessages(ruleName, {
  10. expectedAfter: () => 'Expected newline after ","',
  11. expectedAfterMultiLine: () => 'Expected newline after "," in a multi-line list',
  12. rejectedAfterMultiLine: () => 'Unexpected whitespace after "," in a multi-line list',
  13. });
  14. function rule(expectation, options, context) {
  15. const checker = whitespaceChecker('newline', expectation, messages);
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, {
  18. actual: expectation,
  19. possible: ['always', 'always-multi-line', 'never-multi-line'],
  20. });
  21. if (!validOptions) {
  22. return;
  23. }
  24. // Only check for the newline after the comma, while allowing
  25. // arbitrary indentation after the newline
  26. let fixData;
  27. mediaQueryListCommaWhitespaceChecker({
  28. root,
  29. result,
  30. locationChecker: checker.afterOneOnly,
  31. checkedRuleName: ruleName,
  32. allowTrailingComments: expectation.startsWith('always'),
  33. fix: context.fix
  34. ? (atRule, index) => {
  35. const paramCommaIndex = index - atRuleParamIndex(atRule);
  36. fixData = fixData || new Map();
  37. const commaIndices = fixData.get(atRule) || [];
  38. commaIndices.push(paramCommaIndex);
  39. fixData.set(atRule, commaIndices);
  40. return true;
  41. }
  42. : null,
  43. });
  44. if (fixData) {
  45. fixData.forEach((commaIndices, atRule) => {
  46. let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
  47. commaIndices
  48. .sort((a, b) => b - a)
  49. .forEach((index) => {
  50. const beforeComma = params.slice(0, index + 1);
  51. const afterComma = params.slice(index + 1);
  52. if (expectation.startsWith('always')) {
  53. if (/^\s*\r?\n/.test(afterComma)) {
  54. params = beforeComma + afterComma.replace(/^[^\S\r\n]*/, '');
  55. } else {
  56. params = beforeComma + context.newline + afterComma;
  57. }
  58. } else if (expectation.startsWith('never')) {
  59. params = beforeComma + afterComma.replace(/^\s*/, '');
  60. }
  61. });
  62. if (atRule.raws.params) {
  63. atRule.raws.params.raw = params;
  64. } else {
  65. atRule.params = params;
  66. }
  67. });
  68. }
  69. };
  70. }
  71. rule.ruleName = ruleName;
  72. rule.messages = messages;
  73. module.exports = rule;