tooot/src/utils/styles/ThemeManager.tsx

76 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-11-23 00:07:32 +01:00
import React, { createContext, useContext, useEffect, useState } from 'react'
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'
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) => {
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 }) => {
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