object-property-newline.js
3.59 KB
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
/**
* @fileoverview Rule to enforce placing object properties on separate lines.
* @author Vitor Balocco
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
description: "enforce placing object properties on separate lines",
category: "Stylistic Issues",
recommended: false,
url: "https://eslint.org/docs/rules/object-property-newline"
},
schema: [
{
type: "object",
properties: {
allowAllPropertiesOnSameLine: {
type: "boolean",
default: false
},
allowMultiplePropertiesPerLine: { // Deprecated
type: "boolean",
default: false
}
},
additionalProperties: false
}
],
fixable: "whitespace"
},
create(context) {
const allowSameLine = context.options[0] && (
(context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */)
);
const errorMessage = allowSameLine
? "Object properties must go on a new line if they aren't all on the same line."
: "Object properties must go on a new line.";
const sourceCode = context.getSourceCode();
return {
ObjectExpression(node) {
if (allowSameLine) {
if (node.properties.length > 1) {
const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]);
const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]);
if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) {
// All keys and values are on the same line
return;
}
}
}
for (let i = 1; i < node.properties.length; i++) {
const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]);
const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]);
if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) {
context.report({
node,
loc: firstTokenOfCurrentProperty.loc.start,
message: errorMessage,
fix(fixer) {
const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty);
const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]];
// Don't perform a fix if there are any comments between the comma and the next property.
if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) {
return null;
}
return fixer.replaceTextRange(rangeAfterComma, "\n");
}
});
}
}
}
};
}
};