save darkmode choice

Co-authored-by: Félix Legrelle <legrelle.f@gmail.com>
pull/2360/head
Lucas Stoebner 2022-10-26 19:55:08 +02:00 committed by Johan Girod
parent de9e890666
commit a3dd43c4c2
1 changed files with 22 additions and 6 deletions

View File

@ -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<DarkModeContextType>([
false,
() => {
@ -11,14 +30,11 @@ export const DarkModeContext = React.createContext<DarkModeContextType>([
])
export const DarkModeProvider: React.FC = ({ children }) => {
const [darkMode, _setDarkMode] = React.useState<boolean>(
import.meta.env.DEV && typeof window !== 'undefined' ?
(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) :
false
)
const [darkMode, _setDarkMode] = React.useState<boolean>(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 (
<DarkModeContext.Provider value={[ darkMode, setDarkMode ]}>
<DarkModeContext.Provider value={[darkMode, setDarkMode]}>
{children}
</DarkModeContext.Provider>
)