@@ -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 - z A - 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 ( / c a l c \( \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 ( / s e l e c t o r | u r l | s u p p o r t s | l a y e r \( / 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