We have a design system and design tokens. Design tokens are common variables that are normally used in our components. Something like spacings, borders, colors, etc. (Real-world example is here: https://orbit.kiwi/design-tokens/)
Let's have the following design token and the component:
// design tokens
const tokens = {
scrollbarSize: "10px"
}
// common use in component
export const Scrollbar = styled.div`
height: ${tokens.scrollbarSize};
`;
From time to time we have to use those design tokens directly in some JS function for some calculations. For example how much to scroll with our viewport if we want to respect the size of the custom scrollbar component.
Theoretically, we can "fix it" in this dirty way:
// calculation
const someCalculation = someNumber + parseFloat(tokens.scrollbarSize) // parseFloat(tokens.scrollbarSize) => 10 (px)
But this is not OK, because in the case of using different units, like rem
this will not get the value we expect:
// design tokens
const tokens = {
scrollbarSize: "1rem"
}
// calculation
const someCalculation = someNumber + parseFloat(tokens.scrollbarSize) // parseFloat(tokens.scrollbarSize) => 1 (px)
Problem is that Javascript is using pixels only, so we probably have to create a custom function that could convert any unit to pixels. Something like calc()
in CSS, but implemented in Javascript.
const someCalculation = someNumber + calc(tokens.scrollbarSize) // parseFloat(tokens.scrollbarSize) => ~10 (px)
Any ideas on how to do it?
This issue must be a common use case in doing design systems. And if we force to use just pixels it's very limitating.
question from:
https://stackoverflow.com/questions/66062440/how-to-implement-css-calc-in-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…