Skip to content

Instantly share code, notes, and snippets.

@zaceno
Created March 27, 2020 15:44
Show Gist options
  • Save zaceno/f2447b8bd7581f2c919a60fe6bdd7d81 to your computer and use it in GitHub Desktop.
Save zaceno/f2447b8bd7581f2c919a60fe6bdd7d81 to your computer and use it in GitHub Desktop.
Add scoped css directives from javascript
/*
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