UNPKG

3.67 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to enforce placing object properties on separate lines.
3 * @author Vitor Balocco
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 type: "layout",
15
16 docs: {
17 description: "enforce placing object properties on separate lines",
18 category: "Stylistic Issues",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/object-property-newline"
21 },
22
23 schema: [
24 {
25 type: "object",
26 properties: {
27 allowAllPropertiesOnSameLine: {
28 type: "boolean",
29 default: false
30 },
31 allowMultiplePropertiesPerLine: { // Deprecated
32 type: "boolean",
33 default: false
34 }
35 },
36 additionalProperties: false
37 }
38 ],
39
40 fixable: "whitespace"
41 },
42
43 create(context) {
44 const allowSameLine = context.options[0] && (
45 (context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */)
46 );
47 const errorMessage = allowSameLine
48 ? "Object properties must go on a new line if they aren't all on the same line."
49 : "Object properties must go on a new line.";
50
51 const sourceCode = context.getSourceCode();
52
53 return {
54 ObjectExpression(node) {
55 if (allowSameLine) {
56 if (node.properties.length > 1) {
57 const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]);
58 const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]);
59
60 if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) {
61
62 // All keys and values are on the same line
63 return;
64 }
65 }
66 }
67
68 for (let i = 1; i < node.properties.length; i++) {
69 const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]);
70 const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]);
71
72 if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) {
73 context.report({
74 node,
75 loc: firstTokenOfCurrentProperty.loc.start,
76 message: errorMessage,
77 fix(fixer) {
78 const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty);
79 const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]];
80
81 // Don't perform a fix if there are any comments between the comma and the next property.
82 if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) {
83 return null;
84 }
85
86 return fixer.replaceTextRange(rangeAfterComma, "\n");
87 }
88 });
89 }
90 }
91 }
92 };
93 }
94};