react-experiment-hoc
Version:
Simple hoc to provide a/b-test features.
294 lines (243 loc) • 12.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _hoistNonReactStatics = _interopRequireDefault(require("hoist-non-react-statics"));
var _jsCookie = _interopRequireDefault(require("js-cookie"));
var _Context = _interopRequireDefault(require("./Context"));
var _weighted = _interopRequireDefault(require("./weighted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
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; }
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 _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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
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); }
var DEFAULT_OPTIONS = {
/**
* Wheter the experiment should be persistant betwen renders & sesions.
*
* -1 evaluate on every render
* 0 evaluate on every session
* 1 evaluate once
*
* @default 1
*/
persistent: 1,
/**
* Auto play experiment on render
*
* @default false
*/
autoPlay: false,
/**
* Name of the fallback variation if fetch fails
*
* @default original
*/
fallbackName: 'original',
/**
* Prefix for the prop names passed to BaseComponent
*
* @default null
*/
propPrefix: null,
/**
* Fetch method returns variations of the given experiment
*
* @param experiment
*
* @returns Promise(array)
* @default Promise.resolve([])
*/
onFetch: function onFetch() {
return Promise.resolve([]);
},
/**
* Trigger play
*
* @param experiment
* @param variation
* @param data
*
* @returns Promise()
* @default Promise.resolve()
*/
onPlay: function onPlay() {
return Promise.resolve([]);
},
/**
* Trigger win
*
* @param experiment
* @param variation
* @param data
*
* @returns Promise()
* @default Promise.resolve()
*/
onWin: function onWin() {
return Promise.resolve();
},
/**
* Set cookie method
*
* @param name
* @param value
* @param options
*
* @default js-cookie.set
*/
setCookie: _jsCookie["default"].set,
/**
* Get cookie method
*
* @param name
* @param options
*
* @default js-cookie.get
*/
getCookie: _jsCookie["default"].get
};
var _default = function _default(experiment) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return function (BaseComponent) {
var ExperimentComponent =
/*#__PURE__*/
function (_Component) {
_inherits(ExperimentComponent, _Component);
function ExperimentComponent(props) {
var _this;
_classCallCheck(this, ExperimentComponent);
_this = _possibleConstructorReturn(this, _getPrototypeOf(ExperimentComponent).call(this, props));
_this.state = {
started: false,
fallback: false,
variants: [],
variant: null
};
_this._options = Object.assign({}, DEFAULT_OPTIONS, options);
return _this;
}
_createClass(ExperimentComponent, [{
key: "componentWillMount",
value: function componentWillMount() {
// Apply context options
var context = this.context || {};
this._options = Object.assign({}, this._options, context);
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
var variants = this.state.variants;
var _this$_options = this._options,
autoPlay = _this$_options.autoPlay,
fallbackName = _this$_options.fallbackName;
if (variants.length === 0) {
this.fetch(experiment).then(function (data) {
var variant = _this2.getVariant(data);
_this2.setState({
fallback: false,
variant: variant,
variants: data
});
if (autoPlay && variant) _this2.play(variant);
})["catch"](function () {
var fallbackVariant = {
name: fallbackName,
weight: 100
};
_this2.setState({
fallback: true,
variant: fallbackName,
variants: [fallbackVariant]
});
});
}
}
}, {
key: "getVariant",
value: function getVariant(variants) {
var fallback = this.state.fallback;
if (variants.length === 0) return null;
var _this$_options2 = this._options,
persistent = _this$_options2.persistent,
setCookie = _this$_options2.setCookie,
getCookie = _this$_options2.getCookie;
var key = "experiment_".concat(experiment).concat(persistent);
var cookieIndex = getCookie(key);
var index = cookieIndex;
if (!index || !variants[index] || persistent < 0) index = (0, _weighted["default"])(variants.map(function (v) {
return v.weight;
}));
if (!cookieIndex && !fallback && persistent >= 0) setCookie(key, index, {
path: '/',
expires: !persistent ? null : new Date(Date.now() + 60 * 60 * 24 * 365 * 10 * 1000)
});
return variants[index].name;
}
}, {
key: "win",
value: function win(variant, data) {
if (!this.state.started) return console.warn("[react-experiment-hoc] Experiment \"".concat(experiment, "\" triggerd win without beeing started. Make sure you trigger play before win."));
if (this.state.fallback) return console.warn("[react-experiment-hoc] Experiment \"".concat(experiment, "\" is using fallback. Win will not be registerd."));
this._options.onWin(experiment, variant, data);
console.info("[react-experiment-hoc] Experiment \"".concat(experiment, "\" with variant \"").concat(variant, "\" win."));
}
}, {
key: "play",
value: function play(variant, data) {
if (this.state.started) return console.warn("[react-experiment-hoc] Experiment \"".concat(experiment, "\" has already started."));
if (this.state.fallback) return console.warn("[react-experiment-hoc] Experiment \"".concat(experiment, "\" is using a fallback variant. Play will not be registerd."));
this.setState({
started: true
});
this._options.onPlay(experiment, variant, data);
console.info("[react-experiment-hoc] Experiment \"".concat(experiment, "\" with variant \"").concat(variant, "\" started."));
}
}, {
key: "fetch",
value: function fetch(e) {
return this._options.onFetch(e);
}
}, {
key: "render",
value: function render() {
var _this3 = this,
_objectSpread2;
var variant = this.state.variant;
if (!this.state.started && !variant) console.info("[react-experiment-hoc] Render component while waiting for variants of experiment \"".concat(experiment, "\"."));
if (!this.state.started && variant) console.info("[react-experiment-hoc] Render experiment \"".concat(experiment, "\" with variant \"").concat(variant, "\"."));
if (!variant) return null;
var prefix = function prefix(name) {
if (!_this3._options.propPrefix) return name;
return _this3._options.propPrefix + (name.charAt(0).toUpperCase() + name.slice(1));
};
var props = _objectSpread({}, this.props, (_objectSpread2 = {}, _defineProperty(_objectSpread2, prefix('experimentName'), experiment), _defineProperty(_objectSpread2, prefix('experimentVariant'), variant), _defineProperty(_objectSpread2, prefix('experimentPlay'), function () {
var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return _this3.play(variant, data);
}), _defineProperty(_objectSpread2, prefix('experimentWin'), function () {
var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return _this3.win(variant, data);
}), _objectSpread2));
return _react["default"].createElement(BaseComponent, props);
}
}]);
return ExperimentComponent;
}(_react.Component);
ExperimentComponent.contextType = _Context["default"];
return (0, _hoistNonReactStatics["default"])(ExperimentComponent, BaseComponent);
};
};
exports["default"] = _default;