|
| 1 | +/* eslint-disable no-extra-boolean-cast */ |
1 | 2 | import { RefObject } from "react"; |
2 | | - |
3 | 3 | import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect"; |
| 4 | +import { getOwnerDocument } from "../utils/ownerDocument"; |
4 | 5 | import { getNonce } from "../utils/nonce"; |
5 | 6 |
|
6 | 7 | // Bundler is configured to load this as a processed minified CSS-string |
7 | 8 | import styles from "../css/styles.css"; |
8 | 9 |
|
9 | | -const styleElementMap: Map<Document, HTMLStyleElement> = new Map(); |
| 10 | +const styleElementMap: Map<Document | ShadowRoot, HTMLStyleElement> = new Map(); |
10 | 11 |
|
11 | 12 | /** |
12 | 13 | * Injects CSS code into the document's <head> |
13 | 14 | */ |
14 | 15 | export const useStyleSheet = (nodeRef: RefObject<HTMLDivElement>): void => { |
15 | 16 | useIsomorphicLayoutEffect(() => { |
16 | | - const parentDocument = nodeRef.current ? nodeRef.current.ownerDocument : document; |
17 | | - |
18 | | - if (typeof parentDocument !== "undefined" && !styleElementMap.has(parentDocument)) { |
19 | | - const styleElement = parentDocument.createElement("style"); |
| 17 | + const ownerDocument = getOwnerDocument(nodeRef.current); |
| 18 | + const parentDocument = ownerDocument || document; |
| 19 | + if ( |
| 20 | + parentDocument && |
| 21 | + typeof parentDocument !== "undefined" && |
| 22 | + !styleElementMap.has(parentDocument) |
| 23 | + ) { |
| 24 | + const styleElement = document.createElement("style"); |
20 | 25 | styleElement.innerHTML = styles; |
21 | 26 | styleElementMap.set(parentDocument, styleElement); |
22 | 27 |
|
23 | 28 | // Conform to CSP rules by setting `nonce` attribute to the inline styles |
24 | 29 | const nonce = getNonce(); |
25 | 30 | if (nonce) styleElement.setAttribute("nonce", nonce); |
26 | | - |
27 | | - parentDocument.head.appendChild(styleElement); |
| 31 | + if (parentDocument instanceof ShadowRoot) { |
| 32 | + parentDocument.appendChild(styleElement); |
| 33 | + } else { |
| 34 | + parentDocument.head.appendChild(styleElement); |
| 35 | + } |
28 | 36 | } |
29 | 37 | }, []); |
30 | 38 | }; |
0 commit comments