diff --git a/client/src/context/ThemeContext.jsx b/client/src/context/ThemeContext.jsx index 9836cef1..faece552 100644 --- a/client/src/context/ThemeContext.jsx +++ b/client/src/context/ThemeContext.jsx @@ -1,10 +1,8 @@ import React, { useContext, useEffect, useState } from 'react'; - import { ThemeProvider } from '@mui/material/styles'; - import darkTheme from '../config/themes/dark'; import lightTheme from '../config/themes/light'; - +import useLocalStorage from '../hooks/useLocalStorage'; //context for theming export const ThemeContext = React.createContext({ isDarkTheme: undefined, @@ -15,12 +13,29 @@ export const useTheme = () => useContext(ThemeContext); //context provider const ThemeContextProvider = ({ children }) => { - const [isDarkTheme, setDarkTheme] = useState(false); - + const [defaultTheme, setDefaultTheme] = useLocalStorage('DefaultTheme'); + const [isDarkTheme, setDarkTheme] = useLocalStorage('IsDarkTheme'); useEffect(() => { - const currentHour = new Date().getHours(); - setDarkTheme(currentHour >= 20 || currentHour <= 8 ? true : false); - }, [setDarkTheme]); + const darkModeMediaQuery = window.matchMedia( + '(prefers-color-scheme: dark)', + ); + const setTheme = (event) => { + if (event.matches) { + setDefaultTheme(defaultTheme === true ? defaultTheme : null); + setDarkTheme(true); + } else { + setDefaultTheme(false); + setDarkTheme(defaultTheme === false ? defaultTheme : null); + } + }; + setTheme(darkModeMediaQuery); + darkModeMediaQuery.addEventListener('change', setTheme); + setDarkTheme(isDarkTheme); + setDefaultTheme(isDarkTheme ? isDarkTheme : isDarkTheme); + return () => { + darkModeMediaQuery.removeEventListener('change', setTheme); + }; + }, [isDarkTheme]); return ( diff --git a/client/src/hooks/useLocalStorage.js b/client/src/hooks/useLocalStorage.js new file mode 100644 index 00000000..17ea83b0 --- /dev/null +++ b/client/src/hooks/useLocalStorage.js @@ -0,0 +1,22 @@ +import { useState } from 'react'; +const useLocalStorage = (key, initialValue) => { + const [state, setState] = useState(() => { + try { + const value = window.localStorage.getItem(key); + return value != 'null' ? JSON.parse(value) : initialValue; + } catch (error) { + console.log(error); + } + }); + const setValue = (value) => { + try { + const valueToStore = value instanceof Function ? value(state) : value; + window.localStorage.setItem(key, JSON.stringify(valueToStore)); + setState(value); + } catch (error) { + console.log(error); + } + }; + return [state, setValue]; +}; +export default useLocalStorage;