11/* eslint-disable no-extra-boolean-cast */
22import { RefObject } from "react" ;
33import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect" ;
4- import { getShadowRoot } from "../utils/shadowRoot " ;
4+ import { getOwnerDocument } from "../utils/ownerDocument " ;
55import { 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 */
1515export 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} ;
0 commit comments