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