11import { DARK , LIGHT } from "../../constants" ;
22import { ColorSchemePreference , ResolvedScheme , useStore } from "../../utils" ;
3- import { useEffect } from "react" ;
43import { noFOUCScript } from "./no-fouc" ;
54
65let media : MediaQueryList ,
@@ -36,17 +35,18 @@ export interface CoreProps {
3635
3736/** Modify transition globally to avoid patched transitions */
3837const modifyTransition = ( themeTransition = "none" , nonce = "" ) => {
39- const css = document . createElement ( "style" ) ;
38+ const doc = document ;
39+ const css = doc . createElement ( "style" ) ;
4040 /** split by ';' to prevent CSS injection */
4141 css . textContent = `*,*:after,*:before{transition:${ themeTransition . split ( ";" ) [ 0 ] } !important;}` ;
42- nonce && css . setAttribute ( "nonce" , nonce ) ;
43- document . head . appendChild ( css ) ;
42+ css . setAttribute ( "nonce" , nonce ) ;
43+ doc . head . appendChild ( css ) ;
4444
4545 return ( ) => {
4646 // Force restyle
47- getComputedStyle ( document . body ) ;
47+ getComputedStyle ( doc . body ) ;
4848 // Wait for next tick before removing
49- setTimeout ( ( ) => document . head . removeChild ( css ) , 1 ) ;
49+ setTimeout ( ( ) => doc . head . removeChild ( css ) , 1 ) ;
5050 } ;
5151} ;
5252
@@ -62,14 +62,15 @@ const modifyTransition = (themeTransition = "none", nonce = "") => {
6262 * @source - Source code
6363 */
6464export const Core = ( { t, nonce, k = "o" } : CoreProps ) => {
65+ const isWindowDefined = typeof window != "undefined" ;
6566 // handle client side exceptions when script is not run. <- for client side apps like vite or CRA
66- if ( typeof window !== "undefined" && ! window . m ) noFOUCScript ( k ) ;
67+ if ( isWindowDefined && ! window . q ) noFOUCScript ( k ) ;
6768
68- const [ { m : mode , s : systemMode } , setThemeState ] = useStore ( ) ;
69+ const [ { m, s } , setThemeState ] = useStore ( ) ;
6970
70- useEffect ( ( ) => {
71+ if ( ! updateDOM && isWindowDefined ) {
7172 // store global functions to local variables to avoid any interference
72- [ media , updateDOM ] = [ m , u ] ;
73+ [ media , updateDOM ] = [ q , u ] ;
7374 /** Updating media: prefers-color-scheme*/
7475 media . addEventListener ( "change" , ( ) =>
7576 setThemeState ( state => ( { ...state , s : media . matches ? DARK : LIGHT } ) ) ,
@@ -78,13 +79,12 @@ export const Core = ({ t, nonce, k = "o" }: CoreProps) => {
7879 addEventListener ( "storage" , ( e : StorageEvent ) : void => {
7980 e . key === k && setThemeState ( state => ( { ...state , m : e . newValue as ColorSchemePreference } ) ) ;
8081 } ) ;
81- } , [ ] ) ;
82-
83- useEffect ( ( ) => {
82+ }
83+ if ( updateDOM ) {
8484 const restoreTransitions = modifyTransition ( t , nonce ) ;
85- updateDOM ( mode , systemMode ) ;
85+ updateDOM ( m , s ) ;
8686 restoreTransitions ( ) ;
87- } , [ systemMode , mode , t , nonce ] ) ;
87+ }
8888
8989 return < Script { ...{ n : nonce , k } } /> ;
9090} ;
0 commit comments