Last active
May 6, 2024 04:59
-
-
Save treshugart/b609f856888bef7fbccafe51356171d2 to your computer and use it in GitHub Desktop.
JSS rules for polyfilling Shadow DOM selectors
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
const jss = window.jss.default; | |
const native = fn => (fn || '').toString().indexOf('[native code]') > -1; | |
const div = document.createElement('div'); | |
const supportsShadowDOM = native(ShadowRoot); | |
const supportsShadowDOMV0 = div.createShadowRoot && native(HTMLContentElement); | |
const supportsShadowDOMV1 = div.attachShadow && native(HTMLSlotElement); | |
// Polyfill :host | |
// -------------- | |
jss.use(rule => { | |
if (rule.name.indexOf(':host') === 0) { | |
if (supportsShadowDOM) { | |
rule.selectorText = rule.name; | |
} else { | |
const match = rule.selectorText.match(/:host\((.*)\)/); | |
const matchSelector = match && match[1] || ''; | |
rule.selectorText = rule.options.sheet.options.elem.tagName.toLowerCase() + matchSelector; | |
} | |
} | |
}); | |
// Polyfill ::slotted | |
// ------------------ | |
jss.use(rule => { | |
if (rule.name.indexOf('::slotted') > -1) { | |
const match = rule.name.match(/(.*)::slotted\((.*)\)/); | |
const matchSlot = match && match[1] || ''; | |
const matchSelector = match && match[2] || ''; | |
if (supportsShadowDOMV1) { | |
rule.selectorText = rule.name; | |
} else if (supportsShadowDOMV0) { | |
rule.selectorText = `${matchSlot}::content > ${matchSelector}`; | |
} else { | |
const lcTagName = rule.options.sheet.options.elem.tagName.toLowerCase(); | |
rule.selectorText = `${lcTagName} slot${matchSlot} > ${matchSelector}`; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment