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