Created
March 27, 2020 15:44
-
-
Save zaceno/f2447b8bd7581f2c919a60fe6bdd7d81 to your computer and use it in GitHub Desktop.
Add scoped css directives from javascript
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
/* | |
Usage: | |
import addStyleSheet from 'add-stylesheet.js' | |
export const view = () => ( | |
<div class="container"> | |
<h1>Hello</h1> | |
<p>World</p> | |
</div> | |
) | |
addStylesheet(` | |
{ | |
position: absolute; | |
width: 100%; | |
height: 100%; | |
background-color: #446; | |
font-size: 15px; | |
} | |
h1 { | |
font-weight: normal; | |
font-size: 20px; | |
text-transform: uppercase; | |
text-align: center; | |
} | |
p { | |
margin: 20px; | |
} | |
p.error { | |
color: #900; | |
font-style: italic; | |
height: 15px; | |
} | |
`, | |
".container", | |
) | |
*/ | |
import "https://unpkg.com/construct-style-sheets-polyfill" | |
export default (str, scopeSelector = "") => { | |
const ss = CSSStyleSheet() | |
ss.replaceSync( | |
str | |
.split("}") | |
.map(directive => { | |
if (directive.indexOf("{") < 0) return directive | |
const [selectors, rules] = directive.split("{") | |
return `${selectors | |
.split(",") | |
.map(selector => `${scopeSelector} ${selector}`) | |
.join(",")} { ${rules}` | |
}) | |
.join("}"), | |
) | |
document.adoptedStyleSheets = [...document.adoptedStyleSheets, ss] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment