facebook / facebook/stylex

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

Open
#737 1 comment 7 reactions 0 assignees View on GitHub
enhancement
Dominant language
JavaScript
Stars
10.3k
Forks
481
Avg merge
3d 8h
Merged PRs (30d)
13

Description

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:

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

Output:

```ts
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:

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

Output:

```ts
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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.