Skip to content

Commit

Permalink
feat(formatter): group similar name at-rules (#2964)
Browse files Browse the repository at this point in the history
  • Loading branch information
idoros authored Jun 17, 2024
1 parent d0be0a1 commit 84dc991
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/code-formatter/src/format-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,19 +181,24 @@ function formatAst(ast: AnyNode, index: number, options: FormatOptions) {
ast.value ||= ' '; // minimal space
}
} else if (ast.type === 'atrule') {
const prevType = ast.prev()?.type;
const prevNode = ast.prev();
const prevType = prevNode?.type;
const childrenLen = ast.nodes?.length ?? -1;
const hasNestedChildren = childrenLen === -1;
const hasCommentBefore = prevType === 'comment';
const hasRuleBefore = prevType === 'rule';
const isSameTypeAsPrev = prevType === 'atrule' && prevNode?.name === ast.name;

/* The postcss type does not represent the reality there are atRules without nodes */
const childrenLen = ast.nodes?.length ?? -1;
const separation =
(childrenLen === -1 && !hasRuleBefore) || hasCommentBefore ? 0 : linesBetween;
hasCommentBefore || (hasNestedChildren && !hasRuleBefore && isSameTypeAsPrev)
? 0
: linesBetween;

ast.raws.before =
index !== 0 || indentLevel > 0
? NL.repeat(index !== 0 ? separation + 1 : 1) + indent.repeat(indentLevel)
: '';

ast.raws.after = childrenLen ? NL + indent.repeat(indentLevel) : '';
ast.raws.afterName = ast.params.length
? enforceOneSpaceAround(ast.raws.afterName || '')
Expand Down
13 changes: 13 additions & 0 deletions packages/code-formatter/test/formatter-experimental.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,18 @@ describe('formatter - experimental', () => {
`,
});
});
it('should group similar named atRules with no body', () => {
testFormatCss({
message: 'top-level',
source: `@aaa 1;@aaa 2;@bbb 1;@bbb 2;@aaa 3`,
expect: `@aaa 1;\n@aaa 2;\n\n@bbb 1;\n@bbb 2;\n\n@aaa 3\n`,
});
testFormatCss({
message: 'nested',
source: `@top {@aaa 1;@aaa 2;@bbb 1;@bbb 2;@aaa 3}`,
expect: `@top {\n @aaa 1;\n @aaa 2;\n\n @bbb 1;\n @bbb 2;\n\n @aaa 3\n}\n`,
});
});
it('should set body into lines and indent accordingly', () => {
testFormatCss({
deindent: true,
Expand Down Expand Up @@ -1126,6 +1138,7 @@ describe('formatter - experimental', () => {
@parens (a1: 1px, (a2: 2px) (a3: 3px)) {}
@function f(b1, b2, f-nest(b3)) {}
@square [c1, c2, c3[c4]) {}
`,
Expand Down

0 comments on commit 84dc991

Please sign in to comment.