1 | var __rest = (this && this.__rest) || function (s, e) {
|
2 | var t = {};
|
3 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
4 | t[p] = s[p];
|
5 | if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
6 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
7 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
8 | t[p[i]] = s[p[i]];
|
9 | }
|
10 | return t;
|
11 | };
|
12 | import React from 'react';
|
13 | import deepmerge from 'deepmerge';
|
14 | import hoistNonReactStatics from 'hoist-non-react-statics';
|
15 | import { ThemeConsumer } from './ThemeProvider';
|
16 | import DefaultTheme from './theme';
|
17 | const isClassComponent = (Component) => Boolean(Component.prototype && Component.prototype.isReactComponent);
|
18 | const ThemedComponent = (WrappedComponent, themeKey, displayName) => {
|
19 | return Object.assign((props, forwardedRef) => {
|
20 | const { children } = props, rest = __rest(props, ["children"]);
|
21 | return (<ThemeConsumer>
|
22 | {(context) => {
|
23 | // If user isn't using ThemeProvider
|
24 | if (!context) {
|
25 | const newProps = Object.assign(Object.assign({}, rest), { theme: DefaultTheme, children });
|
26 | return isClassComponent(WrappedComponent) ? (<WrappedComponent ref={forwardedRef} {...newProps}/>) : (<WrappedComponent {...newProps}/>);
|
27 | }
|
28 | const { theme, updateTheme, replaceTheme } = context;
|
29 | const newProps = Object.assign(Object.assign({ theme,
|
30 | updateTheme,
|
31 | replaceTheme }, deepmerge((themeKey &&
|
32 | theme[themeKey]) ||
|
33 | {}, rest, {
|
34 | clone: false,
|
35 | })), { children });
|
36 | if (isClassComponent(WrappedComponent)) {
|
37 | return <WrappedComponent ref={forwardedRef} {...newProps}/>;
|
38 | }
|
39 | return <WrappedComponent {...newProps}/>;
|
40 | }}
|
41 | </ThemeConsumer>);
|
42 | }, { displayName: displayName });
|
43 | };
|
44 | function withTheme(WrappedComponent, themeKey) {
|
45 | const name = themeKey
|
46 | ? `Themed.${themeKey}`
|
47 | : `Themed.${WrappedComponent.displayName || WrappedComponent.name || 'Component'}`;
|
48 | const Component = ThemedComponent(WrappedComponent, themeKey, name);
|
49 | if (isClassComponent(WrappedComponent)) {
|
50 | return hoistNonReactStatics(React.forwardRef(Component), WrappedComponent);
|
51 | }
|
52 | return Component;
|
53 | }
|
54 | export default withTheme;
|