From a3dd43c4c2e5c6e8dc6aa787d42e8e04e7ce1ba7 Mon Sep 17 00:00:00 2001 From: Lucas Stoebner Date: Wed, 26 Oct 2022 19:55:08 +0200 Subject: [PATCH] :sparkles: save darkmode choice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: FĂ©lix Legrelle --- site/source/contexts/DarkModeContext.tsx | 28 +++++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/site/source/contexts/DarkModeContext.tsx b/site/source/contexts/DarkModeContext.tsx index b687e055c..067187aa5 100644 --- a/site/source/contexts/DarkModeContext.tsx +++ b/site/source/contexts/DarkModeContext.tsx @@ -2,6 +2,25 @@ import React from 'react' type DarkModeContextType = [boolean, (darkMode: boolean) => void] +const persistDarkMode = (darkMode: boolean) => { + localStorage.setItem('darkMode', darkMode.toString()) +} + +const getDefaultDarkMode = () => { + if (localStorage.getItem('darkMode')) { + return localStorage.getItem('darkMode') === 'true' + } + + if (import.meta.env.DEV && typeof window !== 'undefined') { + return ( + window.matchMedia && + window.matchMedia('(prefers-color-scheme: dark)').matches + ) + } + + return false +} + export const DarkModeContext = React.createContext([ false, () => { @@ -11,14 +30,11 @@ export const DarkModeContext = React.createContext([ ]) export const DarkModeProvider: React.FC = ({ children }) => { - const [darkMode, _setDarkMode] = React.useState( - import.meta.env.DEV && typeof window !== 'undefined' ? - (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) : - false - ) + const [darkMode, _setDarkMode] = React.useState(getDefaultDarkMode()) const setDarkMode = (darkMode: boolean) => { _setDarkMode(darkMode) + persistDarkMode(darkMode) // https://www.youtube.com/watch?v=Pr8ETbGz35Q // eslint-disable-next-line no-console @@ -26,7 +42,7 @@ export const DarkModeProvider: React.FC = ({ children }) => { } return ( - + {children} )