-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcreate-theme-provider.js
More file actions
88 lines (69 loc) · 2.37 KB
/
create-theme-provider.js
File metadata and controls
88 lines (69 loc) · 2.37 KB
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
// @flow
import React, { type Node, type Context } from 'react';
import warning from 'tiny-warning';
import PropTypes from 'prop-types';
import isObject from './is-object';
type ThemeFunction<Theme> = (outerTheme: Theme) => $NonMaybeType<Theme>;
type ThemeOrThemeFunction<Theme> = $NonMaybeType<Theme> | ThemeFunction<Theme>;
export type ThemeProviderProps<Theme> = {
children: Node,
theme: ThemeOrThemeFunction<Theme>
};
export default function createThemeProvider<Theme>(context: Context<Theme>) {
class ThemeProvider extends React.Component<ThemeProviderProps<Theme>> {
// Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
getTheme(outerTheme: Theme) {
if (
this.props.theme !== this.lastTheme ||
outerTheme !== this.lastOuterTheme ||
!this.cachedTheme
) {
this.lastOuterTheme = outerTheme;
this.lastTheme = this.props.theme;
if (typeof this.lastTheme === 'function') {
const theme: ThemeFunction<Theme> = (this.props.theme: any);
this.cachedTheme = theme(outerTheme);
warning(
isObject(this.cachedTheme),
'[ThemeProvider] Please return an object from your theme function'
);
} else {
const theme: Theme = (this.props.theme: any);
warning(
isObject(theme),
'[ThemeProvider] Please make your theme prop a plain object'
);
this.cachedTheme = outerTheme ? { ...outerTheme, ...theme } : theme;
}
}
return this.cachedTheme;
}
cachedTheme: Theme;
lastOuterTheme: Theme;
lastTheme: ThemeOrThemeFunction<Theme>;
renderProvider = (outerTheme: Theme) => {
const { children } = this.props;
return (
<context.Provider value={this.getTheme(outerTheme)}>
{children}
</context.Provider>
);
};
render() {
const { children } = this.props;
if (!children) {
return null;
}
return <context.Consumer>{this.renderProvider}</context.Consumer>;
}
}
if (process.env.NODE_ENV !== 'production') {
ThemeProvider.propTypes = {
// eslint-disable-next-line react/require-default-props
children: PropTypes.node,
theme: PropTypes.oneOfType([PropTypes.shape({}), PropTypes.func])
.isRequired
};
}
return ThemeProvider;
}