UNPKG

2.7 kBJavaScriptView Raw
1'use strict';
2
3const declarationValueIndex = require('../../utils/declarationValueIndex');
4const isStandardSyntaxDeclaration = require('../../utils/isStandardSyntaxDeclaration');
5const report = require('../../utils/report');
6const ruleMessages = require('../../utils/ruleMessages');
7const validateOptions = require('../../utils/validateOptions');
8const whitespaceChecker = require('../../utils/whitespaceChecker');
9
10const ruleName = 'declaration-colon-newline-after';
11
12const messages = ruleMessages(ruleName, {
13 expectedAfter: () => 'Expected newline after ":"',
14 expectedAfterMultiLine: () => 'Expected newline after ":" with a multi-line declaration',
15});
16
17/** @type {import('stylelint').Rule} */
18const rule = (primary, _secondaryOptions, context) => {
19 const checker = whitespaceChecker('newline', primary, messages);
20
21 return (root, result) => {
22 const validOptions = validateOptions(result, ruleName, {
23 actual: primary,
24 possible: ['always', 'always-multi-line'],
25 });
26
27 if (!validOptions) {
28 return;
29 }
30
31 root.walkDecls((decl) => {
32 if (!isStandardSyntaxDeclaration(decl)) {
33 return;
34 }
35
36 // Get the raw prop, and only the prop
37 const endOfPropIndex = declarationValueIndex(decl) + (decl.raws.between || '').length - 1;
38
39 // The extra characters tacked onto the end ensure that there is a character to check
40 // after the colon. Otherwise, with `background:pink` the character after the
41 const propPlusColon = `${decl.toString().slice(0, endOfPropIndex)}xxx`;
42
43 for (let i = 0, l = propPlusColon.length; i < l; i++) {
44 if (propPlusColon[i] !== ':') {
45 continue;
46 }
47
48 const indexToCheck = /^[^\S\r\n]*\/\*/.test(propPlusColon.slice(i + 1))
49 ? propPlusColon.indexOf('*/', i) + 1
50 : i;
51
52 checker.afterOneOnly({
53 source: propPlusColon,
54 index: indexToCheck,
55 lineCheckStr: decl.value,
56 err: (m) => {
57 if (context.fix) {
58 const between = decl.raws.between;
59
60 if (between == null) throw new Error('`between` must be present');
61
62 const betweenStart = declarationValueIndex(decl) - between.length;
63 const sliceIndex = indexToCheck - betweenStart + 1;
64 const betweenBefore = between.slice(0, sliceIndex);
65 const betweenAfter = between.slice(sliceIndex);
66
67 decl.raws.between = /^\s*\n/.test(betweenAfter)
68 ? betweenBefore + betweenAfter.replace(/^[^\S\r\n]*/, '')
69 : betweenBefore + context.newline + betweenAfter;
70
71 return;
72 }
73
74 report({
75 message: m,
76 node: decl,
77 index: indexToCheck,
78 result,
79 ruleName,
80 });
81 },
82 });
83 }
84 });
85 };
86};
87
88rule.ruleName = ruleName;
89rule.messages = messages;
90module.exports = rule;