@descope/sdk-mixins
Version:
Descope JavaScript SDK mixins
60 lines (57 loc) • 2.03 kB
JavaScript
import { createSingletonMixin, compose } from '@descope/sdk-helpers';
import { cspNonceMixin } from './cspNonceMixin.js';
// we should mimic the CSSStyleSheet API for the fns we are using
class CSSStyleSheetMock {
constructor(ref, nonce, { prepend = false } = {}) {
this.styleEle = document.createElement('style');
this.styleEle.setAttribute('nonce', nonce);
this.ref = ref;
if (!this.ref) {
return;
}
if (prepend) {
this.ref.prepend(this.styleEle);
}
else {
this.ref.append(this.styleEle);
}
}
replaceSync(cssString) {
this.styleEle.textContent = cssString;
}
get cssRules() {
var _a;
return (_a = this.styleEle.sheet) === null || _a === void 0 ? void 0 : _a.cssRules;
}
}
const injectStyleMixin = createSingletonMixin((superclass) => {
const BaseClass = compose(cspNonceMixin)(superclass);
return class InjectStyleMixinClass extends BaseClass {
injectStyle(cssString, { prepend = false } = {}) {
let style;
try {
style = new CSSStyleSheet();
}
catch (e) {
// fallback for browsers that don't support CSSStyleSheet
style = new CSSStyleSheetMock(this.shadowRoot, this.nonce, {
prepend,
});
}
if (cssString) {
style.replaceSync(cssString);
}
if (style instanceof CSSStyleSheet) {
const ref = this.shadowRoot;
if (ref && 'adoptedStyleSheets' in ref) {
const adoptedStyleSheets = [...(ref.adoptedStyleSheets || [])];
adoptedStyleSheets[prepend ? 'unshift' : 'push'](style);
ref.adoptedStyleSheets = adoptedStyleSheets;
}
}
return style;
}
};
});
export { injectStyleMixin };
//# sourceMappingURL=injectStyleMixin.js.map