1
1
/* eslint-disable no-extra-boolean-cast */
2
2
import { RefObject } from "react" ;
3
3
import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect" ;
4
- import { getShadowRoot } from "../utils/shadowRoot " ;
4
+ import { getOwnerDocument } from "../utils/ownerDocument " ;
5
5
import { getNonce } from "../utils/nonce" ;
6
6
7
7
// Bundler is configured to load this as a processed minified CSS-string
@@ -14,23 +14,25 @@ const styleElementMap: Map<Document | ShadowRoot, HTMLStyleElement> = new Map();
14
14
*/
15
15
export const useStyleSheet = ( nodeRef : RefObject < HTMLDivElement > ) : void => {
16
16
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
+ ) {
24
24
const styleElement = document . createElement ( "style" ) ;
25
25
styleElement . innerHTML = styles ;
26
26
styleElementMap . set ( parentDocument , styleElement ) ;
27
27
28
28
// Conform to CSP rules by setting `nonce` attribute to the inline styles
29
29
const nonce = getNonce ( ) ;
30
30
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
+ }
34
36
}
35
37
} , [ ] ) ;
36
38
} ;
0 commit comments