tooot/src/utils/styles/ThemeManager.tsx

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-11-23 00:07:32 +01:00
import React, { createContext, useContext, useEffect, useState } from 'react'
2020-12-01 00:44:28 +01:00
import { useColorScheme } from 'react-native-appearance'
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'
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
}
export const ManageThemeContext = createContext<ContextType>({
mode: 'light',
theme: getTheme('light'),
setTheme: () => {}
2020-11-23 00:07:32 +01:00
})
export const useTheme = () => useContext(ManageThemeContext)
const ThemeManager: React.FC = ({ children }) => {
2020-12-01 00:44:28 +01:00
const osTheme = useColorScheme()
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