Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/ab-connector / hoc / withAbTest.js
Size: Mime:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

exports.default = withAbTest;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactRedux = require('react-redux');

var _abActions = require('../state/actions/abActions');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AB_TEST_TIMEOUT = 750; // Timeout until first render, if no experimentId is passed
var AB_TEST_INTERVAL = 50; // Interval for checking for google optimize
var AB_TEST_INTERVAL_COUNT = 15; // How often we should check max for google optimize

/**
 * Returns whether google_optimize is defined in the window object.
 *
 * @returns {boolean}
 */
function isGoogleOptimizeDefined() {
  return window.google_optimize !== undefined;
}

/**
 * Returns the variation for the given experimentId if google_optimize is
 * defined in the window object. The variation might be a string from 0 - n, where
 * n is the max number of defined variations.
 *
 * @param {string} experimentId - The Optimize experiment id
 */
function getGoogleOptimizeVariant(experimentId) {
  return isGoogleOptimizeDefined() && window.google_optimize.get(experimentId);
}

/**
 * If the variant returned by google_optimize is 0 or undefined, this returns true.
 *
 * The undefined case only appears if google_optimize is defined but the a/b test is
 * not running for this url.
 *
 * @param {string} experimentId
 */
function shouldRenderOriginal(experimentId) {
  var variant = getGoogleOptimizeVariant(experimentId);
  return Boolean(experimentId) && variant === '0';
}

/**
 *
 * @param {React.Component} Component
 * @param {String} experimentName
 * @param {Object} variantComponents
 */
function withAbTest(Component, experimentName, variantComponents) {
  var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
      _ref$debug = _ref.debug,
      debug = _ref$debug === undefined ? false : _ref$debug,
      _ref$isLocal = _ref.isLocal,
      isLocal = _ref$isLocal === undefined ? false : _ref$isLocal,
      _ref$experimentId = _ref.experimentId,
      experimentId = _ref$experimentId === undefined ? '' : _ref$experimentId;

  // Debug info
  if (debug) {
    console.group('A/B - Connector [HOC]');
    console.log('Component:', Component);
    console.log('experimentName:', experimentName);
    console.log('variantComponents:', variantComponents);
    console.log('debug:', debug);
    console.log('isLocal:', isLocal);
    console.groupEnd();
  }

  var ABComponent = function (_React$Component) {
    _inherits(ABComponent, _React$Component);

    function ABComponent(props) {
      _classCallCheck(this, ABComponent);

      var _this = _possibleConstructorReturn(this, (ABComponent.__proto__ || Object.getPrototypeOf(ABComponent)).call(this, props));

      var optimizePending = props.optimizePending;

      var variant = _this.getExperimentVariant(experimentName);
      var pendingDefined = optimizePending !== undefined;
      var renderOriginalComponent = (isLocal || !pendingDefined || shouldRenderOriginal(experimentId)) && Component;
      var renderVariationComponent = variant && variantComponents[variant];
      _this.state = {
        pendingDefined: pendingDefined,
        // If Optimize is not even pending, it is not loaded due to the order of scripts loaded.
        // In this case we do not have to wait and just render the original component
        renderedComponent: renderVariationComponent || renderOriginalComponent
      };
      _this.getExperimentVariant = _this.getExperimentVariant.bind(_this);
      _this.setRenderedVariant = _this.setRenderedVariant.bind(_this);
      _this.resetTimer = _this.resetTimer.bind(_this);
      _this.initializeTimer = _this.initializeTimer.bind(_this);

      // Debug info
      if (debug) {
        console.group('A/B - Connector [Constructor]');
        console.log('variant:', variant);
        console.log('pedingDefined:', pendingDefined);
        console.log('renderOriginalComponent:', Boolean(renderOriginalComponent));
        console.log('renderVariationComponent:', Boolean(renderVariationComponent));
        console.log('Optimize experimentId', experimentId);
        console.log('Optimize shouldRenderOriginal', shouldRenderOriginal(experimentId));
        console.groupEnd();
      }
      return _this;
    }

    _createClass(ABComponent, [{
      key: 'componentDidMount',
      value: function componentDidMount() {
        var _props = this.props,
            onActivateOptimize = _props.onActivateOptimize,
            onActivateVariant = _props.onActivateVariant;

        var variant = this.getExperimentVariant(experimentName);
        // We only send this info the DataLayer if optimize actually was loaded
        if (this.state.pendingDefined) {
          onActivateOptimize();
        }
        if (!variant && !this.state.renderedComponent) {
          this.initializeTimer();
        } else if (!this.state.renderedComponent) {
          this.setRenderedVariant(variantComponents[variant]);
        }

        // Dispatch info about loaded experiment
        if (variant) {
          onActivateVariant(variant);
        }

        // Debug info
        if (debug) {
          console.group('A/B - Connector [componentDidMount]');
          console.log('variant:', variant);
          console.log('this.state.pendingDefined:', this.state.pendingDefined);
          console.log('this.state.renderedComponent:', this.state.renderedComponent);
          console.groupEnd();
        }
      }
    }, {
      key: 'componentDidUpdate',
      value: function componentDidUpdate(_, prevState) {
        var renderedComponent = this.state.renderedComponent;
        var onActivateVariant = this.props.onActivateVariant;

        var variant = this.getExperimentVariant(experimentName);
        var shouldChange = (isLocal || !renderedComponent) && variant && variantComponents[variant] !== prevState.renderedComponent;
        // We should allow multiple changes if it's local development
        if (shouldChange) {
          // We need add this to the active variants
          onActivateVariant(variant);
          this.setRenderedVariant(variantComponents[variant] || Component);
        }
        // Debug info
        if (debug) {
          console.group('A/B - Connector [componentDidUpdate]');
          console.log('experiments:', this.props.experiments);
          console.log('variant:', variant);
          console.log('isLocal:', isLocal);
          console.log('shouldChange:', shouldChange);
          console.log('this.state.renderedComponent:', this.state.renderedComponent);
          console.groupEnd();
        }
      }
    }, {
      key: 'componentWillUnmount',
      value: function componentWillUnmount() {
        var onDeactivateVariant = this.props.onDeactivateVariant;

        var variant = this.getExperimentVariant(experimentName);

        // Unregister so setState is not called
        this.resetTimer();

        // Deactivate experiment in store
        if (variant) {
          onDeactivateVariant();
        }
      }

      /**
       * Safely accesses the experiments to to get the activated variant.
       *
       * @param {string} name - Name of the experiment
       */

    }, {
      key: 'getExperimentVariant',
      value: function getExperimentVariant(name) {
        var experiments = this.props.experiments;

        return experiments[name] && experiments[name].variant;
      }
    }, {
      key: 'setRenderedVariant',
      value: function setRenderedVariant(renderedComponent) {
        // Reset timer, since we know which component to render
        // and no longer need the actual timeout
        this.resetTimer();
        this.setState({
          renderedComponent: renderedComponent
        });
        // Debug info
        if (debug) {
          console.group('A/B - Connector [setRenderedVariant]');
          console.log('renderedComponent:', renderedComponent);
          console.groupEnd();
        }
      }
    }, {
      key: 'initializeTimer',
      value: function initializeTimer() {
        var _this2 = this;

        if (experimentId) {
          var counter = 0;
          this.timer = setInterval(function () {
            // Either Optimize is defined but nothing loaded for this test,
            // or we received variation 0 (original) as experiment
            if (counter === AB_TEST_INTERVAL_COUNT || shouldRenderOriginal(experimentId)) {
              _this2.setRenderedVariant(Component);
            }
            counter += 1;
          }, AB_TEST_INTERVAL);
        } else {
          this.timer = setTimeout(function () {
            // Since we receive no variant from Optimize, lets
            // render the default Wrapped component
            _this2.setRenderedVariant(Component);
          }, AB_TEST_TIMEOUT);
        }
      }
    }, {
      key: 'resetTimer',
      value: function resetTimer() {
        if (experimentId) {
          clearInterval(this.timer);
        } else {
          clearTimeout(this.timer);
        }
        this.timer = null;
        // Debug info
        if (debug) {
          console.log('A/B - Connector [resetTimer]');
        }
      }
    }, {
      key: 'render',
      value: function render() {
        var RenderedComponent = this.state.renderedComponent;
        // If we still do not know which component should be rendered yet,
        // we render an empty component, after max AB_TEST_TIMEOUT we render
        // something, which by default shiuld be the original component
        if (RenderedComponent) {
          // Destructure ABComponent specific props, which should not be passed
          var _props2 = this.props,
              experiments = _props2.experiments,
              optimizePending = _props2.optimizePending,
              optimizeLoaded = _props2.optimizeLoaded,
              onActivateOptimize = _props2.onActivateOptimize,
              onActivateVariant = _props2.onActivateVariant,
              rest = _objectWithoutProperties(_props2, ['experiments', 'optimizePending', 'optimizeLoaded', 'onActivateOptimize', 'onActivateVariant']);

          var abTestData = experiments[experimentName];
          return _react2.default.createElement(RenderedComponent, _extends({}, rest, { abTestData: abTestData }));
        }
        return null;
      }
    }]);

    return ABComponent;
  }(_react2.default.Component);

  ABComponent.propTypes = {
    experiments: _propTypes2.default.object.isRequired,
    onActivateOptimize: _propTypes2.default.func.isRequired,
    onActivateVariant: _propTypes2.default.func.isRequired,
    onDeactivateVariant: _propTypes2.default.func.isRequired,
    optimizePending: _propTypes2.default.bool,
    optimizeLoaded: _propTypes2.default.bool
  };
  ABComponent.defaultProps = {
    optimizePending: undefined,
    optimizeLoaded: undefined
  };


  var mapDispatchToProps = function mapDispatchToProps(dispatch) {
    return {
      onActivateOptimize: function onActivateOptimize() {
        return dispatch((0, _abActions.optimizeActivate)());
      },
      onActivateVariant: (0, _abActions.mountVariant)(dispatch, experimentName),
      onDeactivateVariant: function onDeactivateVariant() {
        return (0, _abActions.unmountVariant)(dispatch, experimentName);
      }
    };
  };

  return (0, _reactRedux.connect)(function (state) {
    return {
      experiments: state.ab.experiments,
      optimizePending: state.ab.optimize.pending,
      optimizeLoaded: state.ab.optimize.loaded
    };
  }, mapDispatchToProps)(ABComponent);
}