All files / config withTheme.js

90.48% Statements 19/21
83.33% Branches 15/18
100% Functions 5/5
90.48% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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              26x 110x   26x     45x   45x       45x                   45x 45x               45x 10x   35x             65x           65x 15x 10x     15x 15x     50x 50x        
import React from 'react';
import deepmerge from 'deepmerge';
import hoistNonReactStatics from 'hoist-non-react-statics';
 
import { ThemeConsumer } from './ThemeProvider';
import DefaultTheme from './theme';
 
const isClassComponent = Component =>
  Boolean(Component.prototype && Component.prototype.isReactComponent);
 
const withTheme = (WrappedComponent, themeKey) => {
  class ThemedComponent extends React.Component {
    render() {
      const { forwardedRef, children, ...rest } = this.props;
 
      return (
        <ThemeConsumer>
          {context => {
            // If user isn't using ThemeProvider
            Iif (!context) {
              const props = { ...rest, theme: DefaultTheme, children };
 
              return isClassComponent(WrappedComponent) ? (
                <WrappedComponent ref={forwardedRef} {...props} />
              ) : (
                <WrappedComponent {...props} />
              );
            }
 
            const { theme, updateTheme, replaceTheme } = context;
            const props = {
              theme,
              updateTheme,
              replaceTheme,
              ...deepmerge((themeKey && theme[themeKey]) || {}, rest),
              children,
            };
 
            if (isClassComponent(WrappedComponent)) {
              return <WrappedComponent ref={forwardedRef} {...props} />;
            }
            return <WrappedComponent {...props} />;
          }}
        </ThemeConsumer>
      );
    }
  }
 
  const name = themeKey
    ? `Themed.${themeKey}`
    : `Themed.${WrappedComponent.displayName ||
        WrappedComponent.name ||
        'Component'}`;
 
  if (isClassComponent(WrappedComponent)) {
    const forwardRef = (props, ref) => (
      <ThemedComponent {...props} forwardedRef={ref} />
    );
 
    forwardRef.displayName = name;
    return hoistNonReactStatics(React.forwardRef(forwardRef), WrappedComponent);
  }
 
  ThemedComponent.displayName = name;
  return ThemedComponent;
};
 
export default withTheme;