Skip to content

Commit 41668c1

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

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

src/hooks/useStyleSheet.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,38 @@
1+
/* eslint-disable no-extra-boolean-cast */
12
import { RefObject } from "react";
2-
33
import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
4+
import { getOwnerDocument } from "../utils/ownerDocument";
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-
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");
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+
if (parentDocument instanceof ShadowRoot) {
32+
parentDocument.appendChild(styleElement);
33+
} else {
34+
parentDocument.head.appendChild(styleElement);
35+
}
2836
}
2937
}, []);
3038
};

src/utils/ownerDocument.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export const getOwnerDocument = (node: HTMLElement | null): ShadowRoot | Document | null => {
2+
let parent = node && node.parentNode;
3+
const ownerDocument = node && node.ownerDocument;
4+
while (parent) {
5+
if (parent instanceof ShadowRoot) {
6+
return parent;
7+
}
8+
parent = parent.parentNode;
9+
}
10+
return ownerDocument;
11+
};

0 commit comments

Comments
 (0)