UNPKG

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