forked from primer/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThemeProvider.tsx
240 lines (208 loc) · 7.54 KB
/
ThemeProvider.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import React from 'react'
import {ThemeProvider as SCThemeProvider} from 'styled-components'
import defaultTheme from './theme'
import deepmerge from 'deepmerge'
const defaultColorMode = 'day'
const defaultDayScheme = 'light'
const defaultNightScheme = 'dark'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Theme = {[key: string]: any}
type ColorMode = 'day' | 'night'
type ColorModeWithAuto = ColorMode | 'auto'
export type ThemeProviderProps = {
theme?: Theme
colorMode?: ColorModeWithAuto
dayScheme?: string
nightScheme?: string
preventSSRMismatch?: boolean
}
const ThemeContext = React.createContext<{
theme?: Theme
colorScheme?: string
colorMode?: ColorModeWithAuto
resolvedColorMode?: ColorMode
resolvedColorScheme?: string
dayScheme?: string
nightScheme?: string
setColorMode: React.Dispatch<React.SetStateAction<ColorModeWithAuto>>
setDayScheme: React.Dispatch<React.SetStateAction<string>>
setNightScheme: React.Dispatch<React.SetStateAction<string>>
}>({
setColorMode: () => null,
setDayScheme: () => null,
setNightScheme: () => null
})
// inspired from __NEXT_DATA__, we use application/json to avoid CSRF policy with inline scripts
const getServerHandoff = () => {
try {
const serverData = document.getElementById('__PRIMER_DATA__')?.textContent
if (serverData) return JSON.parse(serverData)
} catch (error) {
// if document/element does not exist or JSON is invalid, supress error
}
return {}
}
export const ThemeProvider: React.FC<ThemeProviderProps> = ({children, ...props}) => {
// Get fallback values from parent ThemeProvider (if exists)
const {
theme: fallbackTheme,
colorMode: fallbackColorMode,
dayScheme: fallbackDayScheme,
nightScheme: fallbackNightScheme
} = useTheme()
// Initialize state
const theme = props.theme ?? fallbackTheme ?? defaultTheme
const {resolvedServerColorMode} = getServerHandoff()
const resolvedColorModePassthrough = React.useRef(resolvedServerColorMode)
const [colorMode, setColorMode] = React.useState(props.colorMode ?? fallbackColorMode ?? defaultColorMode)
const [dayScheme, setDayScheme] = React.useState(props.dayScheme ?? fallbackDayScheme ?? defaultDayScheme)
const [nightScheme, setNightScheme] = React.useState(props.nightScheme ?? fallbackNightScheme ?? defaultNightScheme)
const systemColorMode = useSystemColorMode()
const resolvedColorMode = resolvedColorModePassthrough.current || resolveColorMode(colorMode, systemColorMode)
const colorScheme = chooseColorScheme(resolvedColorMode, dayScheme, nightScheme)
const {resolvedTheme, resolvedColorScheme} = React.useMemo(
() => applyColorScheme(theme, colorScheme),
[theme, colorScheme]
)
// this effect will only run on client
React.useEffect(
function updateColorModeAfterServerPassthrough() {
const resolvedColorModeOnClient = resolveColorMode(colorMode, systemColorMode)
if (resolvedColorModePassthrough.current) {
// if the resolved color mode passed on from the server is not the resolved color mode on client, change it!
if (resolvedColorModePassthrough.current !== resolvedColorModeOnClient) {
window.setTimeout(() => {
// override colorMode to whatever is resolved on the client to get a re-render
setColorMode(resolvedColorModeOnClient)
// immediately after that, set the colorMode to what the user passed to respond to system color mode changes
setColorMode(colorMode)
})
}
resolvedColorModePassthrough.current = null
}
},
[colorMode, systemColorMode]
)
// Update state if props change
React.useEffect(() => {
setColorMode(props.colorMode ?? fallbackColorMode ?? defaultColorMode)
}, [props.colorMode, fallbackColorMode])
React.useEffect(() => {
setDayScheme(props.dayScheme ?? fallbackDayScheme ?? defaultDayScheme)
}, [props.dayScheme, fallbackDayScheme])
React.useEffect(() => {
setNightScheme(props.nightScheme ?? fallbackNightScheme ?? defaultNightScheme)
}, [props.nightScheme, fallbackNightScheme])
return (
<ThemeContext.Provider
value={{
theme: resolvedTheme,
colorScheme,
colorMode,
resolvedColorMode,
resolvedColorScheme,
dayScheme,
nightScheme,
setColorMode,
setDayScheme,
setNightScheme
}}
>
<SCThemeProvider theme={resolvedTheme}>
{children}
{props.preventSSRMismatch ? (
<script
type="application/json"
id="__PRIMER_DATA__"
dangerouslySetInnerHTML={{__html: JSON.stringify({resolvedServerColorMode: resolvedColorMode})}}
/>
) : null}
</SCThemeProvider>
</ThemeContext.Provider>
)
}
export function useTheme() {
return React.useContext(ThemeContext)
}
export function useColorSchemeVar(values: Partial<Record<string, string>>, fallback: string) {
const {colorScheme = ''} = useTheme()
return values[colorScheme] ?? fallback
}
function useSystemColorMode() {
const [systemColorMode, setSystemColorMode] = React.useState(getSystemColorMode)
React.useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const media = window?.matchMedia?.('(prefers-color-scheme: dark)')
function handleChange(event: MediaQueryListEvent) {
const isNight = event.matches
setSystemColorMode(isNight ? 'night' : 'day')
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (media) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (media.addEventListener !== undefined) {
media.addEventListener('change', handleChange)
return function cleanup() {
media.removeEventListener('change', handleChange)
}
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
else if (media.addListener !== undefined) {
media.addListener(handleChange)
return function cleanup() {
media.removeListener(handleChange)
}
}
}
}, [])
return systemColorMode
}
function getSystemColorMode(): ColorMode {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)')?.matches) {
return 'night'
}
return 'day'
}
function resolveColorMode(colorMode: ColorModeWithAuto, systemColorMode: ColorMode) {
switch (colorMode) {
case 'auto':
return systemColorMode
default:
return colorMode
}
}
function chooseColorScheme(colorMode: ColorMode, dayScheme: string, nightScheme: string) {
switch (colorMode) {
case 'day':
return dayScheme
case 'night':
return nightScheme
}
}
function applyColorScheme(
theme: Theme,
colorScheme: string
): {resolvedTheme: Theme; resolvedColorScheme: string | undefined} {
if (!theme.colorSchemes) {
return {
resolvedTheme: theme,
resolvedColorScheme: undefined
}
}
if (!theme.colorSchemes[colorScheme]) {
// eslint-disable-next-line no-console
console.error(`\`${colorScheme}\` scheme not defined in \`theme.colorSchemes\``)
// Apply the first defined color scheme
const defaultColorScheme = Object.keys(theme.colorSchemes)[0]
return {
resolvedTheme: deepmerge(theme, theme.colorSchemes[defaultColorScheme]),
resolvedColorScheme: defaultColorScheme
}
}
return {
resolvedTheme: deepmerge(theme, theme.colorSchemes[colorScheme]),
resolvedColorScheme: colorScheme
}
}
export default ThemeProvider