github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/ccl/src/views/shared/containers/licenseSwap/index.tsx (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Licensed as a CockroachDB Enterprise file under the Cockroach Community
     4  // License (the "License"); you may not use this file except in compliance with
     5  // the License. You may obtain a copy of the License at
     6  //
     7  //     https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
     8  
     9  import _ from "lodash";
    10  import React from "react";
    11  import { connect } from "react-redux";
    12  
    13  import { selectEnterpriseEnabled } from "src/redux/license";
    14  import { AdminUIState } from "src/redux/state";
    15  
    16  // Some of the type magic is adapted from @types/react-redux.
    17  // Some of the code is adapted from react-redux.
    18  
    19  type ComponentClass<P> = React.ComponentClass<P>;
    20  type StatelessComponent<P> = React.StatelessComponent<P>;
    21  type Component<P> = ComponentClass<P> | StatelessComponent<P>;
    22  
    23  function getComponentName<P>(wrappedComponent: Component<P>) {
    24    return wrappedComponent.displayName
    25      || wrappedComponent.name
    26      || "Component";
    27  }
    28  
    29  function combineNames(a: string, b: string) {
    30    if (a === b) {
    31      return a;
    32    }
    33  
    34    return a + "," + b;
    35  }
    36  
    37  interface OwnProps {
    38    enterpriseEnabled: boolean;
    39  }
    40  
    41  function mapStateToProps(state: AdminUIState): OwnProps {
    42    return {
    43      enterpriseEnabled: selectEnterpriseEnabled(state),
    44    };
    45  }
    46  
    47  /**
    48   * LicenseSwap is a higher-order component that swaps out two components based
    49   * on the current license status.
    50   */
    51  export default function swapByLicense<TProps>(
    52    // tslint:disable:variable-name
    53    OSSComponent: React.ComponentClass<TProps>,
    54    CCLComponent: React.ComponentClass<TProps>,
    55    // tslint:enable:variable-name
    56  ) {
    57    const ossName = getComponentName(OSSComponent);
    58    const cclName = getComponentName(CCLComponent);
    59  
    60    class LicenseSwap extends React.Component<TProps & OwnProps & any> {
    61      public static displayName = `LicenseSwap(${combineNames(ossName, cclName)})`;
    62  
    63      render() {
    64        const props = _.omit(this.props, ["enterpriseEnabled"]);
    65  
    66        if (!this.props.enterpriseEnabled) {
    67          return <OSSComponent {...props as TProps} />;
    68        }
    69        return <CCLComponent {...props as TProps} />;
    70      }
    71    }
    72  
    73    return connect<OwnProps, null, TProps, AdminUIState>(mapStateToProps)(LicenseSwap);
    74  }