Skip to content

Commit

Permalink
Keep braces inline on empty classes and functions (#2336)
Browse files Browse the repository at this point in the history
* Keep braces inline on empty classes and functions

* Handle anonymous classes and static functions

* Update snapshots
  • Loading branch information
hackel authored Jun 11, 2024
1 parent 46b7ba9 commit 7e8f79e
Show file tree
Hide file tree
Showing 20 changed files with 371 additions and 1,007 deletions.
21 changes: 13 additions & 8 deletions src/printer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1297,25 +1297,26 @@ function printClass(path, options, print) {
}
}

const hasEmptyClassBody =
node.body && node.body.length === 0 && !hasDanglingComments(node);

const printedDeclaration = group([
group(declaration),
shouldPrintHardlineForOpenBrace(options)
shouldPrintHardlineForOpenBrace(options) && !hasEmptyClassBody
? isAnonymousClass
? line
: hardline
: " ",
]);

const hasEmptyClassBody =
node.body && node.body.length === 0 && !hasDanglingComments(node);
const printedBody = [
"{",
indent([
hasEmptyClassBody ? "" : hardline,
printStatements(path, options, print, "body"),
]),
printDanglingComments(path, options, true),
isAnonymousClass && hasEmptyClassBody ? softline : hardline,
hasEmptyClassBody ? "" : hardline,
"}",
];

Expand Down Expand Up @@ -1383,14 +1384,14 @@ function printFunction(path, options, print) {
return [...declAttrs, printedDeclaration];
}

const isClosure = node.kind === "closure";
const printedBody = [
"{",
indent([hasEmptyBody(path) ? "" : hardline, print("body")]),
isClosure && hasEmptyBody(path) ? "" : hardline,
hasEmptyBody(path) ? "" : hardline,
"}",
];

const isClosure = node.kind === "closure";
if (isClosure) {
return [...declAttrs, printedDeclaration, " ", printedBody];
}
Expand All @@ -1399,7 +1400,9 @@ function printFunction(path, options, print) {
return [
...declAttrs,
printedDeclaration,
shouldPrintHardlineForOpenBrace(options) ? hardline : " ",
shouldPrintHardlineForOpenBrace(options) && !hasEmptyBody(path)
? hardline
: " ",
printedBody,
];
}
Expand All @@ -1415,7 +1418,9 @@ function printFunction(path, options, print) {
conditionalGroup([
[
printedDeclaration,
shouldPrintHardlineForOpenBrace(options) ? hardline : " ",
shouldPrintHardlineForOpenBrace(options) && !hasEmptyBody(path)
? hardline
: " ",
printedBody,
],
[printedDeclaration, " ", printedBody],
Expand Down
4 changes: 1 addition & 3 deletions tests/attributes/__snapshots__/jsfmt.spec.mjs.snap
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,7 @@ final class DomainEventMessage
}
#[Attr1(Attr1::FOO | Attr1::BAR), Attr2(-20 * 5 + 10)]
class A
{
}
class A {}
class ValueModel
{
Expand Down
Loading

0 comments on commit 7e8f79e

Please sign in to comment.