UNPKG

2.5 kBJavaScriptView Raw
1// @ts-nocheck
2
3'use strict';
4
5const declarationValueIndex = require('../../utils/declarationValueIndex');
6const ruleMessages = require('../../utils/ruleMessages');
7const validateOptions = require('../../utils/validateOptions');
8const valueListCommaWhitespaceChecker = require('../valueListCommaWhitespaceChecker');
9const whitespaceChecker = require('../../utils/whitespaceChecker');
10
11const ruleName = 'value-list-comma-space-before';
12
13const messages = ruleMessages(ruleName, {
14 expectedBefore: () => 'Expected single space before ","',
15 rejectedBefore: () => 'Unexpected whitespace before ","',
16 expectedBeforeSingleLine: () => 'Unexpected whitespace before "," in a single-line list',
17 rejectedBeforeSingleLine: () => 'Unexpected whitespace before "," in a single-line list',
18});
19
20function 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.before,
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 let beforeValue = value.slice(0, valueIndex);
67 const afterValue = value.slice(valueIndex);
68
69 if (expectation.startsWith('always')) {
70 beforeValue = beforeValue.replace(/\s*$/, ' ');
71 } else if (expectation.startsWith('never')) {
72 beforeValue = beforeValue.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
86rule.ruleName = ruleName;
87rule.messages = messages;
88module.exports = rule;