-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathjsx-closing-tag-location.js
74 lines (63 loc) · 1.94 KB
/
jsx-closing-tag-location.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
/**
* @fileoverview Validate closing tag location in JSX
* @author Ross Solomon
*/
'use strict';
const astUtil = require('../util/ast');
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
onOwnLine: 'Closing tag of a multiline JSX expression must be on its own line.',
matchIndent: 'Expected closing tag to match indentation of opening.',
};
module.exports = {
meta: {
type: 'layout',
docs: {
description: 'Validate closing tag location for multiline JSX',
category: 'Stylistic Issues',
recommended: false,
url: docsUrl('jsx-closing-tag-location'),
},
fixable: 'whitespace',
messages,
},
create(context) {
function handleClosingElement(node) {
if (!node.parent) {
return;
}
const opening = node.parent.openingElement || node.parent.openingFragment;
if (opening.loc.start.line === node.loc.start.line) {
return;
}
if (opening.loc.start.column === node.loc.start.column) {
return;
}
const messageId = astUtil.isNodeFirstInLine(context, node)
? 'matchIndent'
: 'onOwnLine';
report(context, messages[messageId], messageId, {
node,
loc: node.loc,
fix(fixer) {
const indent = Array(opening.loc.start.column + 1).join(' ');
if (astUtil.isNodeFirstInLine(context, node)) {
return fixer.replaceTextRange(
[node.range[0] - node.loc.start.column, node.range[0]],
indent
);
}
return fixer.insertTextBefore(node, `\n${indent}`);
},
});
}
return {
JSXClosingElement: handleClosingElement,
JSXClosingFragment: handleClosingElement,
};
},
};