feat(prettier): implement has_comment, improve blank lines when printing arrays (#1601)

This commit is contained in:
Cameron 2023-12-01 12:52:26 +00:00 committed by GitHub
parent deac95e274
commit b4e90a723a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 3 deletions

View file

@ -26,6 +26,16 @@ impl Comment {
self.has_line_suffix = yes;
self
}
pub fn matches_flags(self, flags: CommentFlags) -> bool {
if flags.contains(CommentFlags::Block) && !self.is_block {
return false;
}
if flags.contains(CommentFlags::Line) && self.is_block {
return false;
}
true
}
}
#[derive(Default)]

View file

@ -31,8 +31,38 @@ impl<'a> Prettier<'a> {
doc
}
#[allow(unused)]
pub(crate) fn has_comment(_span: Span, _flags: CommentFlags) -> bool {
pub(crate) fn has_comment(&mut self, range: Span, flags: CommentFlags) -> bool {
let mut peekable_trivias = self.trivias.clone();
while let Some(&(start, end, kind)) = peekable_trivias.peek() {
let mut should_break = true;
let comment = Comment::new(start, end, kind);
if range.end < comment.start
&& self.source_text[range.end as usize..comment.start as usize]
.chars()
.all(|c| c == ' ')
{
if flags.contains(CommentFlags::Trailing) && comment.matches_flags(flags) {
return true;
}
should_break = false;
}
if comment.end <= range.end {
if flags.contains(CommentFlags::Dangling) && comment.matches_flags(flags) {
return true;
}
should_break = false;
}
if should_break {
break;
}
peekable_trivias.next();
}
false
}

View file

@ -4,7 +4,7 @@ use oxc_syntax::operator::UnaryOperator;
use crate::{
array,
comments::DanglingCommentsPrintOptions,
comments::{CommentFlags, DanglingCommentsPrintOptions},
doc::{Doc, DocBuilder, Fill, Group},
group, hardline, if_break, indent, line, softline, ss, Prettier,
};
@ -217,6 +217,12 @@ where
space_parts.extend(hardline!());
space_parts.extend(hardline!());
parts.push(Doc::Array(space_parts));
} else if array.elements.get(i + 1).is_some_and(|next| {
p.has_comment(next.span(), CommentFlags::Leading | CommentFlags::Line)
}) {
let mut space_parts = p.vec();
space_parts.extend(hardline!());
parts.push(Doc::Array(space_parts));
} else {
parts.push(line!());
}