Skip to content

Commit 6252ec9

Browse files
Merge pull request #1406 from mightymeld/2024/06/fix_double_parentheses
fix: double parentheses when returning JSXElements using Babel parser
2 parents 26f21ab + 2d6919c commit 6252ec9

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

lib/printer.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -661,14 +661,22 @@ function genericPrintNoParens(path: any, options: any, print: any) {
661661
parts.push("return");
662662

663663
if (n.argument) {
664-
const argLines = path.call(print, "argument");
664+
const argIsJsxElement =
665+
namedTypes.JSXElement?.check(n.argument) ||
666+
namedTypes.JSXFragment?.check(n.argument);
667+
668+
let argLines = path.call(print, "argument");
665669
if (
666670
argLines.startsWithComment() ||
667-
(argLines.length > 1 &&
668-
namedTypes.JSXElement &&
669-
namedTypes.JSXElement.check(n.argument))
671+
(argLines.length > 1 && argIsJsxElement)
670672
) {
671-
parts.push(" (\n", argLines.indent(options.tabWidth), "\n)");
673+
// Babel: regenerate parenthesized jsxElements so we don't double parentheses
674+
if (argIsJsxElement && n.argument.extra?.parenthesized) {
675+
n.argument.extra.parenthesized = false;
676+
argLines = path.call(print, "argument");
677+
n.argument.extra.parenthesized = true;
678+
}
679+
parts.push(" ", concat(["(\n", argLines]).indentTail(options.tabWidth), "\n)");
672680
} else {
673681
parts.push(" ", argLines);
674682
}

test/jsx.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,35 @@ it("should not remove trailing whitespaces", function () {
9393
"}",
9494
);
9595
});
96+
97+
it("should not double parentheses in Babel", function () {
98+
const printer = new Printer({ tabWidth: 2 });
99+
const source =
100+
"function App() {\n" +
101+
' const name = "world";\n' +
102+
"\n" +
103+
" return (\n" +
104+
' <div className="app">\n' +
105+
" hello {name}\n" +
106+
" </div>\n" +
107+
" );\n" +
108+
"}";
109+
110+
const ast = parse(source, { parser: require("../parsers/babel") });
111+
ast.program.body[0].body.body[1].argument.openingElement.attributes[0].name.name =
112+
"abc";
113+
114+
const code = printer.printGenerically(ast).code;
115+
116+
assert.equal(
117+
code,
118+
"function App() {\n" +
119+
' const name = "world";\n' +
120+
"\n" +
121+
" return (\n" +
122+
' <div abc="app">hello {name}\n' +
123+
" </div>\n" +
124+
" );\n" +
125+
"}",
126+
);
127+
});

0 commit comments

Comments
 (0)