/
index.js
112 lines (96 loc) · 2.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { isBoolean } from "lodash";
import { utils } from "stylelint";
import {
declarationValueIndex,
isSingleLineString,
namespace,
whitespaceChecker
} from "../../utils";
export const ruleName = namespace("dollar-variable-colon-newline-after");
export const messages = utils.ruleMessages(ruleName, {
expectedAfter: () => 'Expected newline after ":"',
expectedAfterMultiLine: () =>
'Expected newline after ":" with a multi-line value'
});
export default function(expectation, options, context) {
const checker = whitespaceChecker("newline", expectation, messages);
return (root, result) => {
const validOptions = utils.validateOptions(
result,
ruleName,
{
actual: expectation,
possible: ["always", "always-multi-line"]
},
{
actual: options,
possible: {
disableFix: isBoolean
},
optional: true
}
);
if (!validOptions) {
return;
}
const shouldFix = context.fix && (!options || options.disableFix !== true);
root.walkDecls(decl => {
if (!decl.prop || decl.prop[0] !== "$") {
return;
}
const value = decl.value.trim();
const startsWithParen = value[0] === "(";
const endsWithParen = value[value.length - 1] === ")";
const endsWithDefault = /\)\s*!default$/.test(value);
const isMultilineVarWithParens =
startsWithParen &&
(endsWithParen || endsWithDefault) &&
!isSingleLineString(value);
if (isMultilineVarWithParens) {
return;
}
// Get the raw $var, and only that
const endOfPropIndex =
declarationValueIndex(decl) + decl.raw("between").length - 1;
// `$var:`, `$var :`
const propPlusColon = decl.toString().slice(0, endOfPropIndex);
for (let i = 0, l = propPlusColon.length; i < l; i++) {
if (propPlusColon[i] !== ":") {
continue;
}
const indexToCheck =
propPlusColon.substr(propPlusColon[i], 3) === "/*"
? propPlusColon.indexOf("*/", i) + 1
: i;
checker.afterOneOnly({
source: propPlusColon,
index: indexToCheck,
lineCheckStr: decl.value,
err: m => {
if (shouldFix) {
const nextLinePrefix =
expectation === "always"
? decl.raws.before.replace(context.newline, "")
: decl.value
.split(context.newline)[1]
.replace(/^(\s+).*$/, (_, whitespace) => whitespace);
decl.raws.between = decl.raws.between.replace(
/:(.*)$/,
`:${context.newline}${nextLinePrefix}`
);
return;
}
utils.report({
message: m,
node: decl,
index: indexToCheck,
result,
ruleName
});
}
});
break;
}
});
};
}