amzn / style-dictionary

A build system for creating cross-platform styles.
https://styledictionary.com
Apache License 2.0
3.87k stars 543 forks source link

Wrap tokens for CSS output containing math expressions in calc() #1055

Open jorenbroekema opened 10 months ago

jorenbroekema commented 10 months ago

Feature Request

For the CSS property formatter or as a CSS-specific value transform (I prefer the latter, format should not be concerned much with token value changes).

:root {
  --my-math: 15px + 20px;
}

This is invalid CSS, but would be valid if wrapped inside CSS calc() statement. This can be done for any expression using * / + - characters. Important to note is that whatever we do to regex match such tokens is that there must be spaces around the + and - math operators, see https://developer.mozilla.org/en-US/docs/Web/CSS/calc#notes

Output will then be:

:root {
  --my-math: calc(15px + 20px);
}

Should probably also support CSS custom props:

:root {
  --my-length: 15px;
  --my-math: calc(var(--my-length) + 20px);
}
surfinzap commented 1 month ago

Is there any update on this feature request? wrapping math operations in calc() should also work for the outputReferences: true config.

jorenbroekema commented 1 month ago

The big issue is that outputting refs happens on the format lifecycle and wrapping values in calc() statements usually happens in the transform lifecycle that happens before. So even if you wrap the values in calc() in transform, the format part will just undo that work by outputting refs by using the original value.

Either the calc wrapping needs to happen on the format level or the outputting refs util needs to act on the transformed value somehow (keeping in mind the bugs that this used to cause in v3 and not regressing on this again)

There are a couple of open issues to rethink how references are resolved and how values with references in them are transformed for a future v5 version of Style Dictionary, but this topic is rather complex and this issue won't be fixed until we have solutions to that broader topic.