UNPKG

2.19 kBJavaScriptView Raw
1'use strict';
2
3const declarationBangSpaceChecker = require('../declarationBangSpaceChecker');
4const declarationValueIndex = require('../../utils/declarationValueIndex');
5const ruleMessages = require('../../utils/ruleMessages');
6const validateOptions = require('../../utils/validateOptions');
7const whitespaceChecker = require('../../utils/whitespaceChecker');
8
9const ruleName = 'declaration-bang-space-after';
10
11const messages = ruleMessages(ruleName, {
12 expectedAfter: () => 'Expected single space after "!"',
13 rejectedAfter: () => 'Unexpected whitespace after "!"',
14});
15
16function rule(expectation, options, context) {
17 const checker = whitespaceChecker('space', expectation, messages);
18
19 return (root, result) => {
20 const validOptions = validateOptions(result, ruleName, {
21 actual: expectation,
22 possible: ['always', 'never'],
23 });
24
25 if (!validOptions) {
26 return;
27 }
28
29 declarationBangSpaceChecker({
30 root,
31 result,
32 locationChecker: checker.after,
33 checkedRuleName: ruleName,
34 fix: context.fix
35 ? (decl, index) => {
36 let bangIndex = index - declarationValueIndex(decl);
37 const value = decl.raws.value ? decl.raws.value.raw : decl.value;
38 let target;
39 let setFixed;
40
41 if (bangIndex < value.length) {
42 target = value;
43 setFixed = (value) => {
44 if (decl.raws.value) {
45 decl.raws.value.raw = value;
46 } else {
47 decl.value = value;
48 }
49 };
50 } else if (decl.important) {
51 target = decl.raws.important || ' !important';
52 bangIndex -= value.length;
53 setFixed = (value) => {
54 decl.raws.important = value;
55 };
56 } else {
57 return false; // not standard
58 }
59
60 const targetBefore = target.slice(0, bangIndex + 1);
61 const targetAfter = target.slice(bangIndex + 1);
62
63 if (expectation === 'always') {
64 setFixed(targetBefore + targetAfter.replace(/^\s*/, ' '));
65
66 return true;
67 }
68
69 if (expectation === 'never') {
70 setFixed(targetBefore + targetAfter.replace(/^\s*/, ''));
71
72 return true;
73 }
74 }
75 : null,
76 });
77 };
78}
79
80rule.ruleName = ruleName;
81rule.messages = messages;
82module.exports = rule;