feature: use constructed style sheets for dom render so that it works with csp style-src 'self'

This commit is contained in:
Simon Siefke
2023-07-27 13:08:22 +02:00
parent 1c98037eed
commit 1c0a25d01b
2 changed files with 50 additions and 12 deletions
+39
View File
@@ -0,0 +1,39 @@
export interface StyleSheet {
dispose: () => void;
setCss: (value: string) => void;
}
const createCssStyleSheet = (): StyleSheet => {
const sheet = new CSSStyleSheet();
document.adoptedStyleSheets.push(sheet);
return {
dispose() {
const index = document.adoptedStyleSheets.indexOf(sheet);
document.adoptedStyleSheets.splice(index, 1);
},
setCss(css) {
sheet.replace(css);
},
};
};
const createStyleElement = (parent: HTMLElement): StyleSheet => {
const element = document.createElement("style");
parent.append(element);
return {
dispose() {
element.remove();
},
setCss(css) {
element.textContent = css;
},
};
};
export const createStyle = (parent: HTMLElement): StyleSheet => {
try {
return createCssStyleSheet();
} catch {
return createStyleElement(parent);
}
};