UNPKG

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