Last active
October 1, 2024 12:01
-
-
Save doeixd/ade8376e2e4ca3eace19f429cf6cea40 to your computer and use it in GitHub Desktop.
Scoped CSS Code Golf: The following is a "one-line" snippet I have created to enable scoped style tags. It supports, :global, media queries, keyframes, and adding and removing style tags/the scoped attribute. It's pretty hacky, and there may be some unexpected edge cases with the regexes, but it works for me! I mostly created it for fun, and as …
This file contains 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
addEventListener('DOMContentLoaded',(a,d=document,s='STYLE',p=(d.head.innerHTML+=`<${s} id='g'>`,'scoped'),f=(e,x,y,i=e?.dataset?.s??new Date%1e3,b=((e.dataset.s=i,a='attributes',x='textContent'),e[a][p]))=>{(e?.parentElement??(i='html'))?.classList?.[b?'add':'remove'](i);e[x]=e?.[x]?.replace(/(?<=^([ \t]*):global\s?{\n?).*?(?=^\1})|(?<s>.s-\d+\s)/gm,(...m)=>(!m?.[5]?.s&&(g[x]+=m[0]),''))?.replace(/^(?<i>[ \t]*)(?![@:]|(?:to|from|\d+%))(?<s>(?:\S|(?<=\S)\s(?!{))*)(?=\s?{$)/gm,`$<i>${b?`.${i} `:''}$<s>`)},m=new MutationObserver(l=>l.map(r=>[...r?.addedNodes,r.target].map(n=>n?.tagName==s&&f(n)))).observe(d.documentElement,{[a]:1,childList:1,subtree:1,attributeFilter:[p]}))=>d.querySelectorAll(s+`[${p}]`).forEach(f)) |
Version 1:
document.querySelectorAll('style[scoped]').forEach(el => {
const id = 's-' + ~~(Math.random() * 1000000)
el.parentElement.classList.add(id)
el.textContent = el.textContent.replace(/(?<!@.*)(?:[^\s])(?<!(?<g>:.*))[\w:\(\)]+(?=\s?{)/g, `.${id} $&`)
})
Example of functionality:
<div>
This text is not blue
<div>
This text is blue.
<!-- Because of the "scoped" attribute, the following styles only apply to the parent element and it's children. -->
<style scoped>
div {
color: blue;
}
</style>
</div>
</div>
Example of :global
escape-hatch functionality:
<div>
This text is red.
<div>
This text is also red.
<style scoped>
/* All styles defined within this block apply globally, and are not scoped */
:global {
div {
color: red;
}
}
</style>
</div>
</div>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Current code golfed version with whitespace:
Readable Version: