-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseTheme.tsx
85 lines (74 loc) · 2.19 KB
/
useTheme.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, { useContext, useState, useEffect } from 'react'
import { Appearance } from 'react-native'
import { retrieveData, storeData } from './useStorage'
import { ThemeColors, DefaultTheme, DarkTheme, PinkTheme } from '../constants/Colors'
const STORAGE_KEY = 'THEME_ID'
const ThemeContext = React.createContext(null)
export function getTheme (mode: string) {
if (mode === 'standard') {
if (Appearance.getColorScheme()) {
mode = Appearance.getColorScheme()
} else {
mode = 'light'
}
}
const Theme = {}
for (const key in ThemeColors) {
Theme[key] = ThemeColors[key][mode]
}
return Theme
}
export function getThemeId () {
const { themeId } = useContext(ThemeContext)
return themeId
}
export function getNavigatorTheme () {
const themeId = getThemeId()
if (themeId === 'light') {
return DefaultTheme
} else if (themeId === 'dark') {
return DarkTheme
} else if (themeId === 'pink') {
return PinkTheme
} else if (Appearance.getColorScheme() === 'light') {
return DefaultTheme
} else {
return DarkTheme
}
}
export function ThemeContextProvider ({ children }) {
const [themeId, setThemeId] = useState('')
useEffect(() => {
(async () => {
const storedThemeId = await retrieveData(STORAGE_KEY)
if (storedThemeId) {
setThemeId(storedThemeId)
} else if (Appearance.getColorScheme()) {
setThemeId('standard')
} else {
setThemeId('light')
}
})()
}, [])
return (
<ThemeContext.Provider value={{ themeId, setThemeId }}>
{themeId ? children : null}
</ThemeContext.Provider>
)
}
export function withTheme (Component) {
return props => {
const { themeId, setThemeId } = useContext(ThemeContext)
function setTheme (themeId: string) {
storeData(STORAGE_KEY, themeId)
setThemeId(themeId)
}
return (
<Component
{...props}
theme={getTheme(themeId)}
setTheme={setTheme}
/>
)
}
}