Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active August 31, 2016 08:34
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 treshugart/b609f856888bef7fbccafe51356171d2 to your computer and use it in GitHub Desktop.
Save treshugart/b609f856888bef7fbccafe51356171d2 to your computer and use it in GitHub Desktop.
JSS rules for polyfilling Shadow DOM selectors
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