Skip to content

Commit

Permalink
avoids double-parentheses on JSXElements
Browse files Browse the repository at this point in the history
  • Loading branch information
tim committed Jun 18, 2024
1 parent 887f5b7 commit 91896cf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,13 +661,19 @@ function genericPrintNoParens(path: any, options: any, print: any) {
parts.push("return");

if (n.argument) {
const argLines = path.call(print, "argument");
const argIsJsxElement = namedTypes.JSXElement?.check(n.argument)

let argLines = path.call(print, "argument");
if (
argLines.startsWithComment() ||
(argLines.length > 1 &&
namedTypes.JSXElement &&
namedTypes.JSXElement.check(n.argument))
(argLines.length > 1 && argIsJsxElement)
) {
// Babel: regenerate parenthesized jsxElements so we don't double parentheses
if (argIsJsxElement && n.argument.extra?.parenthesized) {
n.argument.extra.parenthesized = false;
argLines = path.call(print, "argument");
n.argument.extra.parenthesized = true;
}
parts.push(" (\n", argLines.indent(options.tabWidth), "\n)");
} else {
parts.push(" ", argLines);
Expand Down
32 changes: 32 additions & 0 deletions test/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,35 @@ it("should not remove trailing whitespaces", function () {
"}",
);
});

it("should not double parentheses in Babel", function () {
const printer = new Printer({ tabWidth: 2 });
const source =
"function App() {\n" +
' const name = "world";\n' +
"\n" +
" return (\n" +
' <div className="app">\n' +
" hello {name}\n" +
" </div>\n" +
" );\n" +
"}";

const ast = parse(source, {parser: require("../parsers/babel")});
ast.program.body[0].body.body[1].argument.openingElement.attributes[0].name.name =
"abc";

const code = printer.printGenerically(ast).code;

assert.equal(
code,
"function App() {\n" +
' const name = "world";\n' +
"\n" +
" return (\n" +
' <div abc="app">hello {name}\n' +
" </div>\n" +
" );\n" +
"}",
);
});

0 comments on commit 91896cf

Please sign in to comment.