From 2ec1a2e140d597b920d90b497b43afa4aadcd952 Mon Sep 17 00:00:00 2001 From: Ido Rosenthal Date: Wed, 12 Jun 2024 09:58:01 +0300 Subject: [PATCH] feat: group atrules with same name --- packages/code-formatter/src/format-css.ts | 5 ++++- .../test/formatter-experimental.spec.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/code-formatter/src/format-css.ts b/packages/code-formatter/src/format-css.ts index ab6cae1a9..53bd9e539 100644 --- a/packages/code-formatter/src/format-css.ts +++ b/packages/code-formatter/src/format-css.ts @@ -178,9 +178,12 @@ function formatAst(ast: AnyNode, index: number, options: FormatOptions) { const hasNestedChildren = childrenLen === -1; const hasCommentBefore = prevType === 'comment'; const hasRuleBefore = prevType === 'rule'; + const isSameTypeAsPrev = prevType === 'atrule' && prevNode?.name === ast.name; const separation = - hasCommentBefore || (hasNestedChildren && !hasRuleBefore) ? 0 : linesBetween; + hasCommentBefore || (hasNestedChildren && !hasRuleBefore && isSameTypeAsPrev) + ? 0 + : linesBetween; ast.raws.before = index !== 0 || indentLevel > 0 diff --git a/packages/code-formatter/test/formatter-experimental.spec.ts b/packages/code-formatter/test/formatter-experimental.spec.ts index accd26b56..698440e79 100644 --- a/packages/code-formatter/test/formatter-experimental.spec.ts +++ b/packages/code-formatter/test/formatter-experimental.spec.ts @@ -971,6 +971,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, @@ -1065,6 +1077,7 @@ describe('formatter - experimental', () => { @parens (a1: 1px, (a2: 2px) (a3: 3px)) {} @function f(b1, b2, f-nest(b3)) {} + @square [c1, c2, c3[c4]) {} `,