Skip to content

Commit f81a544

Browse files
JavaScript - indent non-block bodies of if, while, for (#6186)
1 parent 12bd23a commit f81a544

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

rewrite-javascript/rewrite/src/javascript/format.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1145,7 +1145,26 @@ export class TabsAndIndentsVisitor<P> extends JavaScriptVisitor<P> {
11451145

11461146
protected async preVisit(tree: J, p: P): Promise<J | undefined> {
11471147
const ret = await super.preVisit(tree, p);
1148-
const indentShouldIncrease = tree.kind === J.Kind.Block || tree.kind === J.Kind.Case;
1148+
let indentShouldIncrease = tree.kind === J.Kind.Block || tree.kind === J.Kind.Case;
1149+
1150+
// Increase indent for control structures with non-block bodies
1151+
if (tree.kind === J.Kind.If) {
1152+
const ifStmt = tree as J.If;
1153+
if (ifStmt.thenPart.element.kind !== J.Kind.Block) {
1154+
indentShouldIncrease = true;
1155+
}
1156+
} else if (tree.kind === J.Kind.WhileLoop) {
1157+
const whileLoop = tree as J.WhileLoop;
1158+
if (whileLoop.body.element.kind !== J.Kind.Block) {
1159+
indentShouldIncrease = true;
1160+
}
1161+
} else if (tree.kind === J.Kind.ForLoop) {
1162+
const forLoop = tree as J.ForLoop;
1163+
if (forLoop.body.element.kind !== J.Kind.Block) {
1164+
indentShouldIncrease = true;
1165+
}
1166+
}
1167+
11491168
if (indentShouldIncrease) {
11501169
this.cursor.messages.set("indentToUse", this.currentIndent + this.singleIndent);
11511170
}

rewrite-javascript/rewrite/test/javascript/format/tabs-and-indents-visitor.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,34 @@ describe('TabsAndIndentsVisitor', () => {
284284
// @formatter:on
285285
)
286286
})
287+
288+
test("collapsed if/while", () => {
289+
const spec = new RecipeSpec()
290+
spec.recipe = fromVisitor(new TabsAndIndentsVisitor(tabsAndIndents(draft => {})));
291+
return spec.rewriteRun(
292+
// @formatter:off
293+
//language=typescript
294+
typescript(
295+
`
296+
if (504 == 436)
297+
console.log("That's practically true!");
298+
if (407 == 501)
299+
console.log("Also true!");
300+
while (!areWeThereYet())
301+
wait();
302+
if (116 == 119) console.log("Close, but false. No changes");
303+
`,
304+
`
305+
if (504 == 436)
306+
console.log("That's practically true!");
307+
if (407 == 501)
308+
console.log("Also true!");
309+
while (!areWeThereYet())
310+
wait();
311+
if (116 == 119) console.log("Close, but false. No changes");
312+
`,
313+
)
314+
// @formatter:on
315+
)
316+
})
287317
});

0 commit comments

Comments
 (0)