-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
theme-provider.js
61 lines (55 loc) · 1.49 KB
/
theme-provider.js
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
// @flow
import * as React from 'react'
import { ThemeContext } from '@emotion/core'
import weakMemoize from '@emotion/weak-memoize'
let getTheme = (outerTheme: Object, theme: Object | (Object => Object)) => {
if (typeof theme === 'function') {
const mergedTheme = theme(outerTheme)
if (
process.env.NODE_ENV !== 'production' &&
(mergedTheme == null ||
typeof mergedTheme !== 'object' ||
Array.isArray(mergedTheme))
) {
throw new Error(
'[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!'
)
}
return mergedTheme
}
if (
process.env.NODE_ENV !== 'production' &&
(theme == null || typeof theme !== 'object' || Array.isArray(theme))
) {
throw new Error(
'[ThemeProvider] Please make your theme prop a plain object'
)
}
return { ...outerTheme, ...theme }
}
let createCacheWithTheme = weakMemoize(outerTheme => {
return weakMemoize(theme => {
return getTheme(outerTheme, theme)
})
})
type Props = {
theme: Object | (Object => Object),
children: React.Node
}
let ThemeProvider = (props: Props) => {
return (
<ThemeContext.Consumer>
{theme => {
if (props.theme !== theme) {
theme = createCacheWithTheme(theme)(props.theme)
}
return (
<ThemeContext.Provider value={theme}>
{props.children}
</ThemeContext.Provider>
)
}}
</ThemeContext.Consumer>
)
}
export default ThemeProvider