Giter VIP home page Giter VIP logo

stylex's Introduction

StyleX · GitHub license npm version tests PRs Welcome

StyleX is a JavaScript library for defining styles for optimized user interfaces.

Documentation

Documentation Website

Documentation for individual packages can be found in their respective README files. Start with @stylexjs/stylex.

Example

Here is a simple example of StyleX use:

import * as stylex from '@stylexjs/stylex';

const styles = stylex.create({
  root: {
    padding: 10,
  },
  element: {
    backgroundColor: 'red',
  },
});

const styleProps = stylex.props(styles.root, styles.element);

Development

This is the development monorepo for StyleX.

Structure

Tasks

First, npm install the npm workspace.

  • build
    • Use npm run build to run the build script in every package.
    • Use npm run build -w <package-name> to run the build script for a specific package.
  • test
    • Use npm run test to run tests for every package.
    • Use npm run test -w <package-name> to run the test script for a specific package. More details can be found in the contributing guide below.

Contributing

Development happens in the open on GitHub and we are grateful for contributions including bug fixes, improvements, and ideas.

Code of Conduct

This project expects all participants to adhere to Meta's OSS Code of Conduct. Please read the full text so that you can understand what actions will and will not be tolerated.

Contributing Guide

Read the contributing guide to learn about our development process, how to propose bug fixes and improvements, and how to build and test your changes.

Architectural Principles

Before proposing a change or addition to the StyleX API, you should familiarize yourself with the goals and architectural principles of the project.

License

StyleX is MIT licensed.

stylex's People

Contributors

38elements avatar aayushchugh avatar abrahamvphilip avatar afterdie avatar alex-page avatar antoinebrault avatar b4h0-c4t avatar back2lobby avatar benahammond avatar cut0 avatar deining avatar jta26 avatar kevintyj avatar liby avatar necolas avatar nedjulius avatar nelsonuprety1 avatar nmn avatar nonzzz avatar purohitdheeraj avatar qingqishi avatar rayan1810 avatar rosko avatar shafayetahmad avatar tounsoo avatar umutbozdag avatar veksa avatar yash-singh1 avatar yousoumar avatar zetavg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stylex's Issues

Vite plugin

It would be nice to have a Vite plugin. I tried the rollup plugin with a fresh React + Vite and got an error:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import stylex from '@stylexjs/rollup-plugin'

export default defineConfig({
  plugins: [react(), stylex()],
})

Error:

[vite] Internal server error: /Users/walmartwarlord/tmp/react-stylex-test/src/index.css: Unexpected token (1:0)

> 1 | :root {
    | ^
  2 |   font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
  3 |   line-height: 1.5;
  4 |   font-weight: 400;
  Plugin: rollup-plugin-stylex
  File: /Users/walmartwarlord/tmp/react-stylex-test/src/index.css:1:0
  1  |  :root {
     |  ^
  2  |    font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
  3  |    line-height: 1.5;
      at constructor (/Users/walmartwarlord/tmp/react-stylex-test/node_modules/.pnpm/@[email protected]/node_modules/@babel/parser/lib/index.js:356:19)

Edit: Cleaned up the fresh project; dev now runs successfully. However, running build leads to a different error.:

import stylex from '@stylexjs/stylex'

const s = stylex.create({
  main: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 10,
    paddingTop: 20,
  }
})

function App() {
  return (
    <main className={stylex(s.main)}>
      <h1>Hello</h1>
    </main>
  )
}
vite v5.0.5 building for production...
✓ 0 modules transformed.
[rollup-plugin-stylex] /Users/walmartwarlord/tmp/react-stylex-test/index.html: Unexpected token (1:1)

> 1 | <!doctype html>
    |  ^
  2 | <html lang="en">
  3 |   <head>
  4 |     <meta charset="UTF-8" />
file: /Users/walmartwarlord/tmp/react-stylex-test/index.html:1:1
error during build:
SyntaxError: /Users/walmartwarlord/tmp/react-stylex-test/index.html: Unexpected token (1:1)

> 1 | <!doctype html>
    |  ^
  2 | <html lang="en">
  3 |   <head>
  4 |     <meta charset="UTF-8" />
    at constructor (/Users/walmartwarlord/tmp/react-stylex-test/node_modules/.pnpm/@[email protected]/node_modules/@babel/parser/lib/index.js:356:19)

Typing mismatch for fontWeight property (maybe others?)

The problem

fontWeight has to be a string as per TTokens, but cannot be a string as per StyleXCSSTypes.

How to reproduce

I want to do:

// tokens.stylex.ts

import * as stylex from '@stylexjs/stylex';

export const typo = stylex.defineVars({
  fontWeight: '400',
});

// fontWeight has to be a string, as per @stylexjs/stylex/lib/StyleXTypes.d.ts:177:
// type TTokens = Readonly<{
//   [key: string]: string | { [key: string]: string };
// }>;
// MyComponent.tsx

import type { StyleXStyles } from '@stylexjs/stylex';
import * as stylex from '@stylexjs/stylex';

type Styles = {
  container: StyleXStyles;
};

const styles = stylex.create({
  container: {
    fontWeight: typo.fontWeight,
  },
});

// ...

BUT :

// @stylexjs/stylex/lib/StyleXCSSTypes.d.ts

// this cannot be an arbitrary string like '400'
type fontWeight =
  | 'inherit'
  | 'normal'
  | 'bold'
  | 'bolder'
  | 'lighter'
  | 100
  | 200
  | 300
  | 400
  | 500
  | 600
  | 700
  | 800
  | 900;

So I got:

Type 'StyleXClassNameFor<"fontWeight", string>' is not assignable to type 'StyleXClassNameFor<"fontWeight", Readonly<"initial" | "inherit" | "unset" | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | null | undefined>>

Search bar only show's CMD+K on every platform

We should implement a timer that show's ctrl or CMD every 10 seconds. First it show Ctrl then hide the Ctrl and show the CMD which will give a better user experience.

Kindly assign this to me. So that I can implement this..

image

No TypeScript autocomplete for CSS properties when authoring styles in Next.js application

The problem
No autocomplete when writing styles inside stylex.create in Next.js application.

How to reproduce

Steps to reproduce:

  1. Open official Next.js playground: https://stackblitz.com/edit/stylex-next?file=README.md
  2. Try to write styles inside stylex.create({})
Screenshot 2023-12-06 at 16 11 45 Screenshot 2023-12-06 at 16 14 19

Expected behavior

Get suggestions and autocomplete for CSS properties (e.g. display, position, gridColumnStart, and possible values when it's possible (e.g. fixed, absolute, etc for the position property).

Environment (include versions). Did this work in previous versions?
Haven't worked at least from 0.2.* betas.

I think the problem is in the way UserAuthoredType in stylex/packages/stylex/src/StyleXTypes.d.ts is declared:

type UserAuthoredStyles = { [key: string]: unknown }; 

If the definition of UserAuthoredStyles is changed to this (for example), everything works in terms of autocomplete

type UserAuthoredStyles = CSSPropertiesWithExtras;

But the usage of media queries is broken (because CSSPropertiesWithExtras does not cover them).

Update:
@kevintyj suggested a workaround (#68 (comment)) :

type UserAuthoredStyles = CSSPropertiesWithExtras | { [key: string]: unknown };
Which accepts all other nested behaviors, even with nested propertie:

Support dark mode by class

Is your feature request related to a problem? Please describe.

My app set dark mode with <html data-mode="dark">.
I don't think there is a way to use stylex to generate a css style like :is([data-mode="dark"] .myclass) { ... }.

Describe a solution you'd like
Describe alternatives you've considered
Additional context

Intellisense when defining styles in `create` function

Is your feature request related to a problem? Please describe.
When defining styles for stylex.create I'd like TS intellisense for common CSS values for each property, such as block for display. stylex.keyframes seems to support this already.

Describe a solution you'd like
For the param type within create instead of type UserAuthoredStyles = { [key: string]: unknown }; set it to type UserAuthoredStyles = { [key: string]: CSSProperties }; (from @stylexjs/stylex/lib/StyleXCSSTypes)

Describe alternatives you've considered
Right now this seems to work:

import type { CSSProperties } from '@stylexjs/stylex/lib/StyleXCSSTypes';
import * as stylex from '@stylexjs/stylex';

const namespaces: Record<string, CSSProperties> = {
    base: {
      display: 'inline-block',
    }
};
const styles = stylex.create(namespaces);

Additional context

Comparison with existing solutions

Hello! There is a lack of comparison with existing styling solutions.

I use Linaria in my projects and don't understand how stylex could be better.

For example a syntax.

Stylex example from documentation

import * as stylex from '@stylexjs/stylex';

const styles = stylex.create({
  foo: {
    color: 'red',
  },
  bar: {
    backgroundColor: 'blue',
  },
});

function MyComponent({ style }) {
  return <div {...stylex.props(styles.foo, styles.bar, style)} />;
}

Same example with Linaria

import { styled } from '@linaria/react';

const Container = styled.div`
  color: red;
  background-color: blue;
`;

function MyComponent({ style }) {
  return <Container style={style} />;
}

Linaria syntax looks shorter and neater, especially if the component tree is larger.

Why were existing solutions not enough for you and this library was created? Why is it better?

[Webpack Plugin] Support add [hashcontent] to file name.

Is your feature request related to a problem? Please describe.
Currently with webpack config like below, a file with the name styles.css is created after the build.
image

Describe a solution you'd like
I'm expecting a hashcontent will be added to the file name according to the webpack output.filename config to resolve the caching issue.

Describe alternatives you've considered
Or can @stylexjs/webpack-plugin support add [hashcontent] to the filename config? like this:

new StylexPlugin({
      filename: 'styles.[hashcontent].css',
}),

Variants API Support

Is your feature request related to a problem? Please describe.

We are considering StyleX for our design system. We are moving away from Stitches.js. However there are a lot of features of Stitches.js we like such as their "variants" API and "$<token" syntax.

Describe a solution you'd like
It's not really a problem or a feature request. Curious if the maintainers know if it's possible with StyleX to build something similar either internally or externally atop of StyleX's API.

Describe alternatives you've considered

Additional context

Inconsistency in border shorthands

The problem

I've encountered an issue with the use of border shorthands in the Stylex package. While the ESLint rule provided by Stylex seems to prohibit the use of shorthand properties for borders, there's an inconsistency in how these rules are applied and enforced in practice.

I used border shorthand properties (borderTop, borderLeft, borderRight, borderBottom) in my Stylex code as follows:

const s = stylex.create({
  test: {
    borderTop: '5px solid blue',
    borderLeft: '5px solid blue',
    borderRight: '5px solid blue',
    borderBottom: '5px solid blue',
  },
});

When running npm run lint, the following errors are reported:

./app/page.tsx
9:5  Error: The 'borderTop' property is not supported. Use the 'borderTopWidth', 'borderTopStyle' and 'borderTopColor' properties instead.  @stylexjs/valid-styles
10:5  Error: The 'borderLeft' property is not supported. Use the 'borderLeftWidth', 'borderLeftStyle' and 'borderLeftColor' properties instead.  @stylexjs/valid-styles
11:5  Error: The 'borderRight' property is not supported. Use the 'borderRightWidth', 'borderRightStyle' and 'borderRightColor' properties instead.  @stylexjs/valid-styles
12:5  Error: The 'borderBottom' property is not supported. Use the 'borderBottomWidth', 'borderBottomStyle' and 'borderBottomColor' properties instead.  @stylexjs/valid-styles

However, in the rendered output, borderTop, borderRight, and borderBottom are actually applied and rendered correctly, but borderLeft is not.

截屏2023-12-11 下午7 23 03

How to reproduce

I have created a StackBlitz reproduction of this issue, which can be found here: https://stackblitz.com/edit/stylex-next-4kubjy?file=app%2Fpage.tsx

Expected behavior

I would expect the ESLint rule to either allow all border shorthand properties or to consistently enforce the prohibition across all of them. The current behavior where some properties work despite the ESLint errors, and others do not, is confusing.

Could you please provide some clarification on this behavior? Is this an intended feature or an oversight in the ESLint rule implementation?

Thank you for your assistance.

Environment (include versions). Did this work in previous versions?

Mac and Linux, v0.3.0 of stylex, latest Next.js.

docs: Missing readme docs for `@stylexjs/nextjs-plugin`

The README file for @stylexjs/nextjs-plugin only contains ... and is missing the actual docs

Assign the issue to me and I can take reference from actual docs and write it into readme

image image

edit:

docs for @stylexjs/rollup-plugin and @stylexjs/webpack-plugin are also missing

Themed vars are not propagated

The problem

Themes are applied only on first level.

themed(varA) -> component using varA : varA is themed

themed(varA) -> varB = varA -> component using varB : varB is not themed

How to reproduce

// colorScheme.stylex.ts

import * as stylex from '@stylexjs/stylex';

export const colorScheme = stylex.defineVars({
  primary: 'red',
});
// myComponentVars.stylex.ts

import * as stylex from '@stylexjs/stylex';
import { colorScheme } from './colorScheme.stylex';

export const myComponentVars = stylex.defineVars({
  text: colorScheme.primary, // theme not applied here
});
// MyComponent.tsx

import React from 'react';
import { colorScheme } from './colorScheme.stylex';
import { myComponentVars } from './myComponentVars.stylex';

const theme = stylex.createTheme(colorScheme, {
  primary: 'green',
});

const styles = stylex.create({
  container: {
    color: colorScheme.primary, // <- theme is applied (output green)
    color: myComponentVars.text, // <- theme is not applied (output red)
  },
});

export const MyComponent = () => <div {...stylex.props(styles.container, theme)}>TEXT</div>;

Expected behavior

Theme should be applied through myComponentVars.text.

The idea behind this is to allow changing all colors globally (by theming colorScheme.stylex.ts), or only component colors (by theming myComponentVars.stylex.ts).

Footer links becomes column too soon

Footer container links that contain develop, explore, participate and other becomes column too soon it should be totally response first it becomes 2 and then 1 which is good according to all screen sizes.

We can easily fix this by adding more media queries and setting properties according to this.

I can easily fix this. Kindly assign this to me.

image

Usage with Server Components and React Native

Hello,

I have two questions regarding StyleX, and I apologise if this is not the correct way to ask them.

1st question: StyleX + Server Components

I couldn't find any detailed information about usage of StyleX in React Server Components.

I've found this in the docs:

The design of the theming APIs in StyleX are directly inspired by React's Context APIs. Variables are defined with default values similar to how React Contexts are created, and themes can be created to “provide” different values for these variables for UI sub-trees.

which implies that StyleX might have the same issue as Styled Components when it comes to React Server Components, and that doesn't seem right.

I've found one Jack Herrington's article that states that the usage is possible, but it doesn't clearly state that all features will work as expected.

I've seen your NextJS example but that still doesn't fully answer my question.

Will all the StyleX features work without restrictions in all React components?


2nd question: StyleX + React Native

Same question as before, does it work, what are the constrains etc...

Thanks.

Import CSS Modules styles into StyleX

Describe a solution you'd like:
CSS Modules style sheet import into StyleX structure to modify and it on a fly and take instant result.
One of the coolest feature which provided StyleX is style compilation in JS, It is useful when calculation of our style runs in JS. We need it for in such cases as animation.

Seeing a bunch of `:not(#\#)` when building css for the `apps/webpack-example`

The problem
I am evaluating this tool for usage and I noticed a bunch of erroneous css selectors that seemed odd.
This is the output css I am seeing when running basic example webpack implementation.

@keyframes xgnty7z-B{0%{opacity:.25;}100%{opacity:1;}}
.x1oz5o6v:hover:not(#\#):not(#\#){background:red}
.xeuoslp:not(#\#):not(#\#):not(#\#){animation-name:xgnty7z-B}
.x1lliihq:not(#\#):not(#\#):not(#\#){display:block}
.x78zum5:not(#\#):not(#\#):not(#\#){display:flex}
.x1hm9lzh:not(#\#):not(#\#):not(#\#){margin-inline-start:10px}
.x1egiwwb:not(#\#):not(#\#):not(#\#):not(#\#){height:500px}
.xlrshdv:not(#\#):not(#\#):not(#\#):not(#\#){margin-top:99px}
.xh8yej3:not(#\#):not(#\#):not(#\#):not(#\#){width:100%}
.x3hqpx7:not(#\#):not(#\#):not(#\#):not(#\#){width:50%}%

How to reproduce
Steps to reproduce:

  • Checkout the repo
  • npm install in both root and in apps/webpack-example
  • run npm run build
  • run cat .build/styles.css

Expected behavior
I am not 100% sure the expected output here but I would assume it should have less if not none :not selectors and if there are :not() selectors they should have an actual id they are trying to select on.

Environment (include versions). Did this work in previous versions?
Not sure about previous versions but I am running on mac OSX and I just checked the repo out today this is my current SHA
b32b183447c41e11672a200b3f04328cfc895935

Using Monorepo packages in a Next.JS app

Side point, genuinely excited for this project as soon as I heard about it from Theo.

The problem
I know this library is new and not all edge cases have been covered. However, I am trying to use styleX within a pnpm package. Is this a covered use case or a future one? 🤔

I have two pnpm repos that I've tried this with:

  1. a project I'm working on and sadly it's too complex to come up with a simple repo to showcase. But when I instantiate styles.create and build the package, I get the following error:

Error: Unsupported Server Component type: undefined

Without using stylex, the component builds correctly and is able to be imported by the nextjs app just fine.

  1. I'm cloning create-t3-turbo (for a basic pnpm setup) and removing many unused things just to get it working to show the issue.

When I launch nextjs:

../../packages/ui/src/button/button.tsx:21:6
Syntax error: Unexpected token, expected ","

  19 |   return (
  20 |     <button
> 21 |       {...stylex.props(styles.base)}
     |       ^
  22 |       onClick={() => alert(`Hello from your ${appName} app!`)}
  23 |     >
  24 |       {children}

Again, if I remove stylex (and the onClick) there is no issue the button renders.

How to reproduce

  1. clone: https://github.com/paulm17/stylex
  2. pnpm i
  3. pnpm run dev

Expected behavior
should be able to run both as a package and then when built and finally when on npmjs.


Please let me know if I have not followed any documentation or have done something incorrectly!

Many thanks for this library!

Can't get the project to run locally on Windows

Node version: v18.18.1
NPM: 9.8.1

Steps followed:

  • Forked the repository
  • Ran npm install in the root directory
  • Ran npm start -w docs

image

Error: Cannot find package 'C:\Users\Kevin\Documents\stylex\node_modules\@stylexjs\babel-plugin\' imported from C:\Users\Kevin\Documents\stylex\apps\docs\babel-virtual-resolve-base.js

Am I missing a step? It seems every command I try (build) results in some sort of error.

https://github.com/facebook/stylex/blob/main/.github/CONTRIBUTING.md

esbuild plugin

Is your feature request related to a problem? Please describe.
I use esbuild to build my web apps, and need stylex to generate the css for me.

Describe a solution you'd like
esbuild plugin

Describe alternatives you've considered
Reverting to webpack again which I don't want.

Set CSS rule priority based on media query break points

First of all, I just want to say "Awesome work". I have been looking forward to using Stylex since 2021 😃.

Is your feature request related to a problem? Please describe.
I have the below styles.

const styles = stylex.create({
   foo: {
      "@media (min-width: 10px)": {
         color: "red"
      },
      "@media (min-width: 20px)": {
         color: "green"
      }
   }
});

I am expecting

"@media (min-width: 20px)": {
  color: "green"
}

to be placed after

"@media (min-width: 10px)": {
      color: "red"
}

in the sheet.

However, the 👆 code gets babel transformed to

stylex.inject("@media (min-width: 10px){.xl9lbu0.xl9lbu0{color:red}}", 3200);
stylex.inject("@media (min-width: 20px){.xwdmb1y.xwdmb1y{color:green}}", 3200);

These two CSS rules have the same priority, which means the order of these two rules is indeterministic.

Describe a solution you'd like
When we calculate property property, can we consider the breakpoint value from media atrule?

Describe alternatives you've considered
I cannot think of anything alternative.

Additional context
I've raised a similar question in Compiled CSS-in-JS. atlassian-labs/compiled#1567

Copy to ClipBoard option not working properly for Installation Command

The problem
When I click the option of copy to clipboard for the stylex installation command.
image

  • It picks the $ sign also and when I copy it in the terminal, it does not work directly, first I have to remove the $ sign and then the command works.
    image
  • That is the same behavior with other plug-in installations.

How to reproduce
Go to the Installation section, click on the copy to Clipboard Option, and then CTRL+V in the terminal and press enter error will come.

Expected behavior
The commands should run directly without having to remove the $ manually every time.

Environment (include versions). Did this work in previous versions?
Ubuntu Linux

Be able to provide an extra class to stylex.props()

Is your feature request related to a problem? Please describe.

I need to assign my container an extra class, let's say 'my-custom-class'.

Describe a solution you'd like

<div {...stylex.props(styles.container, 'my-custom-class')} />

To be compiled to:

<div class="x1vqgdyp my-custom-class" />

Of course, I cannot do:

<div {...stylex.props(styles.container)} className='my-custom-class' />

Describe alternatives you've considered

No one.

Choose cascade layer usage in bundler plugins

Is your feature request related to a problem? Please describe.

Currently, only when using the Rollup plugin, the definition of style order of precedence on the cascade layer. However, in the plugins for Webpack and Next.js, the cascade layer polyfill (:not(#\#)) is utilized. Is this intentional? From the perspective of CSS size, there may be cases where one would prefer to use the cascade layer without the polyfill.

Describe a solution you'd like

It would be beneficial if users could choose whether or not to use the cascade layer.

Describe alternatives you've considered

Consider adding a useLayer option as follows, allowing users to choose whether to use the cascade layer or the cascade layer polyfill:

Rollup:

import stylexPlugin from '@stylexjs/rollup-plugin';

stylexPlugin({
  fileName: 'stylex.css'
+ useLayer: true,
})

Webpack:

const StylexPlugin = require('@stylexjs/webpack-plugin');

new StylexPlugin({
  filename: 'styles.css',
+ useLayer: true,
})

Next.js:

const stylexPlugin = require('@stylexjs/nextjs-plugin');

module.exports = stylexPlugin({
  rootDir: __dirname,
+ useLayer: true,
})({});

Additional context

If this proposal is accepted, I am willing to create a pull request.

[Webpack plugin] CSS file is not getting attached to html template.

The problem
I am not using create-react-app and trying with webpack configuration in a dummy react project.
I am trying StyleX with my webpack configured dummy react application. My webpack config looks like below.

const StylexPlugin = require("@stylexjs/webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
function config(env, argv) {
  return {
    entry: {
      main: "./src/index.js",
    },
    output: {
      path: path.resolve(__dirname, "build"),
      filename: "[name].js",
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"],
            },
          },
        },

        {
          test: /\.css$/i,
          use: [MiniCssExtractPlugin.loader, "css-loader"],
        },
      ],
    },

    plugins: [
      // Ensure that the stylex plugin is used before Babel
      new StylexPlugin({
        filename: "omkar.css",
        // get webpack mode and set value for dev
        dev: argv.mode === "development",

        // Use statically generated CSS files and not runtime injected CSS.
        // Even in development.
        // optional. default: 'x'
        classNamePrefix: "x-om",
        // Required for CSS variable support
        unstable_moduleResolution: {
          // type: 'commonJS' | 'haste'
          // default: 'commonJS'
          type: "commonJS",
          // The absolute path to the root directory of your project
          rootDir: path.join("__dirname"),
        },
      }),
      new MiniCssExtractPlugin(),
      new HtmlWebpackPlugin({
        inject: "head",
        template: path.join(__dirname, "public", "index.html"),
      }),
    ],
  };
}
module.exports = config;

When I am doing production build. I can see seperate CSS file generated but it is not attached to the index file . Am I missing something?

Expected behavior

The html file under build should be having css file attached to it.

Steps to reproduce
Clone: https://github.com/omkar-nath/styleX-react/blob/master/webpack.config.js
Run: npm run build

Environment (include versions). Did this work in previous versions?

Background do not have a sufficient contrast ratio for "Search"

Is your feature request related to a problem? Please describe.
The background does not have a sufficient contrast ratio for the "Search" feature, making it difficult for users with impaired vision to read the text.

Describe a solution you'd like
I would like to request an improvement in the color contrast of the background for the "Search" feature. This could involve adjusting the background color or the text color to ensure that there is a proper and accessible contrast ratio.

Describe alternatives you've considered

  1. Implementing a customizable color scheme: Allow users to choose a color scheme that suits their preferences and improves readability.

  2. Adding an accessibility mode: Introduce a feature that enhances contrast for users who specifically need it without affecting the default design.

Additional context
image
As we can see in the Lighthouse, the color contrast is not proper. For some users with not proper vision it is very difficult to read.
image

Add types for the @stylexjs/rollup-plugin package

Is your feature request related to a problem? Please describe.
The current implementation of the Rollup plugin doesn't use Flow as other packages like @stylexjs/babel-plugin, so it doesn't include TypeScript or Flow type definitions.

Describe a solution you'd like
Type the package.

Describe alternatives you've considered
An alternative would be to publish the typings to DefinitelyTyped, but that doesn't feel right since this project ships type definitions for other packages.

Additional context
-


I'm open to creating a PR about this, but I've never used Flow before so I need to take a look at the docs first lol.

Combine styles at `stylex.create()` level

Is your feature request related to a problem? Please describe.

I would like to be able to combine styles at stylex.create() level.

Also, i would like to apply existing styles, with a different pseudo class (ie. define a style, and apply it to another element with :hover pseudo class).

To illustrate my point, let's say I have a shadow style:

export const shadowStyles = stylex.create({
  base: {
    '::before': { /* ... */ },
    '::after': { /* ... */ },
  },
  level0: {
    '::before': { boxShadow: `0 0 0 0 ${colorScheme.shadow}` },
    '::after': { boxShadow: `0 0 0 0 ${colorScheme.shadow}` },
  },
  level5: {
    '::before': { boxShadow: `0 4px 4px 0 ${colorScheme.shadow}` },
    '::after': { boxShadow: `0 8px 12px 6px ${colorScheme.shadow}` },
  },
});

I want it to be applied like this:

<div class="base level0 hover:level5" />

Describe a solution you'd like

Ideally, I would like to use it like this:

export const buttonStyles = stylex.create({
  container: {
    className: {
      default: stylex.apply(shadowStyles.base, shadowStyles.level0),
      ':hover': stylex.apply(shadowStyles.level5),
    },
  },
});
export const Button = ({ children }) => <div {...stylex.props(buttonStyles.container)}>{children}</div>;

Does it make sense to you?

Describe alternatives you've considered

I don't have any alternative.

Using imported variables to define styles

I was wondering if there was any way to get imported values working in StyleX like so:

// colorTokens.stylex.ts

import { something } from './test'; // const something = '#ffffff'

const testBg = something;

export const DARK_MODE = '@media (prefers-color-scheme: dark)';

export const colorTokens = stylex.defineVars({
	bgColor: {
		default: testBg,
		[DARK_MODE]: testBg,
	},
});

I cannot tell If this is a supported pattern. I am currently getting the error Only static values are allowed inside of a stylex.create() call.

Importing a .stylex.ts does not work with tsconfig paths settings

The problem
When importing a variable file like is listed in the docs, the build is only succeeding if the import path is a relative path (i.e. ../src/lib/theme/theme.stylex), but fails if the import path uses the tsconfig "paths" setting (i.e. @/lib/theme/theme.stylex when tsconfig paths is { '@/*' : '.src/*'} ).

With non-relative paths, it gives the Only static values are allowed inside of a stylex.create() call error message.

How to reproduce

Steps to reproduce:

  1. Create a next.js app with the default of paths: { '@/*' : '.src/*'} in the tsconfig.json file.
  2. Create a file called theme.stylex.ts in /src/lib/ that defines a color using export const colors = stylex.defineVars({test: '#000000'})
  3. Try to import the colors using import { colors } from @/lib/theme.stylex and use colors.test in a stylex.create call.

Expected behavior
I would expect this to allow colors to be used in stylex.create as specified in the docs.

Environment (include versions). Did this work in previous versions?

  • next 14.0.2 using an app router
  • @stylexjs/stylex - 0.3.0
  • @stylexjs/nextjs-plugin - 0.3.0

Is it possible to add styles to an existing className on an element?

Is your feature request related to a problem? Please describe.
When utilizing some component libraries they utilize their own classNames as a means for allowing developers to customize their components.

Describe a solution you'd like
As it stands, I am not seeing a great way how to do this in the docs. I initially looked at pseudo-classes and tried a similar approach with an existing classname on an element but I ran into some compilation issues. I am curious if this is even possible with StyleX?

Issue with Setting height: 100vh in stylex.create() Not Reflecting in Browser

Title: Issue with Setting height: 100vh in stylex.create() Not Reflecting in Browser

Environment:

  • Operating System: Ubuntu 22.04 (WSL)
  • Next.js Version: 14.0.2
  • Stylex Version: 0.3.0
  • Webpack Version: (Included with Next.js)

Description:
I'm experiencing a problem where setting height: 100vh in stylex.create() is not being reflected in the browser. Despite correctly implementing the Stylex syntax for defining styles, the specified height does not appear to be applied to the elements.

Example of the implementation:

import * as stylex from "@stylexjs/stylex";

export const styles = stylex.create({
    fullHeightContainer: {
        height: "100vh",
        // other styles...
    },
});

Steps to Reproduce:

  1. Define a style in a Stylex style file using stylex.create() with height: "100vh".
  2. Apply the style to a component in a Next.js project.
  3. Run the project and observe the component in a web browser.

Expected Result:
The element should have a height that covers 100% of the viewport height.

Actual Result:
The element does not cover 100% of the viewport height. Inspecting the element in the browser's developer tools reveals that the height: 100vh style is not being applied.

Additional Information:

  • Other styles defined in the same stylex.create() block are applied correctly.
  • There is no console error or warning indicating a problem with the Stylex implementation.

I'm looking for guidance on whether this is a known issue or if there's a specific way to handle viewport height units in Stylex that I might have missed. Any help or pointers would be greatly appreciated.

Thanks for your assistance,
Samplead Team

Dark Theme Inconsistency: Search Bar Color Reverts to Light Mode During Sidebar Navigation

The problem

While using the Stylexjs.com dark theme, an unexpected color inconsistency arises when navigating through the sidebar, causing the search bar to switch to light mode colors.
Interestingly, the color behavior normalizes when toggling between light and dark modes again. However, the issue resurfaces upon navigating the sidebar once more.

issue

Steps to reproduce:

  1. Enable StyleX dark theme.
  2. Consistently navigate through the sidebar.
  3. Observe the search bar switching to light mode colors.

Expected behavior

I anticipated the search bar to maintain a consistent appearance with dark theme colors throughout the sidebar navigation.

Environment

  • Browsers Tested: [Brave, Opera, Edge]

Doc : add pull request template

Is your feature request related to a problem? Please describe.

  • add a pull request template

Describe a solution you'd like
Pull request template should have this sections

  • Description
  • Fix #issue(number)
  • Summary
  • Type of Change
  • Screenshots
  • Added Tests

It won't work without the CSS file generated by the css-loader

The problem

In Next.js, if you don't import any .css file, the styles generated by stylex will not be added to the stylesheet.

How to reproduce

Steps to reproduce:

  1. delete this line
    import './globals.css';
  2. rebuild
  3. not working because not exists.next/static/css

Expected behavior

Is any .css file necessary? Can it be omitted?

Environment (include versions). Did this work in previous versions?

https://github.com/facebook/stylex/blob/c9b205750d835cba82b13ef5cdeaf30bbc683f70/apps/nextjs-example/package.json

Getting an Error when passing a defined variable to a stylex.create

Title; Compilation Error, with Stylex. Values allowed inside the stylex.create() function

Environment;
Operating System; Ubuntu 22.04 (WSL)
Next.js Version; 14.0.2
Stylex Version; 0.3.0
Webpack Version; (Included with Next.js)

Description;
I encountered an issue while trying to compile a Next.js project that uses Stylex for styling. The build process. Displays an error message stating that only static values can be used inside the stylex.create() function call. This problem occurs even though I followed the documentation, which instructs to define variables using stylex.defineVars() and use them within stylex.create().

like so:

import * as stylex from "@stylexjs/stylex";

export const staticColors = stylex.defineVars({
    colorsBaseBlack: "#000000",
    colorsBaseWhite: "#ffffff",
    colorsBlue100: "#d1e9ff",
    colorsBlue200: "#b2ddff",
    colorsBlue25: "#f5faff",
// ...
})

and used it like so:

import { staticColors } from "@/themes/static-colors.stylex";
import * as stylex from "@stylexjs/stylex";

export const styles = stylex.create({
    container: {
        display: "flex",
        padding: "0 24px",
        alignItems: "flex-start",
        gap: 8,
        alignSelf: "stretch",
    },
    title: {
        color: staticColors.colorsGray900,
        fontSize: "1.25rem",
        fontStyle: "normal",
        fontWeight: 600,
        lineHeight: 1.5,
    },
});

Steps to Reproduce;

  1. Define CSS variables by utilizing stylex.defineVars() in a file called tokens.stylex.ts.
  2. Import these variables and incorporate them within a stylex.create() call in a component.
  3. Execute the build command to compile the project.

Expected Result;
The project should successfully compile, with Stylex processing the CSS variable definitions and applying them as intended.

Actual Result;
The build process encounters an error that states;

Failed to compile

./src/components/atoms/slideout menu header/style.stylex.ts
Error;
.../src/components/atoms/slideout menu header/style.stylex.ts; Only static values are allowed inside of a stylex.create() call.
 , at transformFile.next (<anonymous>)
  at run.next (<anonymous>)
  at transform.next (<anonymous>)

This error indicates that there might be dynamic values being passed to stylex.create() which is not supported.

Additional Information;
The Next.js configuration has been customized to utilize the @stylexjs/webpack plugin for StyleX.
Due to the issue, with Google Fonts and the Next.js StyleX plugin it was decided to use the Webpack plugin

Note: It is observed that the compilation works when stylex.create() is used with a function that returns the style object, as shown below:

export const styles = stylex.create({
    container: () => ({
        backgroundColor: staticColors.colorsBaseWhite,
    }),
});

However, this approach is contrary to the examples provided in the Stylex documentation where stylex.create() is directly given an object. The expected usage, as per the documentation, which is currently not working, is:

import * as stylex from '@stylexjs/stylex';
import { staticColors } from '../path/to/tokens.stylex';

const styles = stylex.create({
    container: {
        backgroundColor: staticColors.colorsBaseWhite,
    },
});

This inconsistency between the documentation and the actual working solution suggests a potential issue with the library's handling of variable definitions within stylex.create() calls.

Thanks for reviewing the issue, we are looking forward to use this in our app,
Samplead Team

Discord for informal communication

Is your feature request related to a problem? Please describe.
I see discussions about rollup and vite support and also conflicting contributions with docs. A synchronous informal communication channel for maintainers/contributors/users may relieve some of the issues.

Describe a solution you'd like
A lot of OSS projects elect to use Discord for informal communication with the community. I would love to have a Discord server for maintainers and users of StyleX. This could help the StyleX community gain some more organization with maintainers/contributors/etc. Have seen Discord be highly effective for other OSS projects.

Describe alternatives you've considered
Continue the use of Github Issues, perhaps the use of discussions may work as well.

Additional context
Would be happy to also have an community maintained discord server where fast communication can happen, some good examples of servers are:

[Bug] Properties not recognized by eslint-plugin

The problem

The outlineOffset property is not recognized by the eslint-plugin.

How to reproduce

With the following code:

import * as stylex from '@stylexjs/stylex';

export const styles = stylex.create({
  container: {
    outlineOffset: '2px', // eslint(@stylexjs/valid-styles) error here
  },
});

I have the following eslint error from @stylex/valid-styles:

outlineOffset value must be one of:
'outlineOffset' is not supported yet. Please use 'outline' instead

outlineOffset: showError(
"'outlineOffset' is not supported yet. Please use 'outline' instead",
),

But outline syntax does not allow an offset:

outline = 
  <'outline-color'>  ||
  <'outline-style'>  ||
  <'outline-width'>

Cf. https://developer.mozilla.org/en-US/docs/Web/CSS/outline

Rust Regex experts: Codeblocks and inline code in regex

Problem

Hello StyleX community I'm working on a PR #87 for adding reserved words (with correct capitalization) for the spellchecker typos that the StyleX team uses to eliminate unnecessary PRs.
I have forgotten that there are code blocks in markdown files that we would most likely want to ignore. The issue is the way that we can ignore such patterns is through regex and it does not support backreferences and lookaround Rust Regex.
I have gotten this far:

extend-ignore-re = [
    "(`{3,}|~{3,})(\\w+)?\\s*", # Pattern for code blocks
    "([\\s\\S]*?)",
    "`[^`]+`", # Pattern for inline code snippets
]

This regex pattern detects all code blocks with either ~~~ or ```, but it seems to only capture the first instance of inline code snippets. Wanted to see if there was anyone with experience to help make this PR into a reality.

Steps to reproduce

Clone the PR, install typos (using link above) run typos in root directory. Additional rules are as follows:

[type.md]
extend-glob = ["*.md", ".mdx"]
extend-ignore-re = [
    "(`{3,}|~{3,})(\\w+)?\\s*", # Pattern for code blocks
    "([\\s\\S]*?)",
    "`[^`]+`", # Pattern for inline code snippets
]
[type.md.extend-words]
stylex = "StyleX"
typescript = "TypeScript

Contributor link in the PR template points to the wrong address

Clicking the contributor guideline link in create new PR leads to the wrong address.

How to reproduce

Steps to reproduce:

  1. open CONTRIBUTING.md under .github/
  2. click on the guidelines link
    or just create a new PR and click on the link

Expected behavior

Clicking the link should take you to main/.github/CONTRIBUTING.md

Environment (include versions). Did this work in previous versions?
NA

Ability to apply vars to an element

Is your feature request related to a problem? Please describe.

The doc in https://stylexjs.com/docs/learn/theming/defining-variables/#defining-variables-1 mentions that the defined vars are automatically added to :root. This might not be a desired outcome everytime.

Describe a solution you'd like

In my case, I only want those variables to be applicable to the children of my theming component without polluting the :root. We provide a library that has it's own UI and we do not want to mess with root. Also, we do allow nested themes where a child theme components can override the theme of parent. One way to do this will be to provide the var names in object format that can be passed to an element's style prop.

Describe alternatives you've considered

We are using vanilla extract and it provides this functionality: https://vanilla-extract.style/documentation/packages/dynamic/#assigninlinevars

Additional context

Angular support/example

Is your feature request related to a problem? Please describe.

I want to try stylex in an angular project. As angular is explicitly mentioned in the introduction section of the docs, I want to give it a go.

Describe a solution you'd like

Provide instructions on how to integrate stylex with angular. The instructions for integrating with webpack already provide the base for the integration, but comprehensive documentation on how to apply the stylex API is missing.

Describe alternatives you've considered

Additional context

`Next.js` example app is broken

The problem

The Next.js example app is not working due to the Only static values are allowed inside of a stylex.create() call error.

How to reproduce

Steps to reproduce:

  1. Install dependencies of monorepo
  2. Navigate to nextjs-example
  3. Run npm run build (or npm run dev and the navigate to https://localhost:{port})

Expected behavior

The app should not crash due to the NON_STATIC_VALUE error. Seems like the token file is following the correct conventions.

Environment (include versions). Did this work in previous versions?

  • Node version 18.19
  • macOS Ventura 13.3.1

It was my first time running this example

Add StyleX Logo and Clearly Outline Forking and Cloning Steps in Readme

The problem

REQUIRED:

  1. The current Readme file for the project does not include the StyleX logo, which is essential for branding and visual representation of the project.
  2. the Readme does not provide clear and visible instructions for getting started, specifically the fork and clone method. This information should be easily accessible within the Readme file itself, rather than buried inside another file or section.

Steps to reproduce:

  1. Update the Readme file to include the StyleX logo at the top, ensuring that it is prominently displayed.
  2. Clearly outline the steps for forking and cloning the repository within the Readme itself.

Please assign me this issue

Styles Not Applied with Stylex and Webpack Plugin in Next.js (runtimeInjection: false)

Title: Styles Not Applied with Stylex and Webpack Plugin in Next.js (runtimeInjection: false)

Environment:

  • Operating System: Ubuntu 22.04 (WSL)
  • Next.js Version: 14.0.2
  • Stylex Version: 0.3.0
  • Webpack Version: (Included with Next.js)

Description:
I am facing an issue where CSS styles are not being applied in the browser when using Next.js with the Stylex Webpack plugin. This issue occurs when runtimeInjection is set to false. In this setup, the class names appear on the elements and the styles.css file is created in the .next cache. However, the styles themselves are not applied in the browser. Notably, this setup worked correctly in Stylex version 0.2.0beta27 and the corresponding Webpack plugin, without any changes in the configuration.

My next.config.js is as follows:

const StylexPlugin = require("@stylexjs/webpack-plugin");

/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    images: {
        remotePatterns: [
            {
                protocol: "https",
                hostname: "**",
            },
        ],
    },
    webpack: (
        config,
        { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack },
    ) => {
        config.module.rules.push({
            test: /\.svg$/,
            use: ["@svgr/webpack"],
        });

        config.plugins.push(
            // Ensure that the stylex plugin is used before Babel
            new StylexPlugin({
                filename: "styles.css",
                // get webpack mode and set value for dev
                dev: dev,
                // Use statically generated CSS files and not runtime injected CSS.
                // Even in development.
                runtimeInjection: false,
                // optional. default: 'x'
                classNamePrefix: "x",
                // Required for CSS variable support
                unstable_moduleResolution: {
                    // type: 'commonJS' | 'haste'
                    // default: 'commonJS'
                    type: "commonJS",
                    // The absolute path to the root directory of your project
                    rootDir: __dirname,
                },
            }),
        );

        return config;
    },
};

module.exports = nextConfig;

Steps to Reproduce:

  1. Set up a Next.js project with Stylex and the Webpack plugin.
  2. Configure next.config.js with runtimeInjection set to false.
  3. Run the project and observe that the CSS classes are present on elements but styles are not applied.

Expected Result:
The CSS styles should be applied to the elements in the browser, as they were in Stylex version 0.2.0beta27.

Actual Result:
The CSS classes are present on elements, and the styles.css file is created in the .next cache, but the styles are not applied in the browser.

Additional Information:

  • The issue only occurs when runtimeInjection is set to false. When set to true, the styles are applied as expected.
  • There are no console errors or warnings indicating a problem with the Stylex implementation or the Webpack configuration.
  • The issue started occurring after updating Stylex from version 0.2.0beta27 to 0.3.0.

I am seeking assistance to understand why this issue is occurring with the newer version of Stylex and how it can be resolved. Any insights or suggestions would be highly appreciated.

Thank you for your help,
Samplead Team

Target '.class[pseudo class] [pseudo element]', ie. '.button:hover ::before', or ':before:hover:prop' in tw

Is your feature request related to a problem? Please describe.

I would like to target .class[pseudo class] [pseudo element], ie. .button:hover ::before.

Describe a solution you'd like

const buttonStyles = stylex.create({
  shadow: {
    boxShadow: {
      default: null,
      ':hover': {
        '::before': `0 4px 4px 0 ${colorScheme.shadow}`,
        '::after': `0 8px 12px 6px ${colorScheme.shadow}`,
      },
    },
  },
});

Describe alternatives you've considered

I have no alternative yet.

[feat]: Footer alignment

Is your feature request related to a problem? Please describe.
The alignment of the footer isn't at the center.

image

Describe a solution you'd like
Will fix the alignment of the footer to the center

image

Describe alternatives you've considered

NULL

Additional context

NULL

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.