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";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = withAbTest;

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

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

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

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

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 === void 0 ? false : _ref$debug,
      _ref$isLocal = _ref.isLocal,
      isLocal = _ref$isLocal === void 0 ? false : _ref$isLocal,
      _ref$experimentId = _ref.experimentId,
      experimentId = _ref$experimentId === void 0 ? '' : _ref$experimentId,
      _ref$waitForUser = _ref.waitForUser,
      waitForUser = _ref$waitForUser === void 0 ? false : _ref$waitForUser;

  // 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 = /*#__PURE__*/function (_React$Component) {
    _inherits(ABComponent, _React$Component);

    var _super = _createSuper(ABComponent);

    function ABComponent(props) {
      var _this;

      _classCallCheck(this, ABComponent);

      _this = _super.call(this, props);

      var variant = _this.getExperimentVariant(experimentName);

      var renderOriginalComponent = (isLocal || shouldRenderOriginal(experimentId)) && Component;
      var renderVariationComponent = variant && variantComponents[variant];
      _this.state = {
        // 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(_assertThisInitialized(_this));
      _this.setRenderedVariant = _this.setRenderedVariant.bind(_assertThisInitialized(_this));
      _this.resetTimer = _this.resetTimer.bind(_assertThisInitialized(_this));
      _this.initializeTimer = _this.initializeTimer.bind(_assertThisInitialized(_this)); // Debug info

      if (debug) {
        console.group('A/B - Connector [Constructor]');
        console.log('variant:', variant);
        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 _this$props = this.props,
            onActivateOptimize = _this$props.onActivateOptimize,
            onActivateVariant = _this$props.onActivateVariant;
        var renderedComponent = this.state.renderedComponent;
        var variant = this.getExperimentVariant(experimentName);
        onActivateOptimize();

        if (!variant && !renderedComponent) {
          this.initializeTimer();
        } else if (!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.renderedComponent:', renderedComponent);
          console.groupEnd();
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(_, prevState) {
        var _this$state = this.state,
            renderedComponent = _this$state.renderedComponent,
            experiments = _this$state.experiments;
        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:', experiments);
          console.log('variant:', variant);
          console.log('isLocal:', isLocal);
          console.log('shouldChange:', shouldChange);
          console.log('this.state.renderedComponent:', 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 _this$props2 = this.props,
              experiments = _this$props2.experiments,
              rest = _objectWithoutProperties(_this$props2, ["experiments"]);

          var abTestData = experiments[experimentName];
          return /*#__PURE__*/_react["default"].createElement(RenderedComponent, _extends({}, rest, {
            abTestData: abTestData
          }));
        }

        return null;
      }
    }]);

    return ABComponent;
  }(_react["default"].Component);

  _defineProperty(ABComponent, "propTypes", {
    experiments: _propTypes["default"].object.isRequired,
    onActivateOptimize: _propTypes["default"].func.isRequired,
    onActivateVariant: _propTypes["default"].func.isRequired,
    onDeactivateVariant: _propTypes["default"].func.isRequired
  });

  var mapDispatchToProps = function mapDispatchToProps(dispatch) {
    return {
      onActivateOptimize: function onActivateOptimize() {
        return dispatch((0, _abActions.optimizeActivate)(waitForUser));
      },
      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
    };
  }, mapDispatchToProps)(ABComponent);
}