Also preserve math whitespace in clamp, min, max

Fixes #351
This commit is contained in:
Matthias Mullie 2020-12-21 14:12:21 +01:00
parent 9ba1b45982
commit 8931f76af2
2 changed files with 29 additions and 14 deletions

View File

@ -307,7 +307,7 @@ class CSS extends Minify
*/ */
$this->extractStrings(); $this->extractStrings();
$this->stripComments(); $this->stripComments();
$this->extractCalcs(); $this->extractMath();
$css = $this->replace($css); $css = $this->replace($css);
$css = $this->stripWhitespace($css); $css = $this->stripWhitespace($css);
@ -678,19 +678,21 @@ class CSS extends Minify
} }
/** /**
* Replace all `calc()` occurrences. * Replace all occurrences of functions that may contain math, where
* whitespace around operators needs to be preserved (e.g. calc, clamp)
*/ */
protected function extractCalcs() protected function extractMath()
{ {
// PHP only supports $this inside anonymous functions since 5.4 // PHP only supports $this inside anonymous functions since 5.4
$minifier = $this; $minifier = $this;
$callback = function ($match) use ($minifier) { $callback = function ($match) use ($minifier) {
$length = strlen($match[1]); $function = $match[1];
$length = strlen($match[2]);
$expr = ''; $expr = '';
$opened = 0; $opened = 0;
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$char = $match[1][$i]; $char = $match[2][$i];
$expr .= $char; $expr .= $char;
if ($char === '(') { if ($char === '(') {
$opened++; $opened++;
@ -698,18 +700,25 @@ class CSS extends Minify
break; break;
} }
} }
$rest = str_replace($expr, '', $match[1]); $rest = str_replace($expr, '', $match[2]);
$expr = trim(substr($expr, 1, -1)); $expr = trim(substr($expr, 1, -1));
$count = count($minifier->extracted); $count = count($minifier->extracted);
$placeholder = 'calc('.$count.')'; $placeholder = 'math('.$count.')';
$minifier->extracted[$placeholder] = 'calc('.$expr.')'; $minifier->extracted[$placeholder] = $function.'('.$expr.')';
return $placeholder.$rest; return $placeholder.$rest;
}; };
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/', $callback); $functions = array('calc', 'clamp', 'min', 'max');
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/m', $callback); $this->registerPattern(
'/('. implode($functions, '|') .')(\(.+?)(?=$|;|}|('. implode($functions, '|') .')\()/',
$callback
);
$this->registerPattern(
'/('. implode($functions, '|') .')(\(.+?)(?=$|;|}|('. implode($functions, '|') .')\()/m',
$callback
);
} }
/** /**

View File

@ -800,6 +800,12 @@ body{font-family:sans-serif}',
'ul p{padding-left:calc((var(--icon-size) / 2) + var(--horisontal-space))}', 'ul p{padding-left:calc((var(--icon-size) / 2) + var(--horisontal-space))}',
); );
// https://github.com/matthiasmullie/minify/issues/351
$tests[] = array(
'clamp(2.5rem, 1rem + 4vw, 4rem)',
'clamp(2.5rem, 1rem + 4vw, 4rem)',
);
return $tests; return $tests;
} }