Skip to content

Commit 2a52453

Browse files
committed
reinstate formatting of atrule prelude (1:1 copy
1 parent 4b50756 commit 2a52453

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

index.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,11 +389,33 @@ export function format(css: string, { minify = false, tab_size = undefined }: Fo
389389
return lines.join(NEWLINE)
390390
}
391391

392+
/**
393+
* Pretty-printing atrule preludes takes an insane amount of rules,
394+
* so we're opting for a couple of 'good-enough' string replacements
395+
* here to force some nice formatting.
396+
* Should be OK perf-wise, since the amount of atrules in most
397+
* stylesheets are limited, so this won't be called too often.
398+
*/
399+
function print_atrule_prelude(prelude: string): string {
400+
return prelude
401+
.replace(/\s*([:,])/g, prelude.toLowerCase().includes('selector(') ? '$1' : '$1 ') // force whitespace after colon or comma, except inside `selector()`
402+
.replace(/\)([a-zA-Z])/g, ') $1') // force whitespace between closing parenthesis and following text (usually and|or)
403+
.replace(/\s*(=>|<=)\s*/g, ' $1 ') // force whitespace around => and <=
404+
.replace(/([^<>=\s])([<>])([^<>=\s])/g, `$1${OPTIONAL_SPACE}$2${OPTIONAL_SPACE}$3`) // add spacing around < or > except when it's part of <=, >=, =>
405+
.replace(/\s+/g, OPTIONAL_SPACE) // collapse multiple whitespaces into one
406+
.replace(/calc\(\s*([^()+\-*/]+)\s*([*/+-])\s*([^()+\-*/]+)\s*\)/g, (_, left, operator, right) => {
407+
// force required or optional whitespace around * and / in calc()
408+
let space = operator === '+' || operator === '-' ? SPACE : OPTIONAL_SPACE
409+
return `calc(${left.trim()}${space}${operator}${space}${right.trim()})`
410+
})
411+
.replace(/selector|url|supports|layer\(/gi, (match) => match.toLowerCase()) // lowercase function names
412+
}
413+
392414
function print_atrule(node: CSSNode): string {
393415
let lines = []
394416
let name = [`@`, node.name.toLowerCase()]
395417
if (node.prelude !== null) {
396-
name.push(SPACE, node.prelude)
418+
name.push(SPACE, print_atrule_prelude(node.prelude))
397419
}
398420
if (node.block === null) {
399421
name.push(SEMICOLON)

0 commit comments

Comments
 (0)