Skip to content

Instantly share code, notes, and snippets.

@vdsabev
Created September 9, 2023 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdsabev/c906dad97fb5157b96b93cdb37c2b36b to your computer and use it in GitHub Desktop.
Save vdsabev/c906dad97fb5157b96b93cdb37c2b36b to your computer and use it in GitHub Desktop.
Modified css-scope-inline
// 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