Skip to content

Commit a06e1ec

Browse files
committed
fix attaching styles, check shadowroot
1 parent a85e5b3 commit a06e1ec

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

src/hooks/useStyleSheet.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,36 @@
1+
/* eslint-disable no-extra-boolean-cast */
12
import { RefObject } from "react";
2-
33
import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
4+
import { getShadowRoot } from "../utils/shadowRoot";
45
import { getNonce } from "../utils/nonce";
56

67
// Bundler is configured to load this as a processed minified CSS-string
78
import styles from "../css/styles.css";
89

9-
const styleElementMap: Map<Document, HTMLStyleElement> = new Map();
10+
const styleElementMap: Map<Document | ShadowRoot, HTMLStyleElement> = new Map();
1011

1112
/**
1213
* Injects CSS code into the document's <head>
1314
*/
1415
export const useStyleSheet = (nodeRef: RefObject<HTMLDivElement>): void => {
1516
useIsomorphicLayoutEffect(() => {
16-
const parentDocument = nodeRef.current ? nodeRef.current.ownerDocument : document;
17+
const parentDocument = nodeRef.current
18+
? !!getShadowRoot(nodeRef.current)
19+
? getShadowRoot(nodeRef.current)
20+
: nodeRef.current.ownerDocument
21+
: document;
1722

18-
if (typeof parentDocument !== "undefined" && !styleElementMap.has(parentDocument)) {
19-
const styleElement = parentDocument.createElement("style");
23+
if (parentDocument && !styleElementMap.has(parentDocument)) {
24+
const styleElement = document.createElement("style");
2025
styleElement.innerHTML = styles;
2126
styleElementMap.set(parentDocument, styleElement);
2227

2328
// Conform to CSP rules by setting `nonce` attribute to the inline styles
2429
const nonce = getNonce();
2530
if (nonce) styleElement.setAttribute("nonce", nonce);
26-
27-
parentDocument.head.appendChild(styleElement);
31+
!!getShadowRoot(nodeRef.current)
32+
? parentDocument.appendChild(styleElement)
33+
: parentDocument.head.appendChild(styleElement);
2834
}
2935
}, []);
3036
};

src/utils/shadowRoot.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export const getShadowRoot = (node: any) => {
2+
let parent = node && node.parentNode;
3+
while (parent) {
4+
if (parent.toString() === "[object ShadowRoot]") {
5+
return parent;
6+
}
7+
parent = parent.parentNode;
8+
}
9+
return null;
10+
};

0 commit comments

Comments
 (0)