blob: 861db6ae9c0896c1683c11ab353ad993c96fd4e4 [file] [log] [blame]
svishnevd3886bb2018-01-08 15:21:46 +02001/*!
2 * Copyright © 2016-2017 European Support Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13 * or implied. See the License for the specific language governing
14 * permissions and limitations under the License.
15 */
16
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020017/**
svishnevd3886bb2018-01-08 15:21:46 +020018 * Feature toggling decorator
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020019 * usage:
20 *
svishnevd3886bb2018-01-08 15:21:46 +020021 * @featureToggle('FeatureName')
22 * class Example extends React.Component {
23 * render() {
24 * return (<div>test feature</div>);
25 * }
26 * }
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020027 *
28 * OR
29 *
svishnevd3886bb2018-01-08 15:21:46 +020030 * const TestFeature = () => (<div>test feature</div>)
31 * export default featureToggle('FeatureName')(TestFeature)
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020032 *
svishnevd3886bb2018-01-08 15:21:46 +020033 */
34
35import React from 'react';
36import PropTypes from 'prop-types';
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020037import { connect } from 'react-redux';
svishnevd3886bb2018-01-08 15:21:46 +020038
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020039export const FeatureComponent = props => {
40 const { features = [], featureName, InnerComponent, ...otherProps } = props;
svishnevea5e43c2018-04-15 09:06:57 +030041 const OnComp = InnerComponent.OnComp
42 ? InnerComponent.OnComp
43 : InnerComponent;
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020044
45 return !!features.find(el => el.name === featureName && el.active) ? (
svishnevea5e43c2018-04-15 09:06:57 +030046 <OnComp {...otherProps} />
47 ) : InnerComponent.OffComp ? (
48 <InnerComponent.OffComp {...otherProps} />
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020049 ) : null;
svishnevd3886bb2018-01-08 15:21:46 +020050};
51
52FeatureComponent.propTypes = {
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020053 features: PropTypes.array,
54 featureName: PropTypes.string.isRequired
svishnevd3886bb2018-01-08 15:21:46 +020055};
56
svishnevd3886bb2018-01-08 15:21:46 +020057export default function featureToggle(featureName) {
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020058 return InnerComponent => {
59 return connect(({ features }) => {
60 return { features, featureName, InnerComponent };
61 })(FeatureComponent);
62 };
svishnevd3886bb2018-01-08 15:21:46 +020063}