From ce7083881a530a09df214130691d7950949816d9 Mon Sep 17 00:00:00 2001 From: tim Date: Tue, 25 Jun 2024 15:40:59 +0200 Subject: [PATCH] print jsx children on newline when we have a multi-line jsx opening element --- lib/printer.ts | 12 ++++++-- test/jsx.ts | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/lib/printer.ts b/lib/printer.ts index e3f834f0..8593c7b0 100644 --- a/lib/printer.ts +++ b/lib/printer.ts @@ -1305,7 +1305,7 @@ function genericPrintNoParens(path: any, options: any, print: any) { return openingLines; } - const childLines = concat( + let childLines = concat( path.map(function (childPath: any) { const child = childPath.getValue(); @@ -1322,7 +1322,13 @@ function genericPrintNoParens(path: any, options: any, print: any) { return print(childPath); }, "children"), - ).indentTail(options.tabWidth); + ); + if (openingLines.length > 1) { + // If we have a multiline opening element, start the child out on a newline + childLines = concat(["\n", childLines]).indent(options.tabWidth); + } else { + childLines = childLines.indentTail(options.tabWidth); + } const closingLines = path.call(print, closingPropName); @@ -1351,10 +1357,10 @@ function genericPrintNoParens(path: any, options: any, print: any) { attrParts[i] = "\n"; } }); + attrParts.push("\n"); attrLines = concat(attrParts).indentTail(options.tabWidth); } - parts.push(attrLines, n.selfClosing ? " />" : ">"); return concat(parts); diff --git a/test/jsx.ts b/test/jsx.ts index 37f9d9ae..0b15c429 100644 --- a/test/jsx.ts +++ b/test/jsx.ts @@ -93,3 +93,78 @@ it("should not remove trailing whitespaces", function () { "}", ); }); + +it("should print end jsx > on same line when not wrapping", function () { + const printer = new Printer({ tabWidth: 2 }); + const source = + "function App() {\n" + + ' const name = "world";\n' + + "\n" + + " return (\n" + + " \n" + + " hello {name}\n" + + " \n" + + " );\n" + + "}"; + const ast = parse(source); + 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" + + '
hello {name}\n' + + "
\n" + + " );\n" + + "}", + ); +}); + +it("should print end jsx > on a new line when wrapping", function () { + const printer = new Printer({ tabWidth: 2, wrapColumn: 50 }); + const source = + "function App() {\n" + + ' const name = "world";\n' + + "\n" + + " return (\n" + + " \n" + + " hello {name}\n" + + " \n" + + " );\n" + + "}"; + const ast = parse(source); + 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" + + " \n" + + " hello {name}\n" + + " \n" + + " );\n" + + "}", + ); +});