2020-11-23 00:07:32 +01:00
|
|
|
import React, { createContext, useContext, useEffect, useState } from 'react'
|
2021-01-02 17:55:08 +01:00
|
|
|
import { Appearance } from 'react-native'
|
2020-11-29 18:08:31 +01:00
|
|
|
import { useSelector } from 'react-redux'
|
2020-12-13 14:04:25 +01:00
|
|
|
import { ColorDefinitions, getTheme } from '@utils/styles/themes'
|
|
|
|
import { getSettingsTheme } from '@utils/slices/settingsSlice'
|
2021-01-02 17:55:08 +01:00
|
|
|
import { throttle } from 'lodash'
|
2020-11-23 00:07:32 +01:00
|
|
|
|
2020-11-29 18:08:31 +01:00
|
|
|
type ContextType = {
|
2020-11-23 00:07:32 +01:00
|
|
|
mode: 'light' | 'dark'
|
|
|
|
theme: { [key in ColorDefinitions]: string }
|
2020-11-29 18:08:31 +01:00
|
|
|
setTheme: (theme: 'light' | 'dark') => void
|
|
|
|
}
|
|
|
|
|
2021-03-27 00:02:32 +01:00
|
|
|
const ManageThemeContext = createContext<ContextType>({
|
2020-11-29 18:08:31 +01:00
|
|
|
mode: 'light',
|
|
|
|
theme: getTheme('light'),
|
|
|
|
setTheme: () => {}
|
2020-11-23 00:07:32 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
export const useTheme = () => useContext(ManageThemeContext)
|
|
|
|
|
2021-01-12 00:12:44 +01:00
|
|
|
const useColorSchemeDelay = (delay = 500) => {
|
2021-01-02 17:55:08 +01:00
|
|
|
const [colorScheme, setColorScheme] = React.useState(
|
|
|
|
Appearance.getColorScheme()
|
|
|
|
)
|
|
|
|
const onColorSchemeChange = React.useCallback(
|
|
|
|
throttle(
|
|
|
|
({ colorScheme }) => {
|
|
|
|
setColorScheme(colorScheme)
|
|
|
|
},
|
|
|
|
delay,
|
|
|
|
{
|
|
|
|
leading: false
|
|
|
|
}
|
|
|
|
),
|
|
|
|
[]
|
|
|
|
)
|
|
|
|
React.useEffect(() => {
|
|
|
|
Appearance.addChangeListener(onColorSchemeChange)
|
|
|
|
return () => {
|
|
|
|
onColorSchemeChange.cancel()
|
|
|
|
Appearance.removeChangeListener(onColorSchemeChange)
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
return colorScheme
|
|
|
|
}
|
|
|
|
|
2020-11-23 00:07:32 +01:00
|
|
|
const ThemeManager: React.FC = ({ children }) => {
|
2021-01-02 17:55:08 +01:00
|
|
|
const osTheme = useColorSchemeDelay()
|
2020-11-29 18:08:31 +01:00
|
|
|
const userTheme = useSelector(getSettingsTheme)
|
|
|
|
const currentMode =
|
2020-12-01 00:44:28 +01:00
|
|
|
userTheme === 'auto' ? (osTheme as 'light' | 'dark') : userTheme
|
2020-11-29 18:08:31 +01:00
|
|
|
|
|
|
|
const [mode, setMode] = useState(currentMode)
|
2020-11-23 00:07:32 +01:00
|
|
|
|
2020-11-29 18:08:31 +01:00
|
|
|
const setTheme = (theme: 'light' | 'dark') => setMode(theme)
|
2020-11-23 00:07:32 +01:00
|
|
|
|
|
|
|
useEffect(() => {
|
2020-11-29 18:08:31 +01:00
|
|
|
setMode(currentMode)
|
|
|
|
}, [currentMode])
|
2020-11-23 00:07:32 +01:00
|
|
|
|
|
|
|
return (
|
|
|
|
<ManageThemeContext.Provider
|
|
|
|
value={{
|
|
|
|
mode: mode,
|
|
|
|
theme: getTheme(mode),
|
2020-11-29 18:08:31 +01:00
|
|
|
setTheme: setTheme
|
2020-11-23 00:07:32 +01:00
|
|
|
}}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</ManageThemeContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ThemeManager
|