index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. const atRuleParamIndex = require('../../utils/atRuleParamIndex');
  3. const mediaQueryListCommaWhitespaceChecker = require('../mediaQueryListCommaWhitespaceChecker');
  4. const ruleMessages = require('../../utils/ruleMessages');
  5. const validateOptions = require('../../utils/validateOptions');
  6. const whitespaceChecker = require('../../utils/whitespaceChecker');
  7. const ruleName = 'media-query-list-comma-space-after';
  8. const messages = ruleMessages(ruleName, {
  9. expectedAfter: () => 'Expected single space after ","',
  10. rejectedAfter: () => 'Unexpected whitespace after ","',
  11. expectedAfterSingleLine: () => 'Expected single space after "," in a single-line list',
  12. rejectedAfterSingleLine: () => 'Unexpected whitespace after "," in a single-line list',
  13. });
  14. const meta = {
  15. url: 'https://stylelint.io/user-guide/rules/list/media-query-list-comma-space-after',
  16. };
  17. /** @type {import('stylelint').Rule} */
  18. const rule = (primary, _secondaryOptions, context) => {
  19. const checker = whitespaceChecker('space', primary, messages);
  20. return (root, result) => {
  21. const validOptions = validateOptions(result, ruleName, {
  22. actual: primary,
  23. possible: ['always', 'never', 'always-single-line', 'never-single-line'],
  24. });
  25. if (!validOptions) {
  26. return;
  27. }
  28. /** @type {Map<import('postcss').AtRule, number[]> | undefined} */
  29. let fixData;
  30. mediaQueryListCommaWhitespaceChecker({
  31. root,
  32. result,
  33. locationChecker: checker.after,
  34. checkedRuleName: ruleName,
  35. fix: context.fix
  36. ? (atRule, index) => {
  37. const paramCommaIndex = index - atRuleParamIndex(atRule);
  38. fixData = fixData || new Map();
  39. const commaIndices = fixData.get(atRule) || [];
  40. commaIndices.push(paramCommaIndex);
  41. fixData.set(atRule, commaIndices);
  42. return true;
  43. }
  44. : null,
  45. });
  46. if (fixData) {
  47. for (const [atRule, commaIndices] of fixData.entries()) {
  48. let params = atRule.raws.params ? atRule.raws.params.raw : atRule.params;
  49. for (const index of commaIndices.sort((a, b) => b - a)) {
  50. const beforeComma = params.slice(0, index + 1);
  51. const afterComma = params.slice(index + 1);
  52. if (primary.startsWith('always')) {
  53. params = beforeComma + afterComma.replace(/^\s*/, ' ');
  54. } else if (primary.startsWith('never')) {
  55. params = beforeComma + afterComma.replace(/^\s*/, '');
  56. }
  57. }
  58. if (atRule.raws.params) {
  59. atRule.raws.params.raw = params;
  60. } else {
  61. atRule.params = params;
  62. }
  63. }
  64. }
  65. };
  66. };
  67. rule.ruleName = ruleName;
  68. rule.messages = messages;
  69. rule.meta = meta;
  70. module.exports = rule;