@mopinion/deploy
Version:
Deploy your Mopinion feedback forms with ease
631 lines (525 loc) • 23.8 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = createRule;
var _services = require("../services");
var _utils = require("../utils");
var _listeners = require("../listeners");
var _createRuleStore2 = _interopRequireDefault(require("./createRuleStore"));
var conditionTests = _interopRequireWildcard(require("./ruleConditionTests"));
var _utils2 = require("./utils");
var _constants = require("./constants");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function createRule() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$rule = _ref.rule,
rule = _ref$rule === void 0 ? {} : _ref$rule,
globalListenerStore = _ref.globalListenerStore;
var id = rule.id,
ifRules = rule["if"],
then = rule.then;
var ruleChangeListeners = [];
var _createRuleStore = (0, _createRuleStore2["default"])(rule),
setState = _createRuleStore.setState,
setConditionState = _createRuleStore.setConditionState,
getState = _createRuleStore.getState,
getConditionState = _createRuleStore.getConditionState,
setValidState = _createRuleStore.setValidState,
getValidState = _createRuleStore.getValidState,
getValidConditions = _createRuleStore.getValidConditions,
setTimeOnPageState = _createRuleStore.setTimeOnPageState,
getTimeOnPageState = _createRuleStore.getTimeOnPageState;
var _createListenerStore = (0, _listeners.createListenerStore)(),
clearListeners = _createListenerStore.clearListeners,
setListener = _createListenerStore.setListener,
setIntervalListener = _createListenerStore.setIntervalListener;
var preCheckEffects = {
percentage: function percentage(_ref2) {
var index = _ref2.index;
if (getConditionState(index, function (state) {
return state.percentage;
}) === undefined) {
setConditionState(index, function (state) {
return state.percentage = (0, _utils2.randomPercentage)();
});
}
},
time_in_session: function time_in_session(_ref3) {
var index = _ref3.index,
condition = _ref3.condition;
var isValid = function isValid() {
return getConditionState(index, function (state) {
return state.sessionTime;
}) >= Number(condition.time_in_session);
};
if (isValid()) {
return;
}
setIntervalListener(function () {
setConditionState(index, function (conditionState) {
conditionState.sessionTime = typeof conditionState.sessionTime !== 'undefined' ? conditionState.sessionTime + 1 : 1;
});
if (isValid()) {
checkConditions();
}
}, 1000);
},
number_of_pages: function number_of_pages() {
setState(function (state) {
if (state.lastPage !== document.location.href) {
state.pageCount = typeof state.pageCount !== 'undefined' ? state.pageCount + 1 : 1;
}
state.lastPage = document.location.href;
});
},
type: function type() {
if (getState(function (state) {
return state.returning;
})) {
return;
}
if ((0, _utils.timeInSeconds)() - globalListenerStore.getSession() < 120) {
setState(function (state) {
state.returning = true;
});
}
},
event_listeners: function event_listeners(_ref4) {
var index = _ref4.index,
value = _ref4.value;
try {
(0, _utils.flattenArray)(value).forEach(function (eventListener, eventListenerIndex) {
var _getConditionState;
var selector = eventListener.selector,
event = eventListener.event;
if (((_getConditionState = getConditionState(index, function (state) {
var _state$domEvents;
return (_state$domEvents = state.domEvents) === null || _state$domEvents === void 0 ? void 0 : _state$domEvents[selector];
})) === null || _getConditionState === void 0 ? void 0 : _getConditionState.indexOf(event)) > -1) {
return;
}
setListener(function (listeners) {
var listenerKey = event + selector + index + eventListenerIndex;
listeners[listenerKey] = function (e) {
setTimeout(function () {
try {
var _e$target;
if ((_e$target = e.target) !== null && _e$target !== void 0 && _e$target.matches(selector)) {
setConditionState(index, function (state) {
if (!state.domEvents) {
state.domEvents = {};
}
if (!state.domEvents[selector]) {
state.domEvents[selector] = [];
}
state.domEvents[selector].push(event);
});
checkConditions();
}
} catch (e) {}
});
};
document.addEventListener(event, listeners[listenerKey]);
return function () {
return document.removeEventListener(event, listeners[listenerKey]);
};
});
});
} catch (e) {}
},
form_events: function form_events(_ref5) {
var index = _ref5.index,
value = _ref5.value,
serviceName = _ref5.service;
try {
if (!(0, _services.getService)(serviceName)) {
(0, _services.setService)(serviceName, (0, _services.createService)(serviceName));
}
var service = (0, _services.getService)(serviceName);
(0, _utils.flattenArray)(value).forEach(function (formListener, formListenerIndex) {
var _getConditionState2;
var formKey = formListener.formKey,
event = formListener.event;
if (((_getConditionState2 = getConditionState(index, function (state) {
var _state$formEvents;
return (_state$formEvents = state.formEvents) === null || _state$formEvents === void 0 ? void 0 : _state$formEvents[formKey];
})) === null || _getConditionState2 === void 0 ? void 0 : _getConditionState2.indexOf(event)) > -1) {
return;
}
var applyListener = function applyListener() {
setListener(function (listeners) {
var listenerKey = formKey + event + index + formListenerIndex;
listeners[listenerKey] = function (e) {
setTimeout(function () {
if (e.key === formKey) {
setConditionState(index, function (state) {
if (!state.formEvents[formKey]) {
state.formEvents[formKey] = [];
}
state.formEvents[formKey].push(e.event);
});
checkConditions();
}
});
};
service.addEventListener(event, listeners[listenerKey]);
return function () {
return service.removeEventListener(event, listeners[listenerKey]);
};
});
};
if (service.isLoaded()) {
applyListener();
} else {
service.onLoaded(applyListener);
}
});
} catch (e) {}
}
};
function jsCookieCssSelectorEffect(_ref6) {
var key = _ref6.key,
value = _ref6.value,
wasValid = _ref6.wasValid;
setIntervalListener(function () {
var conditionTestFn = conditionTests[key];
var isValid = conditionTestFn(value, rule);
if (wasValid && !isValid) {
checkConditions();
}
if (!wasValid && isValid) {
checkConditions();
}
});
}
var postCheckEffects = {
js: jsCookieCssSelectorEffect,
cookie: jsCookieCssSelectorEffect,
css_selector: jsCookieCssSelectorEffect,
scrollpos: function scrollpos(_ref7) {
var key = _ref7.key,
value = _ref7.value,
wasValid = _ref7.wasValid;
setListener(function (listeners) {
listeners.scroll = (0, _utils.debounce)(function () {
var conditionTestFn = conditionTests[key];
var isValid = conditionTestFn(value);
if (wasValid && !isValid) {
checkConditions();
}
if (!wasValid && isValid) {
checkConditions();
}
}, 50);
window.addEventListener('scroll', listeners.scroll);
return function () {
return window.removeEventListener('scroll', listeners.scroll);
};
});
},
time: function time(_ref8) {
var index = _ref8.index,
value = _ref8.value;
var isValid = function isValid() {
return (0, _utils.timeInSeconds)() - getTimeOnPageState(index, 'time') >= Number(value);
};
if (!getTimeOnPageState(index, 'time')) {
setTimeOnPageState(index, 'time');
}
if (isValid()) {
return;
}
setIntervalListener(function () {
if (isValid()) {
checkConditions();
}
}, 1000);
},
time_after_valid: function time_after_valid(_ref9) {
var index = _ref9.index,
value = _ref9.value;
var isValid = function isValid() {
return (0, _utils.timeInSeconds)() - getTimeOnPageState(index, 'time_after_valid') >= Number(value);
};
if (!getTimeOnPageState(index, 'time_after_valid')) {
setTimeOnPageState(index, 'time_after_valid');
}
if (isValid()) {
return;
}
setIntervalListener(function () {
if (isValid()) {
checkConditions();
}
}, 1000);
}
};
function validConditionsChanged() {
var previous = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var previouslyValidConditions = previous.filter(function (_ref10) {
var index = _ref10.index;
return index;
});
return getValidConditions().every(function () {
var _ref11 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
index = _ref11.index;
return previouslyValidConditions.indexOf(index) === -1;
});
}
var conditionCheckOrder = ['pause', 'location', 'time', 'percentage', 'number_of_pages', 'referrer', 'date', 'clock', 'type', 'devices', 'css_selector', 'js', 'cookie', 'scrollpos', 'time_in_session', 'event_listeners', 'form_events', 'time_after_valid'];
function checkConditions() {
(0, _utils.schedule)(function () {
clearListeners();
var previouslyValidConditions = getValidConditions();
var ruleConditionsValid = ifRules.filter(function (condition, index) {
if (_constants.showOncePerSessionTriggers.indexOf(condition.trigger) > -1 && getConditionState(index, function (state) {
return state.triggered;
})) {
return false;
}
Object.keys(preCheckEffects).forEach(function (conditionKey) {
var conditionValue = condition[conditionKey];
var preCheckEffect = preCheckEffects[conditionKey];
if (!(0, _utils2.conditionValueIsEmpty)(conditionValue) && preCheckEffect) {
var _then$;
preCheckEffect({
index: index,
condition: condition,
value: conditionValue,
service: then === null || then === void 0 ? void 0 : (_then$ = then[0]) === null || _then$ === void 0 ? void 0 : _then$.service
});
}
});
var isValid = conditionCheckOrder.every(function (conditionKey) {
var conditionTestFn = conditionTests[conditionKey];
var conditionValue = condition[conditionKey];
var postCheckEffect = postCheckEffects[conditionKey];
if ((0, _utils2.conditionValueIsEmpty)(conditionValue)) {
return true;
}
if (typeof conditionTestFn !== 'function') {
return true;
}
var valid = conditionTestFn(conditionValue, {
rule: rule,
state: {
pageCount: getState(function (state) {
return state.pageCount;
}),
returning: getState(function (state) {
return state.returning;
}),
percentage: getConditionState(index, function (state) {
return state.percentage;
}),
timeOnPage: getTimeOnPageState(index, 'time'),
timeAfterValid: getTimeOnPageState(index, 'time_after_valid'),
sessionTime: getConditionState(index, function (state) {
return state.sessionTime;
}),
eventListeners: getConditionState(index, function (state) {
return state.domEvents;
}),
formEvents: getConditionState(index, function (state) {
return state.formEvents;
}),
referrer: globalListenerStore.getPreviousLocation()
}
});
if (postCheckEffect) {
var _then$2;
postCheckEffect({
key: conditionKey,
value: conditionValue,
wasValid: valid,
index: index,
service: then === null || then === void 0 ? void 0 : (_then$2 = then[0]) === null || _then$2 === void 0 ? void 0 : _then$2.service
});
}
return valid;
});
setValidState(index, isValid);
return isValid;
}).length > 0;
var divPlacementValid = (0, _utils2.handleDivPlacement)(then, ruleConditionsValid);
setIntervalListener(function () {
if (divPlacementValid !== (0, _utils2.checkDivs)(then)) {
if (ruleConditionsValid) {
getValidConditions().forEach(function (_ref12) {
var index = _ref12.index;
setValidState(index, false);
});
}
checkConditions();
}
});
var ruleIsCurrentlyValid = ruleConditionsValid && divPlacementValid;
var conditionsChanged = validConditionsChanged(previouslyValidConditions);
if (conditionsChanged && ruleIsCurrentlyValid) {
return runThen();
} else if (previouslyValidConditions.length > 0 && !ruleIsCurrentlyValid) {
return cleanupThen();
}
if (ruleIsCurrentlyValid) {}
if (!ruleIsCurrentlyValid) {}
ruleChangeListeners.forEach(function (fn) {
return fn({
ruleIsCurrentlyValid: ruleIsCurrentlyValid,
conditionsChanged: conditionsChanged
});
});
});
}
function runThen() {
then.forEach(function () {
var thenCondition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _thenCondition$servic = thenCondition.service,
serviceName = _thenCondition$servic === void 0 ? 'mopinion' : _thenCondition$servic,
useQuerySelectorAll = thenCondition.useQuerySelectorAll,
_thenCondition$args = thenCondition.args,
args = _thenCondition$args === void 0 ? [] : _thenCondition$args;
var _args = _slicedToArray(args, 3),
key = _args[0],
domain = _args[1],
divName = _args[2];
if (!(0, _services.getService)(serviceName)) {
(0, _services.setService)(serviceName, (0, _services.createService)(serviceName));
}
var service = (0, _services.getService)(serviceName);
var conditions = getValidConditions();
var open = function open(_ref13) {
var index = _ref13.index,
condition = _ref13.condition;
(0, _utils2.tryService)(function () {
if (!getValidState(index)) {
return;
}
if (_constants.showAlwaysPerSessionTriggers.indexOf(condition.trigger) > -1 || !getConditionState(index, function (state) {
return state.triggered;
})) {
service.handleTrigger(_objectSpread({
key: key,
domain: domain,
divName: divName,
useQuerySelectorAll: useQuerySelectorAll
}, condition));
setConditionState(index, function (state) {
return state.triggered = true;
});
}
});
};
service.start(function () {
handleTriggers({
conditions: conditions,
id: id,
open: open
});
});
});
}
function cleanupThen() {
var cleanAll = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
then.forEach(function () {
var _ref14 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
serviceName = _ref14.service,
_ref14$args = _ref14.args,
args = _ref14$args === void 0 ? [] : _ref14$args;
try {
var service = (0, _services.getService)(serviceName);
service.removeWhenClosed(args[0]);
} catch (e) {}
clearListeners(cleanAll);
});
}
function handleTriggers(_ref15) {
var _ref15$conditions = _ref15.conditions,
conditions = _ref15$conditions === void 0 ? [] : _ref15$conditions,
id = _ref15.id,
open = _ref15.open;
conditions.forEach(function (_ref16) {
var index = _ref16.index,
condition = _ref16.condition;
if (_constants.showOncePerSessionTriggers.indexOf(condition.trigger) > -1 && getConditionState(index, function (state) {
return state.triggered;
})) {
return;
}
setTimeout(function () {
var initTrigger = function initTrigger() {
open({
index: index,
condition: condition
});
clearListeners(false);
};
if (condition.trigger === 'exit') {
return handleExit({
condition: condition,
initTrigger: initTrigger
});
}
initTrigger();
});
});
}
function handleExit(_ref17) {
var condition = _ref17.condition,
initTrigger = _ref17.initTrigger;
var minY = 100;
var mouseY = 0;
setListener(function (listeners) {
listeners.mousemove = function (e) {
return mouseY = e.clientY;
};
listeners.mouseleave = function (e) {
if (mouseY <= minY) {
var YonLeave = mouseY;
setTimeout(function () {
if (mouseY === YonLeave) {
initTrigger();
clearListeners(false);
}
}, 200);
}
};
document.addEventListener('mousemove', listeners.mousemove);
document.querySelector('html').addEventListener('mouseleave', listeners.mouseleave);
return function () {
document.removeEventListener('mousemove', listeners.mousemove);
document.querySelector('html').removeEventListener('mouseleave', listeners.mouseleave);
};
});
}
function onRuleChange(fn) {
if (typeof fn !== 'function') {
return;
}
ruleChangeListeners.push(fn);
}
return {
checkConditions: checkConditions,
cleanupThen: cleanupThen,
getState: getState,
getConditionState: getConditionState,
getValidState: getValidState,
getValidConditions: getValidConditions,
getTimeOnPageState: getTimeOnPageState,
onRuleChange: onRuleChange,
globalListenerStore: globalListenerStore
};
}
//# sourceMappingURL=createRule.js.map