UNPKG

2.56 kBJavaScriptView Raw
1var __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};
12import React from 'react';
13import deepmerge from 'deepmerge';
14import hoistNonReactStatics from 'hoist-non-react-statics';
15import { ThemeConsumer } from './ThemeProvider';
16import DefaultTheme from './theme';
17const isClassComponent = (Component) => Boolean(Component.prototype && Component.prototype.isReactComponent);
18const 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};
44function 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}
54export default withTheme;