postcss-calc icon indicating copy to clipboard operation
postcss-calc copied to clipboard

calc() breaks when using 3+ variable fallbacks

Open dgp1130 opened this issue 5 years ago • 5 comments
trafficstars

From downstream issue https://github.com/cssnano/cssnano/issues/880 which is from downstream issue https://github.com/angular/angular-cli/issues/16910.

Using a calc() command with 3+ variable fallbacks seems to break the parser.

For example, paste the following code into the CSS Nano playground (which I'm told uses postcss-calc via cssnano-preset-default:

.some-rule-lg {
  --width-lg: 1px;
  --width-md: 2px;
  --width-sm: 3px;
  --offset-lg: 4px;
  --offset-md: 5px;
  --offset-sm: 6px;
  width: calc(var(--width-lg, var(--width-md, var(--width-sm, 0))) + var(--offset-lg, var(--offset-md, var(--offset-sm, 0))));
}

Then look at the JavaScript console and see:

"Parse error on line 1: 
var(--width-lg, var(--width-md, var(--width-sm, 0))) + var(--...
---------------------------------------------------^
Expecting end of input, "ADD", "SUB", "MUL", "DIV", got unexpected "RPAREN""

Work around is to use intermediary variables:

.some-rule-lg {
  --width-lg: 1px;
  --width-md: 2px;
  --width-sm: 3px;
  --offset-lg: 4px;
  --offset-md: 5px;
  --offset-sm: 6px;

  --temp-calc1: var(--width-lg, var(--width-md, var(--width-sm, 0)));
  --temp-calc2: var(--offset-lg, var(--offset-md, var(--offset-sm, 0)));
  width: calc(var(--temp-calc1) + var(--temp-calc2));
}

dgp1130 avatar Mar 12 '20 18:03 dgp1130

The same issue: #77

Semigradsky avatar Mar 13 '20 10:03 Semigradsky

Seems to be still an issue. But the workaround works for me! Will it get fixed soon?

chrsalbert avatar Mar 05 '21 09:03 chrsalbert

Any updates?

yf-hk avatar Feb 07 '22 08:02 yf-hk

Any updates?

Since https://github.com/postcss/postcss-calc/pull/137 it should just warn instead of crashing. Does is still crash for you? The underlying problem is that the parser is incomplete, but to fix it we would need to duplicate the code that's already in the existing parsers (postcss-value-parser and postcss-selector-parser) so I would prefer to find a way to refactor so we don't parse multiple times (currently postcss-calc does parse -> stringify -> parse -> stringify)

ludofischer avatar Feb 07 '22 12:02 ludofischer

This was also reported in #119 (I'm closing that one as duplicate)

maranomynet avatar Oct 13 '22 08:10 maranomynet