UNPKG

8.35 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to enforce line breaks after each array element
3 * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
4 */
5
6"use strict";
7
8const astUtils = require("../ast-utils");
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 docs: {
17 description: "enforce line breaks after each array element",
18 category: "Stylistic Issues",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/array-element-newline"
21 },
22 fixable: "whitespace",
23 schema: [
24 {
25 oneOf: [
26 {
27 enum: ["always", "never"]
28 },
29 {
30 type: "object",
31 properties: {
32 multiline: {
33 type: "boolean"
34 },
35 minItems: {
36 type: ["integer", "null"],
37 minimum: 0
38 }
39 },
40 additionalProperties: false
41 }
42 ]
43 }
44 ],
45
46 messages: {
47 unexpectedLineBreak: "There should be no linebreak here.",
48 missingLineBreak: "There should be a linebreak after this element."
49 }
50 },
51
52 create(context) {
53 const sourceCode = context.getSourceCode();
54
55 //----------------------------------------------------------------------
56 // Helpers
57 //----------------------------------------------------------------------
58
59 /**
60 * Normalizes a given option value.
61 *
62 * @param {string|Object|undefined} option - An option value to parse.
63 * @returns {{multiline: boolean, minItems: number}} Normalized option object.
64 */
65 function normalizeOptionValue(option) {
66 let multiline = false;
67 let minItems;
68
69 option = option || "always";
70
71 if (option === "always" || option.minItems === 0) {
72 minItems = 0;
73 } else if (option === "never") {
74 minItems = Number.POSITIVE_INFINITY;
75 } else {
76 multiline = Boolean(option.multiline);
77 minItems = option.minItems || Number.POSITIVE_INFINITY;
78 }
79
80 return { multiline, minItems };
81 }
82
83 /**
84 * Normalizes a given option value.
85 *
86 * @param {string|Object|undefined} options - An option value to parse.
87 * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
88 */
89 function normalizeOptions(options) {
90 const value = normalizeOptionValue(options);
91
92 return { ArrayExpression: value, ArrayPattern: value };
93 }
94
95 /**
96 * Reports that there shouldn't be a line break after the first token
97 * @param {Token} token - The token to use for the report.
98 * @returns {void}
99 */
100 function reportNoLineBreak(token) {
101 const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true });
102
103 context.report({
104 loc: {
105 start: tokenBefore.loc.end,
106 end: token.loc.start
107 },
108 messageId: "unexpectedLineBreak",
109 fix(fixer) {
110 if (astUtils.isCommentToken(tokenBefore)) {
111 return null;
112 }
113
114 if (!astUtils.isTokenOnSameLine(tokenBefore, token)) {
115 return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ");
116 }
117
118 /*
119 * This will check if the comma is on the same line as the next element
120 * Following array:
121 * [
122 * 1
123 * , 2
124 * , 3
125 * ]
126 *
127 * will be fixed to:
128 * [
129 * 1, 2, 3
130 * ]
131 */
132 const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true });
133
134 if (astUtils.isCommentToken(twoTokensBefore)) {
135 return null;
136 }
137
138 return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], "");
139
140 }
141 });
142 }
143
144 /**
145 * Reports that there should be a line break after the first token
146 * @param {Token} token - The token to use for the report.
147 * @returns {void}
148 */
149 function reportRequiredLineBreak(token) {
150 const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true });
151
152 context.report({
153 loc: {
154 start: tokenBefore.loc.end,
155 end: token.loc.start
156 },
157 messageId: "missingLineBreak",
158 fix(fixer) {
159 return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n");
160 }
161 });
162 }
163
164 /**
165 * Reports a given node if it violated this rule.
166 *
167 * @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node.
168 * @param {{multiline: boolean, minItems: number}} options - An option object.
169 * @returns {void}
170 */
171 function check(node) {
172 const elements = node.elements;
173 const normalizedOptions = normalizeOptions(context.options[0]);
174 const options = normalizedOptions[node.type];
175
176 let elementBreak = false;
177
178 /*
179 * MULTILINE: true
180 * loop through every element and check
181 * if at least one element has linebreaks inside
182 * this ensures that following is not valid (due to elements are on the same line):
183 *
184 * [
185 * 1,
186 * 2,
187 * 3
188 * ]
189 */
190 if (options.multiline) {
191 elementBreak = elements
192 .filter(element => element !== null)
193 .some(element => element.loc.start.line !== element.loc.end.line);
194 }
195
196 const needsLinebreaks = (
197 elements.length >= options.minItems ||
198 (
199 options.multiline &&
200 elementBreak
201 )
202 );
203
204 elements.forEach((element, i) => {
205 const previousElement = elements[i - 1];
206
207 if (i === 0 || element === null || previousElement === null) {
208 return;
209 }
210
211 const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken);
212 const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken);
213 const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken);
214
215 if (needsLinebreaks) {
216 if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
217 reportRequiredLineBreak(firstTokenOfCurrentElement);
218 }
219 } else {
220 if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) {
221 reportNoLineBreak(firstTokenOfCurrentElement);
222 }
223 }
224 });
225 }
226
227 //----------------------------------------------------------------------
228 // Public
229 //----------------------------------------------------------------------
230
231 return {
232 ArrayPattern: check,
233 ArrayExpression: check
234 };
235 }
236};