UNPKG

2.36 kBJavaScriptView Raw
1'use strict';
2
3const beforeBlockString = require('../../utils/beforeBlockString');
4const blockString = require('../../utils/blockString');
5const hasBlock = require('../../utils/hasBlock');
6const hasEmptyBlock = require('../../utils/hasEmptyBlock');
7const report = require('../../utils/report');
8const ruleMessages = require('../../utils/ruleMessages');
9const validateOptions = require('../../utils/validateOptions');
10const whitespaceChecker = require('../../utils/whitespaceChecker');
11
12const ruleName = 'block-opening-brace-space-after';
13
14const messages = ruleMessages(ruleName, {
15 expectedAfter: () => 'Expected single space after "{"',
16 rejectedAfter: () => 'Unexpected whitespace after "{"',
17 expectedAfterSingleLine: () => 'Expected single space after "{" of a single-line block',
18 rejectedAfterSingleLine: () => 'Unexpected whitespace after "{" of a single-line block',
19 expectedAfterMultiLine: () => 'Expected single space after "{" of a multi-line block',
20 rejectedAfterMultiLine: () => 'Unexpected whitespace after "{" of a multi-line block',
21});
22
23function rule(expectation, options, context) {
24 const checker = whitespaceChecker('space', expectation, messages);
25
26 return (root, result) => {
27 const validOptions = validateOptions(result, ruleName, {
28 actual: expectation,
29 possible: [
30 'always',
31 'never',
32 'always-single-line',
33 'never-single-line',
34 'always-multi-line',
35 'never-multi-line',
36 ],
37 });
38
39 if (!validOptions) {
40 return;
41 }
42
43 // Check both kinds of statements: rules and at-rules
44 root.walkRules(check);
45 root.walkAtRules(check);
46
47 function check(statement) {
48 // Return early if blockless or has an empty block
49 if (!hasBlock(statement) || hasEmptyBlock(statement)) {
50 return;
51 }
52
53 checker.after({
54 source: blockString(statement),
55 index: 0,
56 err: (m) => {
57 if (context.fix) {
58 if (expectation.startsWith('always')) {
59 statement.first.raws.before = ' ';
60
61 return;
62 }
63
64 if (expectation.startsWith('never')) {
65 statement.first.raws.before = '';
66
67 return;
68 }
69 }
70
71 report({
72 message: m,
73 node: statement,
74 index: beforeBlockString(statement, { noRawBefore: true }).length + 1,
75 result,
76 ruleName,
77 });
78 },
79 });
80 }
81 };
82}
83
84rule.ruleName = ruleName;
85rule.messages = messages;
86module.exports = rule;