universe
universe copied to clipboard
SX: refactor 'injectRuntimeStyles'
Function injectRuntimeStyles
is currently wildly ineffective and kinda broken.
How it works now
We call injectRuntimeStyles
everytime sx.create({ … })
is called at runtime (in a browser context). This function tries to find style[data-adeira-sx]
HTML tag and it tries to inject there the styles from sx.create
. It also tries to avoid adding already existing CSS classes but it does a fairly bad job (basically only simple rules are supported). Moreover, this check is performed for every single CSS class.
You can check the problem by running the following code in a browser console (Firefox) and checking the massive output:
let cssTexts = [];
for (const cssRule of document.querySelector('style[data-adeira-sx]').sheet.cssRules) {
cssTexts.push(cssRule.cssText);
}
// copy(cssTexts.join('\n'));
console.log(cssTexts.join('\n'));
You should be able to see many duplicates caused by incorrectly (or rather inefficiently) injecting StyleCollectorAtNode
and StyleCollectorPseudoNode
.
How it should work
SX should inject only runtime styles that do not exist yet in style[data-adeira-sx]
and each CSS class should be added only once. There are 2 ways how we can do this:
- automatically rehydrate the CSS classes (preferred: https://github.com/styled-components/styled-components/blob/e2c554ebc8607b1249f43e1d38503d155d431c11/packages/styled-components/src/sheet/Rehydration.ts)
- manually
rehydrate
the CSS classes (inspired by Aphrodite: https://github.com/Khan/aphrodite#server-side-rendering)