|
| 1 | +/** |
| 2 | + * @fileoverview Validate closing tag location in JSX |
| 3 | + * @author Ross Solomon |
| 4 | + */ |
| 5 | +'use strict'; |
| 6 | + |
| 7 | +// ------------------------------------------------------------------------------ |
| 8 | +// Rule Definition |
| 9 | +// ------------------------------------------------------------------------------ |
| 10 | +module.exports = { |
| 11 | + meta: { |
| 12 | + docs: { |
| 13 | + description: 'Validate closing tag location for multiline JSX', |
| 14 | + category: 'Stylistic Issues', |
| 15 | + recommended: false |
| 16 | + }, |
| 17 | + fixable: 'whitespace' |
| 18 | + }, |
| 19 | + |
| 20 | + create: function(context) { |
| 21 | + var sourceCode = context.getSourceCode(); |
| 22 | + |
| 23 | + /** |
| 24 | + * Checks if the node is the first in its line, excluding whitespace. |
| 25 | + * @param {ASTNode} node The node to check |
| 26 | + * @return {Boolean} true if its the first node in its line |
| 27 | + */ |
| 28 | + function isNodeFirstInLine(node) { |
| 29 | + let token = node; |
| 30 | + let lines; |
| 31 | + do { |
| 32 | + token = sourceCode.getTokenBefore(token); |
| 33 | + lines = token.type === 'JSXText' |
| 34 | + ? token.value.split('\n') |
| 35 | + : null; |
| 36 | + } while ( |
| 37 | + token.type === 'JSXText' && |
| 38 | + /^\s*$/.test(lines[lines.length - 1]) |
| 39 | + ); |
| 40 | + |
| 41 | + var startLine = node.loc.start.line; |
| 42 | + var endLine = token ? token.loc.end.line : -1; |
| 43 | + return startLine !== endLine; |
| 44 | + } |
| 45 | + |
| 46 | + return { |
| 47 | + JSXClosingElement: function(node) { |
| 48 | + if (!node.parent) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + const opening = node.parent.openingElement; |
| 53 | + if (opening.loc.start.line === node.loc.start.line) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + if (opening.loc.start.column === node.loc.start.column) { |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + let message; |
| 62 | + if (!isNodeFirstInLine(node)) { |
| 63 | + message = 'Closing tag of a multiline JSX expression must be on its own line.'; |
| 64 | + } else { |
| 65 | + message = 'Expected closing tag to match indentation of opening.'; |
| 66 | + } |
| 67 | + |
| 68 | + context.report({ |
| 69 | + node: node, |
| 70 | + loc: node.loc, |
| 71 | + message, |
| 72 | + fix: function(fixer) { |
| 73 | + const indent = Array(opening.loc.start.column + 1).join(' '); |
| 74 | + if (isNodeFirstInLine(node)) { |
| 75 | + return fixer.replaceTextRange( |
| 76 | + [node.start - node.loc.start.column, node.start], |
| 77 | + indent |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + return fixer.insertTextBefore(node, `\n${indent}`); |
| 82 | + } |
| 83 | + }); |
| 84 | + } |
| 85 | + }; |
| 86 | + } |
| 87 | +}; |
0 commit comments