Skip to content

[RFC] Defining styles inline #534

Closed
Closed

Description

@nmn

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:

  1. Defining styles with stylex.create is too much ceremony for one-off styles
  2. stylex.create doesn't benefit for Prop type constrains when passing styles as props.
  3. Developer preference for more co-location.

Naming Bikeshed

There has been much discussion about what the function name for this API should be.

  1. stylex.inline - Slightly verbose, slightly unclear.
  2. stylex.atom - Terse but unclear
  3. stylex.createOne - Very verbose but clear
  4. stylex.make - Short and clear, but confusing alongside stylex.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:

  1. Increased maintenance burden - A bigger API is harder to maintain takes focus away from other improvements.
  2. Increased API surface area - Makes StyleX harder to understand
  3. Leads to less readable code - Enforcing all styles be defined in stylex.create arguably creates more readable and maintainable code in the long run at the cost of some minor inconvenience upfront.
  4. 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

  1. added
    enhancement
    on Apr 11, 2024
  2. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    stylex.inline

  3. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    stylex.atom

  4. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    stylex.createOne

  5. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    stylex.make

  6. zaydek commented on Apr 11, 2024

    @zaydek

    This is exciting. My only hesitation with inline is that it could unintentionally lead users to believe that pseudos are not supported. Something like atom makes 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.

  7. necolas commented on Apr 11, 2024

    @necolas
    Contributor

    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

  8. zaydek commented on Apr 11, 2024

    @zaydek

    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

    If flexibility is paramount would it not make sense to implement your concerns as ESLint warnings? The reality of not implementing inline means that users will defer to using inline styles rather than something that StyleX controls. I'd argue between those two choices, support for inline is 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.include for support for inline. I found I can lean into some kind of pattern like this (particularly with typography), when I want to compose styles:

    import * as stylex from "@stylexjs/stylex";
    
    export type ExtendProps = { extend?: stylex.StyleXStyles };
    
    export function Title({ extend, ...props }: ExtendProps & JSX.IntrinsicElements["div"]) {
      return <div {...props} {...stylex.props(styles.title, extend)} />;
    }

    Then I can simply use <Title extend={styles.foo} />. I imagine RSD has some way of making this simpler, still.

    Anyway, if StyleX makes inline or 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 inline also work in React Native? Another question would be, would this be possible to implement as a standalone package experiment?

  9. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    The proposed API would add significant maintenance complexity and needless surface area to StyleX.

    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.

    if StyleX makes inline or something like it a first-class primitive, I can imagine it being easily abused.

    This is another valid reason against adding this API. Although a bit subjective, I believe enforcing the usage of stylex.create for all styles results in more readable styles in the long run.

    would this be possible to implement as a standalone package experiment?

    This is possible and what I'm working towards. I don't want to bring this into "core" anytime soon.

    Does inline also work in React Native?

    Did you mean RSD? RN supports inline style objects. RSD does not support this API.

  10. zaydek commented on Apr 11, 2024

    @zaydek

    Did you mean RSD? RN supports inline style objects. RSD does not support this API.

    @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 inline unlocks, but given the choice, I think I'm indifferent. I already learned my lesson with stylex.include that I don't really need it, even though originally I thought I did. I suspect the same could be true for inline.

    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:

    The only concepts you need to understand in StyleX:

    1. Style Objects - apply them, merge them, use them conditionally whatever
    2. Variable Objects - use them within styles
    3. Themes - set values for variables on a UI sub-tree

    That’s it. Seriously.

    This is very good 'north star' for StyleX.

  11. nonzzz commented on Apr 11, 2024

    @nonzzz
    Contributor

    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

  12. nonzzz commented on Apr 11, 2024

    @nonzzz
    Contributor

    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 SpreadElement node. But I don't know if it's worth it.

  13. aspizu commented on Apr 11, 2024

    @aspizu
    Contributor
    1. Why can't you put style objects directly in the stylex.props call?
    <div {...stylex.props({display: 'flex', flexDirection: 'column'}, ...)}>
      ...
    </div>
    1. One way this feature could be abused is by creating a library of tailwind like utility inline styles.
    const flex = stylex.inline({display: 'flex'})
    const flexCol = stylex.inline({flexDirection: 'column'})
    
    <div {...stylex.props(flex, flexCol)}>
      ...
    </div>

    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.create stylesheet.

  14. nmn commented on Apr 11, 2024

    @nmn
    CollaboratorAuthor

    Why can't you put style objects directly in the stylex.props call?
    @aspizu This isn't feasible for a couple of reasons:

    1. It only works for styles being applied directly on an element and not props to custom components
    2. Since conditions can be used within stylex.props detecting inline styles without a function call wrapper can be error prone.
  15. necolas commented on Apr 11, 2024

    @necolas
    Contributor

    The reality of not implementing inline means that users will defer to using inline styles rather than something that StyleX controls

    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 within create().

    Then I can simply use <Title extend={styles.foo} />. I imagine RSD has some way of making this simpler, still.

    No need for a new prop name, we just pass styles down using the style prop.

  16. 14 remaining items

  17. nonzzz commented on May 21, 2024

    @nonzzz
    Contributor

    Let me explain what i did. The JSXAttribute is just translating JSXAttribute into props or attrs and combing it with create In the follow code block

    // input
    
    const Component = () => {
      return <div stylex={{ color: "red" }} />;
    };
    
    // output
    
    import { create, props } from "@stylexjs/stylex";
    
    const styles = create({
      xxHash: {
        color: "red",
      },
    });
    
    const Component = () => {
      return <div {...props(styles.xxHash)} />;
    };

    Back to topic. In my option is that inline is equivalent to create. So i extra them to the toplevel and translate them. Here is a simple example

    // input
    
    import { create, props } from "@stylexjs/stylex";
    
    const styles = create({
      test: {
        // ... a long style sheet
      },
    });
    
    const Component = () => {
      return <div {...props(styles.test, inline({ position: "static" }))} />;
    };
    
    // output
    
    import { create, props } from "@stylexjs/stylex";
    
    const styles = create({
      test: {
        // ... a long style sheet
      },
    });
    
    const _styles = create({
      xxHash: {
        position: "static",
      },
    });
    
    const Component = () => {
      return <div {...props(styles.test, _styles.xxHash)} />;
    };
  18. zaydek commented on May 21, 2024

    @zaydek

    @nonzzz Is that a custom Vite plugin? What's doing the translation for you? That's really interesting.

  19. nonzzz commented on May 21, 2024

    @nonzzz
    Contributor

    @zaydek Yeah, I create an babel-plugin to do this. plugin

  20. zaydek commented on May 21, 2024

    @zaydek
    Amazing. Thanks!
  21. zaydek commented on May 21, 2024

    @zaydek

    Just to follow up, @nonzzz did manage to implement inline as 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

  22. necolas commented on May 21, 2024

    @necolas
    Contributor

    Splitting the component into smaller ones can also improve readability

    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 pretty obvious that libraries like Tailwind are popular because they don't force you to think, but they do lead to pretty obfuscated code that gets gnarlier the more the project grows.

    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 util example 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.

    <div stylex={{ ... }} />

    How is that going to work for custom components, which may or may not use stylex (or an alternative less likely to clash with the stylex import) 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 create API'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.

  23. zaydek commented on May 25, 2024

    @zaydek

    I took some encouragement from this reply and wanted to double down on a simple approach: https://gist.github.com/zaydek/6a3abb586c6bb82405d4f4b9c4ce7ee2.

    The util example is natively supported by StyleX with the existing APIs, and results in less JS code in bundles.

    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 utils pattern 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 CSSProperties type for the specified property:

    export const u = stylex.create({
      accentColor: (value: CSSProperties["accentColor"]) => ({ accentColor: value }),
      alignContent: (value: CSSProperties["alignContent"]) => ({ alignContent: value }),
      alignItems: (value: CSSProperties["alignItems"]) => ({ alignItems: value }),
      alignSelf: (value: CSSProperties["alignSelf"]) => ({ alignSelf: value }),
      alignTracks: (value: CSSProperties["alignTracks"]) => ({ alignTracks: value }),
      ...
    });

    Looks like this, you probably always want to specify utils last.

    <header {...stylex.props(dialogStyles.header, u.paddingBlockEnd(0))}>
      <div {...stylex.props(dialogStyles.hero, u.alignSelf("center"))} />
      <h1 {...stylex.props(typographyStyles.title, u.textAlign("center"))}>
        Are you sure you want to continue? This action is irreversible.
      </h1>
    </header>

    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.

  24. nmn commented on Jun 23, 2024

    @nmn
    CollaboratorAuthor

    This is simpler than my previous implementation because it doesn't hard code what values you can use and defers to the CSSProperties type for the specified property:

    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.

  25. nonzzz commented on Jun 24, 2024

    @nonzzz
    Contributor

    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?

  26. nmn commented on Jun 30, 2024

    @nmn
    CollaboratorAuthor

    @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.

  27. frattaro commented on Jul 19, 2024

    @frattaro

    Could you make a jsx parser to pull out inline styles? like

    <div stylex={{
      borderColor: "red"
    }}>
      My div
    </div>

    that then pulls out the data, throws it into stylex.create and links w/stylex.props?

  28. nmn commented on Jul 21, 2024

    @nmn
    CollaboratorAuthor
  29. necolas commented on Sep 8, 2024

    @necolas
    Contributor

    Moving this to Discussions

  30. locked and limited conversation to collaborators on Sep 8, 2024
  31. converted this issue into a discussion #682 on Sep 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions