2018-09-08 22:55:42 -05:00
|
|
|
|
|
|
|
import * as css from 'css';
|
|
|
|
import React from 'react';
|
|
|
|
|
|
|
|
let newId = 0;
|
|
|
|
const map = new WeakMap();
|
|
|
|
let sheet = null;
|
|
|
|
|
|
|
|
// Ensure styles exist for a component.
|
|
|
|
const ensureComponentStyles = (constructor, styles) => {
|
|
|
|
|
|
|
|
if (!window || !styles || map.has(constructor)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
newId += 1;
|
|
|
|
const id = newId.toString(36);
|
|
|
|
map.set(constructor, id);
|
|
|
|
|
|
|
|
// Ensure sheet exists.
|
|
|
|
if (!sheet) {
|
|
|
|
sheet = window.document.createElement('style');
|
|
|
|
sheet.id = 'stylist-styles';
|
|
|
|
window.document.getElementsByTagName('head')[0].appendChild(sheet);
|
|
|
|
}
|
|
|
|
|
|
|
|
// All rules made component-specific.
|
|
|
|
for (const style of styles) {
|
|
|
|
|
|
|
|
const ast = css.parse(style);
|
|
|
|
ast.stylesheet.rules = mapStyleRulesTree(ast.stylesheet.rules, id);
|
|
|
|
sheet.innerHTML += css.stringify(ast);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const mapStyleRulesTree = (rules, id) => rules.map((rule) => {
|
|
|
|
|
|
|
|
// Recur for mediaqueries.
|
|
|
|
if ('media' === rule.type) {
|
|
|
|
rule.rules = mapStyleRulesTree(rule.rules, id);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!rule.selectors) {
|
|
|
|
return rule;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...rule,
|
|
|
|
...{
|
|
|
|
selectors: rule.selectors.map((rule) =>
|
|
|
|
`[data-component-style="${id}"] ${rule}`
|
|
|
|
),
|
|
|
|
},
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2018-12-23 07:58:10 -06:00
|
|
|
export default function contempo(styles) { return function (Component) {
|
2018-09-08 22:55:42 -05:00
|
|
|
if (!Array.isArray(styles)) {
|
|
|
|
styles = [styles];
|
|
|
|
}
|
|
|
|
|
|
|
|
const createRenderFunction = (constructor, markupFn) => function() {
|
|
|
|
ensureComponentStyles(constructor, styles);
|
|
|
|
|
|
|
|
const markup = markupFn.apply(this, arguments);
|
|
|
|
const id = map.get(constructor);
|
|
|
|
if (!id) {
|
|
|
|
return markup;
|
|
|
|
}
|
|
|
|
return <ins data-component-style={id}>{markup}</ins>;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Component.prototype.render) {
|
2018-12-23 07:58:10 -06:00
|
|
|
class ContempoComponent extends Component {
|
2018-09-08 22:55:42 -05:00
|
|
|
}
|
2018-12-23 07:58:10 -06:00
|
|
|
ContempoComponent.prototype.render = createRenderFunction(
|
2018-09-08 22:55:42 -05:00
|
|
|
Component, Component.prototype.render
|
|
|
|
);
|
2018-12-23 07:58:10 -06:00
|
|
|
return ContempoComponent;
|
2018-09-08 22:55:42 -05:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
return createRenderFunction(Component, Component);
|
|
|
|
}
|
2018-12-23 07:58:10 -06:00
|
|
|
}}
|
2018-09-08 22:55:42 -05:00
|
|
|
|