From 059dd6807fbc5ed013877ad4e871b3b4ef87312f Mon Sep 17 00:00:00 2001 From: Kenneth Law Date: Thu, 14 Mar 2019 06:30:36 +0800 Subject: [PATCH] [Fix] `jsx-indent`: Fix false positive when a jsx element is the last statement within a do expression Fixes #2199. --- lib/rules/jsx-indent.js | 53 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/lib/rules/jsx-indent.js b/lib/rules/jsx-indent.js index 2076704ad1..f75c4ad6af 100644 --- a/lib/rules/jsx-indent.js +++ b/lib/rules/jsx-indent.js @@ -195,6 +195,56 @@ module.exports = { ); } + /** + * Check if the node is the last statement within a do expression + * @param {ASTNode} node The node to check + * @return {Boolean} true if its the case, false if not + */ + function isLastExpInDoExp(node) { + /* + Detect the structure below: + DoExpression { + body: ( + BlockStatement { + body: [ + (...), + ExpressionStatement { + body: ( + JSXElement { + openingElement: (node) + } + ) + } + ] + } + ) + } + */ + const isInExpStmt = ( + node.parent && + node.parent.parent && + node.parent.parent.type === 'ExpressionStatement' + ); + if (!isInExpStmt) { + return false; + } + + const expStmt = node.parent.parent; + const isInBlockStmtWithinDoExp = ( + expStmt.parent && + expStmt.parent.type === 'BlockStatement' && + expStmt.parent.parent && + expStmt.parent.parent.type === 'DoExpression' + ); + if (!isInBlockStmtWithinDoExp) { + return false; + } + + const blockStmt = expStmt.parent; + const blockStmtLastElm = blockStmt.body[blockStmt.body.length - 1]; + return blockStmtLastElm === expStmt; + } + /** * Check indent for nodes list * @param {ASTNode} node The node to check @@ -239,7 +289,8 @@ module.exports = { const indent = ( prevToken.loc.start.line === node.loc.start.line || isRightInLogicalExp(node) || - isAlternateInConditionalExp(node) + isAlternateInConditionalExp(node) || + isLastExpInDoExp(node) ) ? 0 : indentSize; checkNodesIndent(node, parentElementIndent + indent); }