UNPKG

3 kBJavaScriptView Raw
1/**
2 * Requires placing object keys on new line
3 *
4 * Types: `Boolean` or `Object`
5 *
6 * Values:
7 * - `true`
8 * - `Object`:
9 * - `'allExcept'` array of exceptions:
10 * - `'sameLine'` ignores the rule if all the keys and values are on the same line
11 *
12 * #### Example
13 *
14 * ```js
15 * "requireObjectKeysOnNewLine": true
16 * "requireObjectKeysOnNewLine": {
17 * "allExcept": ["sameLine"]
18 * }
19 * ```
20 *
21 * ##### Valid
22 *
23 * ```js
24 * var a = {
25 * b: 'b',
26 * c: 'c'
27 * };
28 * ```
29 *
30 * ##### Invalid
31 *
32 * ```js
33 * var a = {
34 * b: 'b', c: 'c'
35 * };
36 * ```
37 *
38 * ##### Valid for `{ "allExcept": ["sameLine"] }`
39 *
40 * ```js
41 * var a = {
42 * b: 'b', c: 'c'
43 * };
44 * ```
45 *
46 * ##### Invalid for `{ "allExcept": ["sameLine"] }`
47 *
48 * ```js
49 * var a = {
50 * b: 'b', c: 'c',
51 * d: 'd'
52 * };
53 * ```
54 */
55
56var assert = require('assert');
57
58module.exports = function() {};
59
60module.exports.prototype = {
61 configure: function(options) {
62 assert(
63 options === true || Array.isArray(options.allExcept),
64 this.getOptionName() + ' option requires a true value or an object of exceptions'
65 );
66
67 this._isSameLine = false;
68 if (Array.isArray(options.allExcept)) {
69 this._isSameLine = options.allExcept[0] === 'sameLine';
70 }
71 },
72
73 getOptionName: function() {
74 return 'requireObjectKeysOnNewLine';
75 },
76
77 check: function(file, errors) {
78 var message = 'Object keys must go on a new line';
79 var isSameLine = this._isSameLine;
80
81 if (isSameLine) {
82 message = 'Object keys must go on a new line if they aren\'t all on the same line';
83 }
84
85 file.iterateNodesByType('ObjectExpression', function(node) {
86 var firstKeyToken;
87 var lastValueToken;
88 var lastProp;
89
90 if (isSameLine) {
91 if (node.properties.length > 1) {
92 firstKeyToken = file.getFirstNodeToken(node.properties[0].key);
93 lastProp = node.properties[node.properties.length - 1];
94 lastValueToken = file.getLastNodeToken(lastProp.value || lastProp.key);
95
96 if (firstKeyToken.getLoc().end.line === lastValueToken.getLoc().start.line) {
97 // It's ok, all keys and values are on the same line.
98 return;
99 }
100 }
101 }
102
103 for (var i = 1; i < node.properties.length; i++) {
104 var prop = node.properties[i - 1];
105 lastValueToken = file.getLastNodeToken(prop.value || prop.body);
106 var comma = file.findNextToken(lastValueToken, 'Punctuator', ',');
107
108 firstKeyToken = file.getFirstNodeToken(node.properties[i].key);
109
110 errors.assert.differentLine({
111 token: comma,
112 nextToken: firstKeyToken,
113 message: message
114 });
115 }
116 });
117 }
118};