From ed6a2d905569d860f55965c23fe63bab601e2370 Mon Sep 17 00:00:00 2001 From: Lucas Duailibe Date: Wed, 10 Oct 2018 14:11:37 -0300 Subject: [PATCH] Prevent JSX from breaking a logical expression chain (#5092) --- src/language-js/printer-estree.js | 33 +++++++++++++++++-- .../__snapshots__/jsfmt.spec.js.snap | 11 +++---- tests/jsx/__snapshots__/jsfmt.spec.js.snap | 11 +++---- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/src/language-js/printer-estree.js b/src/language-js/printer-estree.js index f3851e449..6e3c531bb 100644 --- a/src/language-js/printer-estree.js +++ b/src/language-js/printer-estree.js @@ -58,6 +58,8 @@ const { printer: { printDocToString } } = require("../doc"); +let uid = 0; + function shouldPrintComma(options, level) { level = level || "es5"; @@ -503,16 +505,41 @@ function printPathNoParens(path, options, print, args) { return group(concat(parts)); } - const rest = concat(parts.slice(1)); + if (parts.length === 0) { + return ""; + } - return group( + // If the right part is a JSX node, we include it in a separate group to + // prevent it breaking the whole chain, so we can print the expression like: + // + // foo && bar && ( + // + // + // + // ) + + const hasJSX = isJSXNode(n.right); + const rest = concat(hasJSX ? parts.slice(1, -1) : parts.slice(1)); + + const groupId = Symbol("logicalChain-" + ++uid); + const chain = group( concat([ // Don't include the initial expression in the indentation // level. The first item is guaranteed to be the first // left-most expression. parts.length > 0 ? parts[0] : "", indent(rest) - ]) + ]), + { id: groupId } + ); + + if (!hasJSX) { + return chain; + } + + const jsxPart = getLast(parts); + return group( + concat([chain, ifBreak(indent(jsxPart), jsxPart, { groupId })]) ); } case "AssignmentPattern": diff --git a/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap b/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap index 3b219baab..cbb26b7c0 100644 --- a/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap +++ b/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap @@ -423,12 +423,11 @@ exports[`jsx_parent.js - flow-verify 1`] = ` />;
- {!isJellyfishEnabled && - diffUpdateMessageInput != null && ( -
- Text -
- )} + {!isJellyfishEnabled && diffUpdateMessageInput != null && ( +
+ Text +
+ )}
;
diff --git a/tests/jsx/__snapshots__/jsfmt.spec.js.snap b/tests/jsx/__snapshots__/jsfmt.spec.js.snap index 552262dd8..f13e52886 100644 --- a/tests/jsx/__snapshots__/jsfmt.spec.js.snap +++ b/tests/jsx/__snapshots__/jsfmt.spec.js.snap @@ -823,12 +823,11 @@ exports[`logical-expression.js - flow-verify 1`] = `
;
- {a && - b && ( - - make this text just so long enough to break this to the next line - - )} + {a && b && ( + + make this text just so long enough to break this to the next line + + )}
;