diff --git a/src/OnboardingSPA/components/ThemeContextProvider/index.js b/src/OnboardingSPA/components/ThemeContextProvider/index.js index f03d9eb85..8f1a2cd06 100644 --- a/src/OnboardingSPA/components/ThemeContextProvider/index.js +++ b/src/OnboardingSPA/components/ThemeContextProvider/index.js @@ -1,20 +1,37 @@ import { useState, useEffect, createContext } from '@wordpress/element'; +import { useSelect, useDispatch } from '@wordpress/data'; +import { store as nfdOnboardingStore } from '../../store'; +import { setFlow } from '../../utils/api/flow'; import { THEME_DARK, THEME_LIGHT } from '../../../constants'; const ThemeContext = createContext(); -function getPreferredColorScheme() { +function usePreferredColorScheme( currentData ) { + if ( currentData.sitegenThemeMode ) { + return currentData.sitegenThemeMode; + } + if ( window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches ) { return THEME_DARK; } + return THEME_LIGHT; } const ThemeProvider = ( { children } ) => { - const [ theme, setTheme ] = useState( getPreferredColorScheme ); + const { currentData } = useSelect( ( select ) => { + return { + currentData: + select( nfdOnboardingStore ).getCurrentOnboardingData(), + }; + } ); + + const preferredColorScheme = usePreferredColorScheme( currentData ); + const [ theme, setTheme ] = useState( preferredColorScheme ); + const { setCurrentOnboardingData } = useDispatch( nfdOnboardingStore ); useEffect( () => { const colorSchemeMediaQuery = window.matchMedia( @@ -22,7 +39,11 @@ const ThemeProvider = ( { children } ) => { ); const handleChange = ( event ) => { - setTheme( event.matches ? THEME_DARK : THEME_LIGHT ); + const newTheme = event.matches ? THEME_DARK : THEME_LIGHT; + setTheme( newTheme ); + currentData.sitegenThemeMode = newTheme; + setCurrentOnboardingData( currentData ); + setFlow( currentData ); }; colorSchemeMediaQuery.addEventListener( 'change', handleChange ); @@ -33,9 +54,14 @@ const ThemeProvider = ( { children } ) => { }, [] ); const toggleTheme = () => { - setTheme( ( prevTheme ) => - prevTheme === THEME_DARK ? THEME_LIGHT : THEME_DARK - ); + setTheme( ( prevTheme ) => { + const newTheme = + prevTheme === THEME_DARK ? THEME_LIGHT : THEME_DARK; + currentData.sitegenThemeMode = newTheme; + setCurrentOnboardingData( currentData ); + setFlow( currentData ); + return newTheme; + } ); }; return (