UNPKG

3.12 kBJavaScriptView Raw
1const { fixingNodes } = require('./es-beautifier-common.js');
2
3const create = (context) => {
4 const option = context.options[0] || {
5 allowSingleLine: true,
6 maxLenInSingleLine: 80,
7 };
8 const allowSingleLine = option.allowSingleLine;
9 const maxElements = option.maxElementsInSingleLine;
10 const maxLen = option.maxLenInSingleLine;
11
12 const sourceCode = context.getSourceCode();
13
14 const enterArrayExpression = (node) => {
15 if (allowSingleLine &&
16 node.loc.start.line === node.loc.end.line &&
17 (!maxElements || node.elements.length <= maxElements) &&
18 (!maxLen || sourceCode.lines[node.loc.end.line - 1].length < maxLen)) {
19 // we accept one line
20 return;
21 }
22
23 let parent = node.parent;
24 while (parent && parent.loc.start.line === node.loc.start.line) {
25 if (fixingNodes.has(parent)) {
26 // we ignore this time as we are still in the process
27 return;
28 }
29 parent = parent.parent;
30 }
31
32 let fixed = false;
33 let prev = null;
34 node.elements.forEach((curr) => {
35 if (prev && prev.loc.end.line === curr.loc.start.line) {
36 if (prev.type === 'ObjectExpression' &&
37 curr.type === 'ObjectExpression') {
38 // we simply ignore in this case
39 } else {
40 context.report({
41 node,
42 message: 'Expression in an array should be on a new line.',
43 loc: curr.loc.start,
44 fix: fixer => fixer.insertTextBefore(curr, '\n'),
45 });
46 fixed = true;
47 }
48 }
49 prev = curr;
50 });
51
52 if (node.elements.length) {
53 const firstToken = sourceCode.getFirstToken(node);
54 const lastToken = sourceCode.getLastToken(node);
55 const firstChild = node.elements[0];
56 const lastChild = node.elements[node.elements.length - 1];
57 if (firstToken.loc.end.line === firstChild.loc.start.line &&
58 firstChild.type !== 'ObjectExpression') {
59 context.report({
60 node,
61 message: 'Expression in an array should be on a new line.',
62 loc: firstToken.loc.start,
63 fix: fixer => fixer.insertTextAfter(firstToken, '\n'),
64 });
65 fixed = true;
66 }
67 if (lastToken.loc.start.line === lastChild.loc.end.line &&
68 lastChild.type !== 'ObjectExpression') {
69 context.report({
70 node,
71 message: 'Expression in an array should be on a new line.',
72 loc: lastToken.loc.end,
73 fix: fixer => fixer.insertTextBefore(lastToken, '\n'),
74 });
75 fixed = true;
76 }
77 }
78
79 if (fixed) fixingNodes.add(node);
80 };
81
82 return {
83 ArrayExpression: enterArrayExpression,
84 };
85};
86
87module.exports = {
88 meta: {
89 docs: {
90 description: 'enforce multi-line elements in an array',
91 category: 'Stylistic Issues',
92 },
93 fixable: 'whitespace',
94 schema: [{
95 type: 'object',
96 properties: {
97 allowSingleLine: { type: 'boolean' },
98 maxElementsInSingleLine: { type: 'integer' },
99 maxLenInSingleLine: { type: 'integer' },
100 },
101 additionalProperties: false,
102 }],
103 },
104 create,
105};