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