-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathjsx-first-prop-new-line.js
77 lines (67 loc) · 2.3 KB
/
jsx-first-prop-new-line.js
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
/**
* @fileoverview Ensure proper position of the first property in JSX
* @author Joachim Seminck
*/
'use strict';
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
propOnNewLine: 'Property should be placed on a new line',
propOnSameLine: 'Property should be placed on the same line as the component declaration',
};
module.exports = {
meta: {
type: 'layout',
docs: {
description: 'Ensure proper position of the first property in JSX',
category: 'Stylistic Issues',
recommended: false,
url: docsUrl('jsx-first-prop-new-line'),
},
fixable: 'whitespace',
messages,
schema: [{
enum: ['always', 'never', 'multiline', 'multiline-multiprop'],
}],
},
create(context) {
const configuration = context.options[0] || 'multiline-multiprop';
function isMultilineJSX(jsxNode) {
return jsxNode.loc.start.line < jsxNode.loc.end.line;
}
return {
JSXOpeningElement(node) {
if (
(configuration === 'multiline' && isMultilineJSX(node))
|| (configuration === 'multiline-multiprop' && isMultilineJSX(node) && node.attributes.length > 1)
|| (configuration === 'always')
) {
node.attributes.some((decl) => {
if (decl.loc.start.line === node.loc.start.line) {
report(context, messages.propOnNewLine, 'propOnNewLine', {
node: decl,
fix(fixer) {
return fixer.replaceTextRange([node.name.range[1], decl.range[0]], '\n');
},
});
}
return true;
});
} else if (configuration === 'never' && node.attributes.length > 0) {
const firstNode = node.attributes[0];
if (node.loc.start.line < firstNode.loc.start.line) {
report(context, messages.propOnSameLine, 'propOnSameLine', {
node: firstNode,
fix(fixer) {
return fixer.replaceTextRange([node.name.range[1], firstNode.range[0]], ' ');
},
});
}
}
},
};
},
};