Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimise dynamic styles into static styles when possible #737

Open
nmn opened this issue Oct 9, 2024 · 0 comments
Open

Optimise dynamic styles into static styles when possible #737

nmn opened this issue Oct 9, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@nmn
Copy link
Contributor

nmn commented Oct 9, 2024

See #727


There are cases where a developer may use dynamic styles syntax with a function but the styles themselves are conditional styles that can be known at compile time.

In such scenarios, we can compile every possible value into static classNames.

Here are some examples to clarify what should happen:


Source:

const styles = stylex.create({
  root: (isCondition) => ({
    width: '100%',
    maxWidth: 768,
    display: 'flex',
    color: isCondition ? 'red' : 'blue'
  }),
});

Output:

const _styles_root = {
  width: 'w-full', // sets `width: 100%`
  maxWidth: 'mw-768',
  display: 'd-flex',
};
const _styles_root1 = {
  $$css: true,
  color: 'c-red', // className that sets color: red;
};
const _styles_root2 = {
  $$css: true,
  color: 'c-blue', // className that sets color: blue;
};
const styles = {
  root: (isCondition) => [
    _styles_root,
    isCondition ? _styles_root1 : _styles_root2,
  ],
};


Source:

const styles = stylex.create({
  root: (isA, isB) => ({
    width: '100%',
    maxWidth: 768,
    display: 'flex',
    color: isA ? 'red' : 'blue',
    backgroundColor: isB ? 'yellow' : 'green',
  }),
});

Output:

const _styles_root = {
  width: 'w-full', // sets `width: 100%`
  maxWidth: 'mw-768',
  display: 'd-flex',
};
const _styles_root1_1 = {
  $$css: true,
  color: 'c-red', // className that sets color: red;
};
const _styles_root1_2 = {
  $$css: true,
  color: 'c-blue',
};
const _styles_root2_1 = {
  $$css: true,
  backgroundColor: 'c-yellow',
};
const _styles_root2_2 = {
  $$css: true,
  backgroundColor: 'c-green',
};
const styles = {
  root: (isA, isB) => [
    _styles_root,
    isA ? _styles_root1_1 : _styles_root1_2,
    isB ? _styles_root2_1 : _styles_root2_2,
  ],
};

The overall logic can be:

  1. Separate the dynamic style object into separate chunks:
    • The complete static part
    • The parts that are conditional styles
    • The truly dynamic parts
  2. Compile each of the parts separately
  3. Return them all within an array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant