Last active
July 26, 2017 07:28
-
-
Save giuseppeg/2038ed8c51d4ac4a612abf679c825b6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
1 and 2 are hashes of | |
`p[data-jsx~="?"] { color: ${props.color}; }` | |
and | |
`div[data-jsx~="?"] { border: 1px solid ${borderStyle} }` | |
*/ | |
export default (props) => { | |
const borderStyle = props.foo ? 'solid' : 'dashed' | |
return <div data-jsx={_JSXStyle.get([[1, [props.color]], [2, [borderStyle]]])}> | |
<p data-jsx={_JSXStyle.get([[1, [props.color]], [2, [borderStyle]]])}>hi</p> | |
<_JSXStyle id={1} quasis={['p[data-jsx~="?"] { color: ', '; }']} expressions={[props.color]} /> | |
<_JSXStyle id={2} quasis={['div[data-jsx~="?"] { border: 1px ', ' #000 }']} expressions={[borderStyle]} /> | |
</div> | |
} | |
// _JSXStyle.get | |
// returns a space separated list of hashes | |
function get(arr) { | |
return arr.map((tagInfo) => { | |
const [id, expressions] = tagInfo | |
const hash = hashArray(expressions) | |
return `${id}-${hash}` | |
}).join(' ') | |
} | |
/* | |
In _JSXStyle | |
<_JSXStyle id={1} quasis={['p[data-jsx~="?"] { color: ', '; }']} expressions={[props.color]} /> | |
*/ | |
const resolvedCache = {} | |
// ... | |
// componentWillMount/Update | |
const expressionsHash = hashArray(expressions) | |
const hash = `${id}-${expressionsHash}` | |
// if mounted, return / noop | |
let css = resolvedCache[hash] | |
if (!css) { | |
css = resolvedCache[hash] = computeCss(hash, quasis, expressions) | |
} | |
// mount css | |
/* end */ | |
function computeCss(hash, quasis, expressions) { | |
return ( | |
quasis[0] + expressions | |
.map((exp, index) => `${expr}${quasis[index+1]}`) | |
.join('') | |
).replace(/\[data-jsx~="?"]/g, `[data-jsx~="${hash}"]`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mounted styles are shared, so we'd need a count of mounted instances and unmount them only when
0
instances are using them.When styles don't have expressions (i.e. static) we can avoid a bunch of work obviously.