Skip to content

Commit 69fd951

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

File tree

3 files changed

+24
-21
lines changed

3 files changed

+24
-21
lines changed

src/hooks/useStyleSheet.ts

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable no-extra-boolean-cast */
22
import { RefObject } from "react";
33
import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
4-
import { getShadowRoot } from "../utils/shadowRoot";
4+
import { getOwnerDocument } from "../utils/ownerDocument";
55
import { getNonce } from "../utils/nonce";
66

77
// Bundler is configured to load this as a processed minified CSS-string
@@ -14,23 +14,25 @@ const styleElementMap: Map<Document | ShadowRoot, HTMLStyleElement> = new Map();
1414
*/
1515
export const useStyleSheet = (nodeRef: RefObject<HTMLDivElement>): void => {
1616
useIsomorphicLayoutEffect(() => {
17-
const parentDocument = nodeRef.current
18-
? !!getShadowRoot(nodeRef.current)
19-
? getShadowRoot(nodeRef.current)
20-
: nodeRef.current.ownerDocument
21-
: document;
22-
23-
if (parentDocument && !styleElementMap.has(parentDocument)) {
17+
const ownerDocument = getOwnerDocument(nodeRef.current);
18+
const parentDocument = ownerDocument || document;
19+
if (
20+
parentDocument &&
21+
typeof parentDocument !== "undefined" &&
22+
!styleElementMap.has(parentDocument)
23+
) {
2424
const styleElement = document.createElement("style");
2525
styleElement.innerHTML = styles;
2626
styleElementMap.set(parentDocument, styleElement);
2727

2828
// Conform to CSP rules by setting `nonce` attribute to the inline styles
2929
const nonce = getNonce();
3030
if (nonce) styleElement.setAttribute("nonce", nonce);
31-
!!getShadowRoot(nodeRef.current)
32-
? parentDocument.appendChild(styleElement)
33-
: parentDocument.head.appendChild(styleElement);
31+
if (parentDocument instanceof ShadowRoot) {
32+
parentDocument.appendChild(styleElement);
33+
} else {
34+
parentDocument.head.appendChild(styleElement);
35+
}
3436
}
3537
}, []);
3638
};

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+
};

src/utils/shadowRoot.ts

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)