Repository navigation
Description
Describe the feature request
Motivation
It has often been suggested that it should be possible to define styles inline. There are many reasons why such a feature might be desirable:
- Defining styles with
stylex.createis too much ceremony for one-off styles stylex.createdoesn't benefit for Prop type constrains when passing styles as props.- Developer preference for more co-location.
Naming Bikeshed
There has been much discussion about what the function name for this API should be.
stylex.inline- Slightly verbose, slightly unclear.stylex.atom- Terse but unclearstylex.createOne- Very verbose but clearstylex.make- Short and clear, but confusing alongsidestylex.create.
I would love feedback to help make a decision here. Please leave a 👍 on one of the first four comments below to register your vote.
Proposed API
Assuming the stylex.inline name, the usage would still be what you would expect from a hypothetical stylex.createOne function. i.e. Instead of defining:
const styles = stylex.create({
base: {color: 'red'}
});You'd be able to do:
const red = stylex.inline({color: 'red'})Of course, it would also be possible to use this function call directly
with a stylex.props() call or a component prop.
<div {...stylex.props(
stylex.inline({color: 'red'})
)} />;
<MyButton styles={stylex.inline({color: 'red'})} />;Since the function accepts an object, it would be possible to define a whole object of styles.
stylex.inline({
color: 'red',
backgroundColor: 'black',
textDecoration: {
default: 'none',
':hover': 'underline',
':focus-visible': 'underline',
},
...
})It would be possible to apply the styles conditionally:
<MyButton styles={[
isRed && stylex.inline({color: 'red'}),
isBlue && stylex.inline({color: 'blue'}),
]} />;And it would be be possible to reduce verbosity with the import.
import {inline as _} from '@stylexjs/stylex';
<MyButton styles={[
isRed && _({color: 'red'}),
isBlue && _({color: 'blue'}),
]} />;Constrains and Considerations
One of the biggest concerns when implementing this feature is dynamic styles. stylex.create enforces the usage of functions to define styles that can be dynamic. However, doing the same with the new API would be awkward.
<MyButton styles={stylex.inline((color) => ({color}))(dynamicColor)} />;Instead, the developer expectation would be the ability to use dynamic values directly within the objects
<MyButton styles={stylex.inline({color: dynamicColor})} />;This has two issues:
One: It is difficult to implement this correctly and detect all the ways the value of the styles may be known statically. We don't accidentally want to generate dynamic styles when the styles are actually statically know.
Two: It makes it far too easy to define dynamic styles. One of the reasons for requiring functions within stylex.create to define dynamic styles is that the vast majority of use-cases should not depend on dynamic styles. Instead conditional styles, and compositions should be sufficient. Requiring functions makes the need for truly dynamic styles explicit and enforces intentionality. Automatically generating dynamic styles with the new API would encourage patterns that would lead to bloated and slower styles.
Therefore, the current proposal would disallow the usage of dynamic styles within the new API entirely. Using dynamic values of styles within a stylex.inline() (or whatever we call it) call would be a compile-time error. It would still be possible to define constants and use them, but the amount expressivity possible would be limited by the capabilities of the compiler.
Reasons against implementing this API
There are also many great reasons why this API should not implemented. To name a few:
- Increased maintenance burden - A bigger API is harder to maintain takes focus away from other improvements.
- Increased API surface area - Makes StyleX harder to understand
- Leads to less readable code - Enforcing all styles be defined in
stylex.createarguably creates more readable and maintainable code in the long run at the cost of some minor inconvenience upfront. - The lack of dynamic styles in the API could become a pitfall.
Thoughts?
I'm posting this proposal early to gather feedback and help improve this idea before implementation.
To vote for the API name, simply react with a 👍 on one of the first four comments on this issue. For any feedback about how the API works, respond with a comment.
Activity
nmn commentedon Apr 11, 2024
stylex.inlinenmn commentedon Apr 11, 2024
stylex.atomnmn commentedon Apr 11, 2024
stylex.createOnenmn commentedon Apr 11, 2024
stylex.makezaydek commentedon Apr 11, 2024
This is exciting. My only hesitation with
inlineis that it could unintentionally lead users to believe that pseudos are not supported. Something likeatommakes sense to me for this reason. Then you can think of StyleX as a composition of Style atoms.Either way, excited for this to land.necolas commentedon Apr 11, 2024
The proposed API would add significant maintenance complexity and needless surface area to StyleX. We have a design principle in React which is to only have one way to do things, even if it is more verbose in some cases. Defining styles directly on an element only looks readable in the most simple of cases. We already have 3 functions to resolve styles (one is legacy) and 2 ways to merge them (include and arrays). We could be simplifying the API rather than adding more ways to do the same thing
zaydek commentedon Apr 11, 2024
If flexibility is paramount would it not make sense to implement your concerns as ESLint warnings? The reality of not implementing
inlinemeans that users will defer to using inline styles rather than something that StyleX controls. I'd argue between those two choices, support forinlineis probably preferable over users implementing inline styles themselves. Of course, users will probably still implement inline styles (unintentionally), but at least this way there's a small, incremental path to refactoring their code which is still correct.Another implementation would be having strict mode, which disciplines developers to write code one way, like @necolas is suggesting. But not having a need for strict mode is even better.
For what it's worth I'd be willing to give up
stylex.includefor support forinline. I found I can lean into some kind of pattern like this (particularly with typography), when I want to compose styles:Then I can simply use
<Title extend={styles.foo} />. I imagine RSD has some way of making this simpler, still.Anyway, if StyleX makes
inlineor something like it a first-class primitive, I can imagine it being easily abused. A lot of people would love to implement styles orthogonal to the way they write Emotion CSS and Tailwind, which is usually more productive in the short term and easily becomes a clusterfuck of unreadable code down the road.For this reason, the StyleSheet API, although somewhat ceremonious at times, reinforces the idea that correctness is about narrowing decisions, which I certainly appreciate. A little bit of pain up front can be worth if it if it narrows the overall complexity space of what you're trying to achieve.
@nmn Does
inlinealso work in React Native? Another question would be, would this be possible to implement as a standalone package experiment?nmn commentedon Apr 11, 2024
I share this concern. I have received repeated requests for something on these lines and so I'm trying to gather feedback to see if makes sense. The "Constrains & Considerations" section also describes some limitations that make me way of implementing this API.
@zaydek This RFC should not yet be considered as something we're about to land. This issue exists to gather feedback. There are still many reasons against doing this. The benefits would need to great outweigh those downsides.
This is another valid reason against adding this API. Although a bit subjective, I believe enforcing the usage of
stylex.createfor all styles results in more readable styles in the long run.This is possible and what I'm working towards. I don't want to bring this into "core" anytime soon.
Did you mean RSD? RN supports inline style objects. RSD does not support this API.
zaydek commentedon Apr 11, 2024
@nmn I actually meant RN but I didn't know RN supports inline style objects already. Also, it sounds like RSD is effectively strict mode for StyleX so that seems aligned.
Thanks for clarifying this is not 'about to land' as I assumed. FWIW everytime I've tried to write inline style-based UIs first it's always come back to haunt me. It tooks some getting used to StyleX's StyleSheet approach but honestly it's really just like CSS Modules but typed and colocated. Now it's a no brainer for me to use StyleX and I love the API. So a little friction is fine and totally valid if you're trying to do something different, which StyleX is.
Experiments help gather information, so perhaps there's some opportunity that
inlineunlocks, but given the choice, I think I'm indifferent. I already learned my lesson withstylex.includethat I don't really need it, even though originally I thought I did. I suspect the same could be true forinline.I do use inline styles alongside StyleX at present, but it's simply because I'm too lazy. It's probably only 2-5% so it doesn't really matter either way. I genuinely appreciate there are so few ways to do things in StyleX, as this tweet reads:
This is very good 'north star' for StyleX.
nonzzz commentedon Apr 11, 2024
I have been using stylex for a long time,To be honest, the current method is too cumbersome for react, So i mad a babel-plugin for this problem. test-case
You might notice i'm using
JSXAttributes, In my opinion this is simpler to use.inspired by style9-jsx-prop
nonzzz commentedon Apr 11, 2024
AFAIK. The dynamic values are very difficult to calculate, So i have to treat each attribute as a token. But i don't think is a good way. I try to merge static token to a whole object until the token meet dynamic or
SpreadElementnode. But I don't know if it's worth it.aspizu commentedon Apr 11, 2024
stylex.propscall?I feel like 2 can be solved, if only 1 is allowed. if you want to reuse styles, then you should put them in a
stylex.createstylesheet.nmn commentedon Apr 11, 2024
stylex.propsdetecting inline styles without a function call wrapper can be error prone.necolas commentedon Apr 11, 2024
Is the proposed name (
inline) is confusing you (or me)? This isn't an RFC for adding what is traditionally referred to as "inline styles", we already support those using the function syntax withincreate().No need for a new prop name, we just pass styles down using the
styleprop.14 remaining items
nonzzz commentedon May 21, 2024
Let me explain what i did. The
JSXAttributeis just translatingJSXAttributeintopropsorattrsand combing it withcreateIn the follow code blockBack to topic. In my option is that
inlineis equivalent tocreate. So i extra them to the toplevel and translate them. Here is a simple examplezaydek commentedon May 21, 2024
@nonzzz Is that a custom Vite plugin? What's doing the translation for you? That's really interesting.
nonzzz commentedon May 21, 2024
@zaydek Yeah, I create an babel-plugin to do this. plugin
zaydek commentedon May 21, 2024
Amazing. Thanks!
zaydek commentedon May 21, 2024
Just to follow up, @nonzzz did manage to implement
inlineas a Vite plugin (and it works!). I setup a simple repo to provide footing for anyone who wants to experiment with this. Exciting times.https://github.com/zaydek/stylex-extend
necolas commentedon May 21, 2024
At the cost of performance. React components have a non-trivial performance cost. In the future, maybe the React Compiler can flatten components defined like this within a single file.
It's not just that. Tailwind can lead to large amounts of "inline" class names that make the structure and behavior of the tree very hard to read, because the elements and events are lost within a sea of styles. This is less often a problem with Flutter and SwiftUI code, because they provide components for features that are part of the CSS API on web. And frankly we tend to implement more complex, responsive components on web too. Styles - like event handlers - are generally more portable and readable when they're not defined inline on elements.
The
utilexample is natively supported by StyleX with the existing APIs, and results in less JS code in bundles. I don't think the use case of quick-and-dirty prototypes justifies the complexity of adding APIs that do the same thing, often worse, than what already exists. FWIW, we've spent half a decade building all of Meta's web products with StyleX and never really had a need or request for the API proposed here.How is that going to work for custom components, which may or may not use
stylex(or an alternative less likely to clash with thestyleximport) as a prop name? Another issue with pretending to users that styles are just plain objects is that they might introduce runtime patterns for manipulating or reading styles that cannot be preserved when they're processed by the compiler. The type system would also struggle to cover all the cases we can currently throw errors for.We see a similar problem in the existing RN ecosystem, where a change to the
createAPI's return value a few years ago allowed people to read style values in the render loop - it now essentially prevents potential build-time optimizations to styles being introduced, and allows for perf anti-patterns like flattening style arrays in render.zaydek commentedon May 25, 2024
I took some encouragement from this reply and wanted to double down on a simple approach: https://gist.github.com/zaydek/6a3abb586c6bb82405d4f4b9c4ce7ee2.
If anyone's struggling with wanting to be able to more easily define inline styles in StyleX and doesn't want to depend on plugins, I've been using a simplified version of the
utilspattern to great effect. You wouldn't want to use it everywhere because it creates CSS variables for all properties, but if there's one or two properties you'd rather not model a style object for, I find this to be very ergonomic.This is simpler than my previous implementation because it doesn't hard code what values you can use and defers to the
CSSPropertiestype for the specified property:Looks like this, you probably always want to specify
utilslast.I found StyleX to be a lot easier having something like this in my back pocket, particularly for prototyping and scaffolding ideas before I'm ready to name them.
nmn commentedon Jun 23, 2024
This is worse for performance as when you use dynamic styles with functions, you're relying on inline styles to set variables in addition to setting classNames.
nonzzz commentedon Jun 24, 2024
A friendly ping. @nmn This RFC hasn't been updated for a long time. FWIW, I implemented it and using for a long time. I found it very useful for simple cases.
Is there any further information or updates planned for the RFC?
nmn commentedon Jun 30, 2024
@nonzzz The current decision is to not implement this in StyleX itself in order to keep the API small. But the issue remains open as a central place for people to be able to chime in with their opinions.
frattaro commentedon Jul 19, 2024
Could you make a jsx parser to pull out inline styles? like
that then pulls out the data, throws it into
stylex.createand links w/stylex.props?nmn commentedon Jul 21, 2024
@frattaro Look at https://github.com/zaydek/stylex-extend
necolas commentedon Sep 8, 2024
Moving this to Discussions