1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const blockString = require('../../utils/blockString');
|
6 | const report = require('../../utils/report');
|
7 | const ruleMessages = require('../../utils/ruleMessages');
|
8 | const validateOptions = require('../../utils/validateOptions');
|
9 | const whitespaceChecker = require('../../utils/whitespaceChecker');
|
10 |
|
11 | const ruleName = 'declaration-block-semicolon-space-before';
|
12 |
|
13 | const messages = ruleMessages(ruleName, {
|
14 | expectedBefore: () => 'Expected single space before ";"',
|
15 | rejectedBefore: () => 'Unexpected whitespace before ";"',
|
16 | expectedBeforeSingleLine: () =>
|
17 | 'Expected single space before ";" in a single-line declaration block',
|
18 | rejectedBeforeSingleLine: () =>
|
19 | 'Unexpected whitespace before ";" in a single-line declaration block',
|
20 | });
|
21 |
|
22 | function rule(expectation, options, context) {
|
23 | const checker = whitespaceChecker('space', expectation, messages);
|
24 |
|
25 | return (root, result) => {
|
26 | const validOptions = validateOptions(result, ruleName, {
|
27 | actual: expectation,
|
28 | possible: ['always', 'never', 'always-single-line', 'never-single-line'],
|
29 | });
|
30 |
|
31 | if (!validOptions) {
|
32 | return;
|
33 | }
|
34 |
|
35 | root.walkDecls((decl) => {
|
36 |
|
37 | const parentRule = decl.parent;
|
38 |
|
39 | if (!parentRule.raws.semicolon && parentRule.last === decl) {
|
40 | return;
|
41 | }
|
42 |
|
43 | const declString = decl.toString();
|
44 |
|
45 | checker.before({
|
46 | source: declString,
|
47 | index: declString.length,
|
48 | lineCheckStr: blockString(parentRule),
|
49 | err: (m) => {
|
50 | if (context.fix) {
|
51 | const value = decl.raws.value ? decl.raws.value.raw : decl.value;
|
52 |
|
53 | if (expectation.startsWith('always')) {
|
54 | if (decl.important) {
|
55 | decl.raws.important = ' !important ';
|
56 | } else if (decl.raws.value) {
|
57 | decl.raws.value.raw = value.replace(/\s*$/, ' ');
|
58 | } else {
|
59 | decl.value = value.replace(/\s*$/, ' ');
|
60 | }
|
61 |
|
62 | return;
|
63 | }
|
64 |
|
65 | if (expectation.startsWith('never')) {
|
66 | if (decl.important) {
|
67 | decl.raws.important = decl.raws.important.replace(/\s*$/, '');
|
68 | } else if (decl.raws.value) {
|
69 | decl.raws.value.raw = value.replace(/\s*$/, '');
|
70 | } else {
|
71 | decl.value = value.replace(/\s*$/, '');
|
72 | }
|
73 |
|
74 | return;
|
75 | }
|
76 | }
|
77 |
|
78 | report({
|
79 | message: m,
|
80 | node: decl,
|
81 | index: decl.toString().length - 1,
|
82 | result,
|
83 | ruleName,
|
84 | });
|
85 | },
|
86 | });
|
87 | });
|
88 | };
|
89 | }
|
90 |
|
91 | rule.ruleName = ruleName;
|
92 | rule.messages = messages;
|
93 | module.exports = rule;
|