stylex icon indicating copy to clipboard operation
stylex copied to clipboard

[babel-plugin] Optimise dynamic styles into static styles when possible

Open nmn opened this issue 1 year ago • 0 comments

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.

nmn avatar Oct 09 '24 07:10 nmn