Created
September 9, 2023 12:40
-
-
Save vdsabev/c906dad97fb5157b96b93cdb37c2b36b to your computer and use it in GitHub Desktop.
Modified css-scope-inline
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
// Original: https://github.com/gnat/css-scope-inline | |
// Modified: https://gist.github.com/Gyanreyer/a9d5fe8b91055ea4dc302c1d0ff17452 | |
(() => { | |
let cssScopeCount = 0; | |
const scopedSelectorRegex = new RegExp('(:scope)(?![A-Za-z0-9_-])', 'g'); | |
/** @returns {Node[]} */ | |
const getAllChildNodes = (/** @type {NodeList} */ childNodes) => | |
[...childNodes].flatMap((childNode) => [ | |
childNode, | |
...getAllChildNodes(childNode.childNodes), | |
]); | |
new MutationObserver((mutations) => { | |
for (const mutation of mutations) { | |
if (mutation.type !== 'childList' || mutation.addedNodes.length === 0) { | |
continue; | |
} | |
const addedNodesWithAllTheirChildren = getAllChildNodes( | |
mutation.addedNodes | |
); | |
for (const addedNode of addedNodesWithAllTheirChildren) { | |
if (addedNode.nodeName !== 'STYLE') { | |
// Must be a <style> tag | |
continue; | |
} | |
const parentElement = addedNode.parentElement; | |
if (!parentElement || parentElement.tagName === 'HEAD') { | |
// Must have a parent outside of the <head> | |
continue; | |
} | |
const textContent = addedNode.textContent; | |
if (!textContent) { | |
// Must have content | |
continue; | |
} | |
let scopedSelector; | |
const existingScope = addedNode.parentElement.dataset.scope; | |
if (existingScope) { | |
scopedSelector = `[data-scope="${existingScope}"]`; | |
} else { | |
// Increment the scope count to make it unique for this <style> tag | |
cssScopeCount++; | |
// Add unique scope data attribute, example: data-scope="1234" | |
addedNode.parentElement.dataset.scope = String(cssScopeCount); | |
scopedSelector = `[data-scope="${cssScopeCount}"]`; | |
} | |
addedNode.textContent = textContent.replace( | |
scopedSelectorRegex, | |
scopedSelector | |
); | |
} | |
} | |
}).observe(document.documentElement, { childList: true, subtree: true }); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment