Skip to content

Use attribute based scoping instead of classes; small optimizaitons #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Combine child and parent css scope attribute assignments
  • Loading branch information
infogulch committed Oct 4, 2023
commit 8049ee2b62725a8ae26353d638f295a800e767b0
5 changes: 2 additions & 3 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// 🌘 CSS Scope Inline (https://github.com/gnat/css-scope-inline)
window.cssScopeCount ??= 1 // Let other scripts read the scope count.
window.cssScope ??= new MutationObserver(mutations => { // Allow 1 observer.
document?.body?.querySelectorAll('style:not([scoped-to])').forEach(node => { // Faster than walking MutationObserver results when recieving subtree (DOM swap, htmx, ajax, jquery).
node.parentNode.dataset.cssScope ??= (window.cssScopeCount++)
document?.body?.querySelectorAll('style:not([data-css-scope])').forEach(node => { // Faster than walking MutationObserver results when recieving subtree (DOM swap, htmx, ajax, jquery).
node.dataset.cssScope = node.parentNode.dataset.cssScope ??= (window.cssScopeCount++)
node.textContent = node.textContent
.replace(/((@keyframes\s|animation:|animation-name:)[^{};]*)\bme(?![A-Za-z])/g, `$1css-scope-${node.parentNode.dataset.cssScope}`)
.replace(/(^|[^-\w])me(?![-\w])/g, `$1[data-css-scope='${node.parentNode.dataset.cssScope}']`)
.replace(/(?:@media)\s+(xs-|sm-|md-|lg-|xl-|sm|md|lg|xl|xx)(?![-\w])/g, // Optional responsive design shorthand for @media breakpoints. Mobile First (above breakpoint): 🟢 None sm md lg xl xx 🏁 Desktop First (below breakpoint): 🏁 xs- sm- md- lg- xl- None 🟢
(match, part1) => { return '@media '+({'sm':'(min-width: 640px)','md':'(min-width: 768px)', 'lg':'(min-width: 1024px)', 'xl':'(min-width: 1280px)', 'xx':'(min-width: 1536px)', 'xs-':'(max-width: 639px)', 'sm-':'(max-width: 767px)', 'md-':'(max-width: 1023px)', 'lg-':'(max-width: 1279px)', 'xl-':'(max-width: 1535px)'}[part1]) }
)
node.setAttribute('scoped-to', node.parentNode.dataset.cssScope)
})
}).observe(document.documentElement, {childList: true, subtree: true})