callstack / linaria

Zero-runtime CSS in JS library
https://linaria.dev
MIT License
11.68k stars 417 forks source link

Styled Linaria Components #1219

Open jantimon opened 1 year ago

jantimon commented 1 year ago

Describe the feature

What do you think about an approach which would allow to toggle class names and inject css variables like this?

const Title = styled.h1<{ x: number; children: React.ReactNode }>`
  display: block;
  ${styleWhen(({ x }) => x % 2 === 0, `color: red;`)}
  position: relative;
  top: ${cssVar(({ x }) => `${x}px`)};
`;

It's totally possible with typescript and might work very well with the upcoming css nesting proposal:

https://codesandbox.io/s/yacijs-p0xt3m?file=/src/App.tsx:111-315

Motivation

This idea would allow to connect css classes with any complex logic.
The runtime code would only keep the logic and the class names.

Possible implementations

https://codesandbox.io/s/yacijs-p0xt3m?file=/src/App.tsx:111-315

Anber commented 1 year ago

The dynamic styling in Linaria is based on css variables, but they are suitable only for property values. So… it's just impossible to implement your approach.

Something similar has been discussed here https://github.com/callstack/linaria/issues/244

jantimon commented 1 year ago

as shown in the POC it is totally possible by pregenerating class names - soon we will have native css class nesting which would make that even easier

Anber commented 1 year ago

Your PoC requires parse styles to create a list of class names. It means that if we want to interpolate or wrap a styled component in another styled, we will have to evaluate its styles, whereas now we can just use a pre-generated class name. It is slow. However, we already do it in atomic. I'll keep this issue open for future discussion.

jantimon commented 1 year ago

thank you for reopening the discussion and for further insights why this might not be a good idea 👍

I guess you are right - one very hard problem might be the order when wrapping components - or do you see any further issues?

Anber commented 1 year ago

After giving it more consideration, I believe we can still utilize pre-generated class names for referencing and compositions. This will prevent us from having to do additional work during the evaluation stage. Therefore, your approach appears to be viable.