/
index.js
90 lines (72 loc) · 2.65 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
'use strict';
const declarationValueIndex = require('../../utils/declarationValueIndex');
const isStandardSyntaxDeclaration = require('../../utils/isStandardSyntaxDeclaration');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const whitespaceChecker = require('../../utils/whitespaceChecker');
const ruleName = 'declaration-colon-newline-after';
const messages = ruleMessages(ruleName, {
expectedAfter: () => 'Expected newline after ":"',
expectedAfterMultiLine: () => 'Expected newline after ":" with a multi-line declaration',
});
/** @type {import('stylelint').StylelintRule} */
const rule = (primary, _secondaryOptions, context) => {
const checker = whitespaceChecker('newline', primary, messages);
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: primary,
possible: ['always', 'always-multi-line'],
});
if (!validOptions) {
return;
}
root.walkDecls((decl) => {
if (!isStandardSyntaxDeclaration(decl)) {
return;
}
// Get the raw prop, and only the prop
const endOfPropIndex = declarationValueIndex(decl) + (decl.raws.between || '').length - 1;
// The extra characters tacked onto the end ensure that there is a character to check
// after the colon. Otherwise, with `background:pink` the character after the
const propPlusColon = `${decl.toString().slice(0, endOfPropIndex)}xxx`;
for (let i = 0, l = propPlusColon.length; i < l; i++) {
if (propPlusColon[i] !== ':') {
continue;
}
const indexToCheck = /^[^\S\r\n]*\/\*/.test(propPlusColon.slice(i + 1))
? propPlusColon.indexOf('*/', i) + 1
: i;
checker.afterOneOnly({
source: propPlusColon,
index: indexToCheck,
lineCheckStr: decl.value,
err: (m) => {
if (context.fix) {
const between = decl.raws.between;
if (between == null) throw new Error('`between` must be present');
const betweenStart = declarationValueIndex(decl) - between.length;
const sliceIndex = indexToCheck - betweenStart + 1;
const betweenBefore = between.slice(0, sliceIndex);
const betweenAfter = between.slice(sliceIndex);
decl.raws.between = /^\s*\n/.test(betweenAfter)
? betweenBefore + betweenAfter.replace(/^[^\S\r\n]*/, '')
: betweenBefore + context.newline + betweenAfter;
return;
}
report({
message: m,
node: decl,
index: indexToCheck,
result,
ruleName,
});
},
});
}
});
};
};
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;