11import { doc } from 'prettier' ;
2- import { printSeparatedItem } from '../common/printer-helpers.js' ;
2+ import {
3+ printComments ,
4+ printSeparatedItem
5+ } from '../common/printer-helpers.js' ;
36
47const { group, hardline, indent, line } = doc . builders ;
58
@@ -19,9 +22,10 @@ const printFalseBody = (node, path, print) =>
1922 ? [ ' ' , path . call ( print , 'falseBody' ) ]
2023 : group ( indent ( [ line , path . call ( print , 'falseBody' ) ] ) ) ;
2124
22- const printElse = ( node , path , print ) => {
25+ const printElse = ( node , path , print , commentsBetweenIfAndElse ) => {
2326 if ( node . falseBody ) {
24- const elseOnSameLine = node . trueBody . type === 'Block' ;
27+ const elseOnSameLine =
28+ node . trueBody . type === 'Block' && commentsBetweenIfAndElse . length === 0 ;
2529 return [
2630 elseOnSameLine ? ' ' : hardline ,
2731 'else' ,
@@ -32,11 +36,22 @@ const printElse = (node, path, print) => {
3236} ;
3337
3438export const IfStatement = {
35- print : ( { node, path, print } ) => [
36- 'if (' ,
37- printSeparatedItem ( path . call ( print , 'condition' ) ) ,
38- ')' ,
39- printTrueBody ( node , path , print ) ,
40- printElse ( node , path , print )
41- ]
39+ print : ( { node, options, path, print } ) => {
40+ const comments = node . comments || [ ] ;
41+ const commentsBetweenIfAndElse = comments . filter (
42+ ( comment ) => ! comment . leading && ! comment . trailing
43+ ) ;
44+
45+ const parts = [ ] ;
46+
47+ parts . push ( 'if (' , printSeparatedItem ( path . call ( print , 'condition' ) ) , ')' ) ;
48+ parts . push ( printTrueBody ( node , path , print ) ) ;
49+ if ( commentsBetweenIfAndElse . length && node . falseBody ) {
50+ parts . push ( hardline ) ;
51+ parts . push ( printComments ( node , path , options ) ) ;
52+ }
53+ parts . push ( printElse ( node , path , print , commentsBetweenIfAndElse ) ) ;
54+
55+ return parts ;
56+ }
4257} ;
0 commit comments