Commit 6f772644 by Chris

update dist to latest version

parent 1c89f3aa
...@@ -100,7 +100,7 @@ return /******/ (function(modules) { // webpackBootstrap ...@@ -100,7 +100,7 @@ return /******/ (function(modules) { // webpackBootstrap
"use strict"; "use strict";
/*! /**!
* Foresight * Foresight
* *
* @author James Ooi <james.ooi@forefront.com.my> * @author James Ooi <james.ooi@forefront.com.my>
...@@ -128,11 +128,11 @@ var Foresight = /** @class */ (function () { ...@@ -128,11 +128,11 @@ var Foresight = /** @class */ (function () {
* @constructor * @constructor
*/ */
function Foresight(config) { function Foresight(config) {
if (config === void 0) { config = {}; }
var _this = this; var _this = this;
if (config === void 0) { config = {}; }
/** /**
* Stores a mapping of elements with is respective functions to de-register * Stores a mapping of elements with its respective functions to de-register
* listeners. * the listeners.
* @private * @private
*/ */
this._untrackFns = new Map(); this._untrackFns = new Map();
...@@ -141,7 +141,17 @@ var Foresight = /** @class */ (function () { ...@@ -141,7 +141,17 @@ var Foresight = /** @class */ (function () {
* @private * @private
*/ */
this._observer = null; this._observer = null;
this.options = __assign({}, Foresight.defaultOptions, config); /**
* Store the current maximum page scroll amount.
* @private
*/
this._maxScrollY = 0;
/**
* Indicates that the scroll tracker has already been initialised
* @private
*/
this._scrollTrackerInitialised = false;
this.options = __assign(__assign({}, Foresight.defaultOptions), config);
// Initialise IntersectionObserver // Initialise IntersectionObserver
this._observer = new IntersectionObserver(function (entries, observer) { this._observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) { entries.forEach(function (entry) {
...@@ -172,6 +182,13 @@ var Foresight = /** @class */ (function () { ...@@ -172,6 +182,13 @@ var Foresight = /** @class */ (function () {
Utils Utils
.toArray(root.querySelectorAll('[data-track], [data-track-view]')) .toArray(root.querySelectorAll('[data-track], [data-track-view]'))
.map(function (element) { return _this.track(element); }); .map(function (element) { return _this.track(element); });
if (!this._scrollTrackerInitialised) {
var maxScrollListener = Utils.debounce(function () { return _this._onScroll(); });
window.addEventListener('scroll', maxScrollListener, { passive: true });
this._onScroll(); // call once
this._scrollTrackerInitialised = true;
}
window.addEventListener('beforeunload', function (e) { return _this._onUnload(e); });
}; };
/** /**
* Start tracking an element for events. * Start tracking an element for events.
...@@ -219,7 +236,7 @@ var Foresight = /** @class */ (function () { ...@@ -219,7 +236,7 @@ var Foresight = /** @class */ (function () {
return this.options.sendEventFn(data); return this.options.sendEventFn(data);
} }
if (typeof window['gtag'] === 'function') { if (typeof window['gtag'] === 'function') {
return window['gtag']('event', data.action, __assign({ 'event_label': data.label, 'event_category': data.category, 'non_interaction': !data.interaction }, data.metrics, data.dimensions)); return window['gtag']('event', data.action, __assign(__assign({ 'event_label': data.label, 'event_category': data.category, 'non_interaction': !data.interaction }, data.metrics), data.dimensions));
} }
if (typeof window['ga'] === 'function') { if (typeof window['ga'] === 'function') {
return window['ga']('send', { return window['ga']('send', {
...@@ -228,7 +245,7 @@ var Foresight = /** @class */ (function () { ...@@ -228,7 +245,7 @@ var Foresight = /** @class */ (function () {
eventAction: data.action, eventAction: data.action,
eventLabel: data.label, eventLabel: data.label,
nonInteraction: !data.interaction, nonInteraction: !data.interaction,
}, __assign({}, data.metrics, data.dimensions)); }, __assign(__assign({}, data.metrics), data.dimensions));
} }
throw 'No available analytics backend found. Has Google Analytics been loaded yet?'; throw 'No available analytics backend found. Has Google Analytics been loaded yet?';
}; };
...@@ -255,7 +272,7 @@ var Foresight = /** @class */ (function () { ...@@ -255,7 +272,7 @@ var Foresight = /** @class */ (function () {
*/ */
Foresight.prototype._trackClicks = function (element) { Foresight.prototype._trackClicks = function (element) {
var _this = this; var _this = this;
// Define listen fucntion // Define listen function
var listener = function (e) { return _this._onTrackedClick(element, e); }; var listener = function (e) { return _this._onTrackedClick(element, e); };
element.addEventListener('click', listener); element.addEventListener('click', listener);
element.addEventListener('auxclick', listener); element.addEventListener('auxclick', listener);
...@@ -355,9 +372,26 @@ var Foresight = /** @class */ (function () { ...@@ -355,9 +372,26 @@ var Foresight = /** @class */ (function () {
this.send(data); this.send(data);
}; };
/** /**
* Default Options * Handles a scroll event
* @static
*/ */
Foresight.prototype._onScroll = function (root) {
if (root === void 0) { root = document.documentElement; }
var vh = Math.max(root.clientHeight, window.innerHeight || 0);
var scrollY = root.scrollTop + vh;
if (scrollY > this._maxScrollY) {
this._maxScrollY = scrollY;
}
};
Foresight.prototype._onUnload = function (e) {
var scrollData = {
category: 'general',
action: 'scroll y',
label: window.location.pathname,
interaction: false,
value: Math.floor((this._maxScrollY / document.body.clientHeight) * 100)
};
this.send(scrollData);
};
Foresight.defaultOptions = { Foresight.defaultOptions = {
defer: false, defer: false,
observerOptions: {}, observerOptions: {},
...@@ -409,7 +443,7 @@ if ('IntersectionObserver' in window && ...@@ -409,7 +443,7 @@ if ('IntersectionObserver' in window &&
/** /**
* An IntersectionObserver registry. This registry exists to hold a strong * An IntersectionObserver registry. This registry exists to hold a strong
* reference to IntersectionObserver instances currently observering a target * reference to IntersectionObserver instances currently observing a target
* element. Without this registry, instances without another reference may be * element. Without this registry, instances without another reference may be
* garbage collected. * garbage collected.
*/ */
...@@ -438,7 +472,9 @@ function IntersectionObserverEntry(entry) { ...@@ -438,7 +472,9 @@ function IntersectionObserverEntry(entry) {
// Sets intersection ratio. // Sets intersection ratio.
if (targetArea) { if (targetArea) {
this.intersectionRatio = intersectionArea / targetArea; // Round the intersection ratio to avoid floating point math issues:
// https://github.com/w3c/IntersectionObserver/issues/324
this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4));
} else { } else {
// If area is zero and is intersecting, sets to 1, otherwise to 0 // If area is zero and is intersecting, sets to 1, otherwise to 0
this.intersectionRatio = this.isIntersecting ? 1 : 0; this.intersectionRatio = this.isIntersecting ? 1 : 0;
...@@ -626,7 +662,7 @@ IntersectionObserver.prototype._parseRootMargin = function(opt_rootMargin) { ...@@ -626,7 +662,7 @@ IntersectionObserver.prototype._parseRootMargin = function(opt_rootMargin) {
/** /**
* Starts polling for intersection changes if the polling is not already * Starts polling for intersection changes if the polling is not already
* happening, and if the page's visibilty state is visible. * happening, and if the page's visibility state is visible.
* @private * @private
*/ */
IntersectionObserver.prototype._monitorIntersections = function() { IntersectionObserver.prototype._monitorIntersections = function() {
...@@ -928,7 +964,7 @@ function now() { ...@@ -928,7 +964,7 @@ function now() {
/** /**
* Throttles a function and delays its executiong, so it's only called at most * Throttles a function and delays its execution, so it's only called at most
* once within a given time period. * once within a given time period.
* @param {Function} fn The function to throttle. * @param {Function} fn The function to throttle.
* @param {number} timeout The amount of time that must pass before the * @param {number} timeout The amount of time that must pass before the
...@@ -1059,7 +1095,7 @@ function getEmptyRect() { ...@@ -1059,7 +1095,7 @@ function getEmptyRect() {
} }
/** /**
* Checks to see if a parent element contains a child elemnt (including inside * Checks to see if a parent element contains a child element (including inside
* shadow DOM). * shadow DOM).
* @param {Node} parent The parent element. * @param {Node} parent The parent element.
* @param {Node} child The child element. * @param {Node} child The child element.
...@@ -1109,6 +1145,8 @@ window.IntersectionObserverEntry = IntersectionObserverEntry; ...@@ -1109,6 +1145,8 @@ window.IntersectionObserverEntry = IntersectionObserverEntry;
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var toArray_1 = __webpack_require__(3); var toArray_1 = __webpack_require__(3);
exports.toArray = toArray_1.default; exports.toArray = toArray_1.default;
var debounce_1 = __webpack_require__(4);
exports.debounce = debounce_1.default;
/***/ }), /***/ }),
...@@ -1127,6 +1165,34 @@ function toArray(arrayLike) { ...@@ -1127,6 +1165,34 @@ function toArray(arrayLike) {
exports.default = toArray; exports.default = toArray;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Returns a debounced function that as long as it continues to be invoked,
* will not be triggered until it stops being called for N milliseconds.
*/
function debounce(func, wait) {
if (wait === void 0) { wait = 300; }
var timeout;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
timeout = null;
func.apply(context, args);
}, wait);
};
}
exports.debounce = debounce;
exports.default = debounce;
/***/ }) /***/ })
/******/ ]); /******/ ]);
}); });
\ No newline at end of file
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Foresight=e():t.Foresight=e()}(window,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/",n(n.s=0)}([function(t,e,n){"use strict"; !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Foresight=e():t.Foresight=e()}(window,function(){return r={},i.m=n=[function(t,e,n){"use strict";
/*! /**!
* Foresight * Foresight
* *
* @author James Ooi <james.ooi@forefront.com.my> * @author James Ooi <james.ooi@forefront.com.my>
* @license MIT * @license MIT
* @copyright 2018 (c) FOREFRONT International Sdn Bhd * @copyright 2018 (c) FOREFRONT International Sdn Bhd
*/var r=this&&this.__assign||function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};n(1);var i=n(2),o=function(){function t(e){void 0===e&&(e={});var n=this;(this._untrackFns=new Map,this._observer=null,this.options=r({},t.defaultOptions,e),this._observer=new IntersectionObserver(function(t,e){t.forEach(function(t){t.isIntersecting&&(n._onTrackedView(t.target,e),e.unobserve(t.target))})},this.options.observerOptions),this.options.defer)||("complete"===document.readyState||"interactive"===document.readyState?this.start():window.addEventListener("DOMContentLoaded",function(){return n.start()}))}return t.prototype.start=function(t){var e=this;void 0===t&&(t=document.body),i.toArray(t.querySelectorAll("[data-track], [data-track-view]")).map(function(t){return e.track(t)})},t.prototype.track=function(t){this._untrackFns.has(t)||this._untrackFns.set(t,{click:null,view:null});var e=this._untrackFns.get(t);null!==t.getAttribute("data-track")&&null==e.click&&(e.click=this._trackClicks(t)),null!==t.getAttribute("data-track-view")&&null==e.view&&(e.view=this._trackViews(t)),this._untrackFns.set(t,e)},t.prototype.untrack=function(t){var e=this._untrackFns.get(t);void 0!==e&&(null!==e.click&&e.click(),null!==e.view&&e.view(),this._untrackFns.delete(t))},t.prototype.send=function(t){if(null!==this.options.sendEventFn)return this.options.sendEventFn(t);if("function"==typeof window.gtag)return window.gtag("event",t.action,r({event_label:t.label,event_category:t.category,non_interaction:!t.interaction},t.metrics,t.dimensions));if("function"==typeof window.ga)return window.ga("send",{hitType:"event",eventCategory:t.category,eventAction:t.action,eventLabel:t.label,nonInteraction:!t.interaction},r({},t.metrics,t.dimensions));throw"No available analytics backend found. Has Google Analytics been loaded yet?"},t.prototype._parseEventString=function(t){var e=t.split(";").map(function(t){return t.trim()}),n=e[0],r=e[1],i=e[2];return 1===e.length&&(r=n,n=void 0),{category:n,action:r,label:i,interaction:!0}},t.prototype._trackClicks=function(t){var e=this,n=function(n){return e._onTrackedClick(t,n)};return t.addEventListener("click",n),t.addEventListener("auxclick",n),function(){t.removeEventListener("click",n),t.removeEventListener("auxclick",n)}},t.prototype._trackViews=function(t){var e=this;return this._observer.observe(t),function(){e._observer.unobserve(t)}},t.prototype._onTrackedClick=function(t,e){var n=t.getAttribute("data-track"),r=this._parseEventString(n);r.metrics=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track:metrics")}).reduce(function(t,e){var n=e.name.replace(/data-track:metrics:/,""),r=""===e.value?1:e.value;return t[n]=r,t},{}),r.dimensions=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track:dimensions")}).reduce(function(t,e){if(""===e.value)return console.warn("No dimension value provided for "+e.name),t;var n=e.name.replace(/data-track:dimensions:/,""),r=e.value;return t[n]=r,t},{}),r.interaction=this.options.clicksAreInteractions,null!==t.getAttribute("data-track:non-interaction")&&(r.interaction=!1),this.send(r)},t.prototype._onTrackedView=function(t,e){var n=t.getAttribute("data-track-view"),r=this._parseEventString(n);r.metrics=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track-view:metrics")}).reduce(function(t,e){var n=e.name.replace(/data-track-view:metrics:/,""),r=""===e.value?1:e.value;return t[n]=r,t},{}),r.dimensions=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track-view:dimensions")}).reduce(function(t,e){if(""===e.value)return console.warn("No dimension value provided for "+e.name),t;var n=e.name.replace(/data-track-view:dimensions:/,""),r=e.value;return t[n]=r,t},{}),r.interaction=this.options.viewsAreInteractions,null!==t.getAttribute("data-track-view:interaction")&&(r.interaction=!0),this.send(r)},t.defaultOptions={defer:!1,observerOptions:{},clicksAreInteractions:!0,viewsAreInteractions:!1,sendEventFn:null},t}();t.exports=o},function(t,e){!function(t,e){"use strict";if("IntersectionObserver"in t&&"IntersectionObserverEntry"in t&&"intersectionRatio"in t.IntersectionObserverEntry.prototype)"isIntersecting"in t.IntersectionObserverEntry.prototype||Object.defineProperty(t.IntersectionObserverEntry.prototype,"isIntersecting",{get:function(){return this.intersectionRatio>0}});else{var n=[];i.prototype.THROTTLE_TIMEOUT=100,i.prototype.POLL_INTERVAL=null,i.prototype.USE_MUTATION_OBSERVER=!0,i.prototype.observe=function(t){if(!this._observationTargets.some(function(e){return e.element==t})){if(!t||1!=t.nodeType)throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:t,entry:null}),this._monitorIntersections(),this._checkForIntersections()}},i.prototype.unobserve=function(t){this._observationTargets=this._observationTargets.filter(function(e){return e.element!=t}),this._observationTargets.length||(this._unmonitorIntersections(),this._unregisterInstance())},i.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorIntersections(),this._unregisterInstance()},i.prototype.takeRecords=function(){var t=this._queuedEntries.slice();return this._queuedEntries=[],t},i.prototype._initThresholds=function(t){var e=t||[0];return Array.isArray(e)||(e=[e]),e.sort().filter(function(t,e,n){if("number"!=typeof t||isNaN(t)||t<0||t>1)throw new Error("threshold must be a number between 0 and 1 inclusively");return t!==n[e-1]})},i.prototype._parseRootMargin=function(t){var e=(t||"0px").split(/\s+/).map(function(t){var e=/^(-?\d*\.?\d+)(px|%)$/.exec(t);if(!e)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(e[1]),unit:e[2]}});return e[1]=e[1]||e[0],e[2]=e[2]||e[0],e[3]=e[3]||e[1],e},i.prototype._monitorIntersections=function(){this._monitoringIntersections||(this._monitoringIntersections=!0,this.POLL_INTERVAL?this._monitoringInterval=setInterval(this._checkForIntersections,this.POLL_INTERVAL):(o(t,"resize",this._checkForIntersections,!0),o(e,"scroll",this._checkForIntersections,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in t&&(this._domObserver=new MutationObserver(this._checkForIntersections),this._domObserver.observe(e,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))))},i.prototype._unmonitorIntersections=function(){this._monitoringIntersections&&(this._monitoringIntersections=!1,clearInterval(this._monitoringInterval),this._monitoringInterval=null,s(t,"resize",this._checkForIntersections,!0),s(e,"scroll",this._checkForIntersections,!0),this._domObserver&&(this._domObserver.disconnect(),this._domObserver=null))},i.prototype._checkForIntersections=function(){var e=this._rootIsInDom(),n=e?this._getRootRect():{top:0,bottom:0,left:0,right:0,width:0,height:0};this._observationTargets.forEach(function(i){var o=i.element,s=a(o),c=this._rootContainsTarget(o),u=i.entry,h=e&&c&&this._computeTargetAndRootIntersection(o,n),l=i.entry=new r({time:t.performance&&performance.now&&performance.now(),target:o,boundingClientRect:s,rootBounds:n,intersectionRect:h});u?e&&c?this._hasCrossedThreshold(u,l)&&this._queuedEntries.push(l):u&&u.isIntersecting&&this._queuedEntries.push(l):this._queuedEntries.push(l)},this),this._queuedEntries.length&&this._callback(this.takeRecords(),this)},i.prototype._computeTargetAndRootIntersection=function(n,r){if("none"!=t.getComputedStyle(n).display){for(var i=a(n),o=h(n),s=!1;!s;){var u=null,l=1==o.nodeType?t.getComputedStyle(o):{};if("none"==l.display)return;if(o==this.root||o==e?(s=!0,u=r):o!=e.body&&o!=e.documentElement&&"visible"!=l.overflow&&(u=a(o)),u&&!(i=c(u,i)))break;o=h(o)}return i}},i.prototype._getRootRect=function(){var t;if(this.root)t=a(this.root);else{var n=e.documentElement,r=e.body;t={top:0,left:0,right:n.clientWidth||r.clientWidth,width:n.clientWidth||r.clientWidth,bottom:n.clientHeight||r.clientHeight,height:n.clientHeight||r.clientHeight}}return this._expandRectByRootMargin(t)},i.prototype._expandRectByRootMargin=function(t){var e=this._rootMarginValues.map(function(e,n){return"px"==e.unit?e.value:e.value*(n%2?t.width:t.height)/100}),n={top:t.top-e[0],right:t.right+e[1],bottom:t.bottom+e[2],left:t.left-e[3]};return n.width=n.right-n.left,n.height=n.bottom-n.top,n},i.prototype._hasCrossedThreshold=function(t,e){var n=t&&t.isIntersecting?t.intersectionRatio||0:-1,r=e.isIntersecting?e.intersectionRatio||0:-1;if(n!==r)for(var i=0;i<this.thresholds.length;i++){var o=this.thresholds[i];if(o==n||o==r||o<n!=o<r)return!0}},i.prototype._rootIsInDom=function(){return!this.root||u(e,this.root)},i.prototype._rootContainsTarget=function(t){return u(this.root||e,t)},i.prototype._registerInstance=function(){n.indexOf(this)<0&&n.push(this)},i.prototype._unregisterInstance=function(){var t=n.indexOf(this);-1!=t&&n.splice(t,1)},t.IntersectionObserver=i,t.IntersectionObserverEntry=r}function r(t){this.time=t.time,this.target=t.target,this.rootBounds=t.rootBounds,this.boundingClientRect=t.boundingClientRect,this.intersectionRect=t.intersectionRect||{top:0,bottom:0,left:0,right:0,width:0,height:0},this.isIntersecting=!!t.intersectionRect;var e=this.boundingClientRect,n=e.width*e.height,r=this.intersectionRect,i=r.width*r.height;this.intersectionRatio=n?i/n:this.isIntersecting?1:0}function i(t,e){var n=e||{};if("function"!=typeof t)throw new Error("callback must be a function");if(n.root&&1!=n.root.nodeType)throw new Error("root must be an Element");this._checkForIntersections=function(t,e){var n=null;return function(){n||(n=setTimeout(function(){t(),n=null},e))}}(this._checkForIntersections.bind(this),this.THROTTLE_TIMEOUT),this._callback=t,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(n.rootMargin),this.thresholds=this._initThresholds(n.threshold),this.root=n.root||null,this.rootMargin=this._rootMarginValues.map(function(t){return t.value+t.unit}).join(" ")}function o(t,e,n,r){"function"==typeof t.addEventListener?t.addEventListener(e,n,r||!1):"function"==typeof t.attachEvent&&t.attachEvent("on"+e,n)}function s(t,e,n,r){"function"==typeof t.removeEventListener?t.removeEventListener(e,n,r||!1):"function"==typeof t.detatchEvent&&t.detatchEvent("on"+e,n)}function c(t,e){var n=Math.max(t.top,e.top),r=Math.min(t.bottom,e.bottom),i=Math.max(t.left,e.left),o=Math.min(t.right,e.right),s=o-i,c=r-n;return s>=0&&c>=0&&{top:n,bottom:r,left:i,right:o,width:s,height:c}}function a(t){var e;try{e=t.getBoundingClientRect()}catch(t){}return e?(e.width&&e.height||(e={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.right-e.left,height:e.bottom-e.top}),e):{top:0,bottom:0,left:0,right:0,width:0,height:0}}function u(t,e){for(var n=e;n;){if(n==t)return!0;n=h(n)}return!1}function h(t){var e=t.parentNode;return e&&11==e.nodeType&&e.host?e.host:e}}(window,document)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(3);e.toArray=r.default},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return[].slice.call(t)}}])}); */var r=this&&this.__assign||function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};n(1);var i=n(2),o=(s.prototype.start=function(t){var e=this;if(void 0===t&&(t=document.body),i.toArray(t.querySelectorAll("[data-track], [data-track-view]")).map(function(t){return e.track(t)}),!this._scrollTrackerInitialised){var n=i.debounce(function(){return e._onScroll()});window.addEventListener("scroll",n,{passive:!0}),this._onScroll(),this._scrollTrackerInitialised=!0}window.addEventListener("beforeunload",function(t){return e._onUnload(t)})},s.prototype.track=function(t){this._untrackFns.has(t)||this._untrackFns.set(t,{click:null,view:null});var e=this._untrackFns.get(t);null!==t.getAttribute("data-track")&&null==e.click&&(e.click=this._trackClicks(t)),null!==t.getAttribute("data-track-view")&&null==e.view&&(e.view=this._trackViews(t)),this._untrackFns.set(t,e)},s.prototype.untrack=function(t){var e=this._untrackFns.get(t);void 0!==e&&(null!==e.click&&e.click(),null!==e.view&&e.view(),this._untrackFns.delete(t))},s.prototype.send=function(t){if(null!==this.options.sendEventFn)return this.options.sendEventFn(t);if("function"==typeof window.gtag)return window.gtag("event",t.action,r(r({event_label:t.label,event_category:t.category,non_interaction:!t.interaction},t.metrics),t.dimensions));if("function"==typeof window.ga)return window.ga("send",{hitType:"event",eventCategory:t.category,eventAction:t.action,eventLabel:t.label,nonInteraction:!t.interaction},r(r({},t.metrics),t.dimensions));throw"No available analytics backend found. Has Google Analytics been loaded yet?"},s.prototype._parseEventString=function(t){var e=t.split(";").map(function(t){return t.trim()}),n=e[0],r=e[1],i=e[2];return 1===e.length&&(r=n,n=void 0),{category:n,action:r,label:i,interaction:!0}},s.prototype._trackClicks=function(e){function t(t){return n._onTrackedClick(e,t)}var n=this;return e.addEventListener("click",t),e.addEventListener("auxclick",t),function(){e.removeEventListener("click",t),e.removeEventListener("auxclick",t)}},s.prototype._trackViews=function(t){var e=this;return this._observer.observe(t),function(){e._observer.unobserve(t)}},s.prototype._onTrackedClick=function(t,e){var n=t.getAttribute("data-track"),r=this._parseEventString(n);r.metrics=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track:metrics")}).reduce(function(t,e){var n=e.name.replace(/data-track:metrics:/,""),r=""===e.value?1:e.value;return t[n]=r,t},{}),r.dimensions=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track:dimensions")}).reduce(function(t,e){if(""===e.value)return console.warn("No dimension value provided for "+e.name),t;var n=e.name.replace(/data-track:dimensions:/,""),r=e.value;return t[n]=r,t},{}),r.interaction=this.options.clicksAreInteractions,null!==t.getAttribute("data-track:non-interaction")&&(r.interaction=!1),this.send(r)},s.prototype._onTrackedView=function(t,e){var n=t.getAttribute("data-track-view"),r=this._parseEventString(n);r.metrics=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track-view:metrics")}).reduce(function(t,e){var n=e.name.replace(/data-track-view:metrics:/,""),r=""===e.value?1:e.value;return t[n]=r,t},{}),r.dimensions=i.toArray(t.attributes).filter(function(t){return t.name.startsWith("data-track-view:dimensions")}).reduce(function(t,e){if(""===e.value)return console.warn("No dimension value provided for "+e.name),t;var n=e.name.replace(/data-track-view:dimensions:/,""),r=e.value;return t[n]=r,t},{}),r.interaction=this.options.viewsAreInteractions,null!==t.getAttribute("data-track-view:interaction")&&(r.interaction=!0),this.send(r)},s.prototype._onScroll=function(t){void 0===t&&(t=document.documentElement);var e=Math.max(t.clientHeight,window.innerHeight||0),n=t.scrollTop+e;n>this._maxScrollY&&(this._maxScrollY=n)},s.prototype._onUnload=function(t){var e={category:"general",action:"scroll y",label:window.location.pathname,interaction:!1,value:Math.floor(this._maxScrollY/document.body.clientHeight*100)};this.send(e)},s.defaultOptions={defer:!1,observerOptions:{},clicksAreInteractions:!0,viewsAreInteractions:!1,sendEventFn:null},s);function s(t){var n=this;void 0===t&&(t={}),this._untrackFns=new Map,this._observer=null,this._maxScrollY=0,this._scrollTrackerInitialised=!1,this.options=r(r({},s.defaultOptions),t),this._observer=new IntersectionObserver(function(t,e){t.forEach(function(t){t.isIntersecting&&(n._onTrackedView(t.target,e),e.unobserve(t.target))})},this.options.observerOptions),this.options.defer||("complete"===document.readyState||"interactive"===document.readyState?this.start():window.addEventListener("DOMContentLoaded",function(){return n.start()}))}t.exports=o},function(t,e){!function(v,m){"use strict";if("IntersectionObserver"in v&&"IntersectionObserverEntry"in v&&"intersectionRatio"in v.IntersectionObserverEntry.prototype)"isIntersecting"in v.IntersectionObserverEntry.prototype||Object.defineProperty(v.IntersectionObserverEntry.prototype,"isIntersecting",{get:function(){return 0<this.intersectionRatio}});else{var e=[];t.prototype.THROTTLE_TIMEOUT=100,t.prototype.POLL_INTERVAL=null,t.prototype.USE_MUTATION_OBSERVER=!0,t.prototype.observe=function(e){if(!this._observationTargets.some(function(t){return t.element==e})){if(!e||1!=e.nodeType)throw new Error("target must be an Element");this._registerInstance(),this._observationTargets.push({element:e,entry:null}),this._monitorIntersections(),this._checkForIntersections()}},t.prototype.unobserve=function(e){this._observationTargets=this._observationTargets.filter(function(t){return t.element!=e}),this._observationTargets.length||(this._unmonitorIntersections(),this._unregisterInstance())},t.prototype.disconnect=function(){this._observationTargets=[],this._unmonitorIntersections(),this._unregisterInstance()},t.prototype.takeRecords=function(){var t=this._queuedEntries.slice();return this._queuedEntries=[],t},t.prototype._initThresholds=function(t){var e=t||[0];return Array.isArray(e)||(e=[e]),e.sort().filter(function(t,e,n){if("number"!=typeof t||isNaN(t)||t<0||1<t)throw new Error("threshold must be a number between 0 and 1 inclusively");return t!==n[e-1]})},t.prototype._parseRootMargin=function(t){var e=(t||"0px").split(/\s+/).map(function(t){var e=/^(-?\d*\.?\d+)(px|%)$/.exec(t);if(!e)throw new Error("rootMargin must be specified in pixels or percent");return{value:parseFloat(e[1]),unit:e[2]}});return e[1]=e[1]||e[0],e[2]=e[2]||e[0],e[3]=e[3]||e[1],e},t.prototype._monitorIntersections=function(){this._monitoringIntersections||(this._monitoringIntersections=!0,this.POLL_INTERVAL?this._monitoringInterval=setInterval(this._checkForIntersections,this.POLL_INTERVAL):(n(v,"resize",this._checkForIntersections,!0),n(m,"scroll",this._checkForIntersections,!0),this.USE_MUTATION_OBSERVER&&"MutationObserver"in v&&(this._domObserver=new MutationObserver(this._checkForIntersections),this._domObserver.observe(m,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))))},t.prototype._unmonitorIntersections=function(){this._monitoringIntersections&&(this._monitoringIntersections=!1,clearInterval(this._monitoringInterval),this._monitoringInterval=null,r(v,"resize",this._checkForIntersections,!0),r(m,"scroll",this._checkForIntersections,!0),this._domObserver&&(this._domObserver.disconnect(),this._domObserver=null))},t.prototype._checkForIntersections=function(){var c=this._rootIsInDom(),a=c?this._getRootRect():o();this._observationTargets.forEach(function(t){var e=t.element,n=_(e),r=this._rootContainsTarget(e),i=t.entry,o=c&&r&&this._computeTargetAndRootIntersection(e,a),s=t.entry=new u({time:v.performance&&performance.now&&performance.now(),target:e,boundingClientRect:n,rootBounds:a,intersectionRect:o});i?c&&r?this._hasCrossedThreshold(i,s)&&this._queuedEntries.push(s):i&&i.isIntersecting&&this._queuedEntries.push(s):this._queuedEntries.push(s)},this),this._queuedEntries.length&&this._callback(this.takeRecords(),this)},t.prototype._computeTargetAndRootIntersection=function(t,e){if("none"!=v.getComputedStyle(t).display){for(var n,r,i,o,s,c,a,u,l=_(t),h=g(t),d=!1;!d;){var f=null,p=1==h.nodeType?v.getComputedStyle(h):{};if("none"==p.display)return;if(h==this.root||h==m?(d=!0,f=e):h!=m.body&&h!=m.documentElement&&"visible"!=p.overflow&&(f=_(h)),f&&(n=f,r=l,0,i=Math.max(n.top,r.top),o=Math.min(n.bottom,r.bottom),s=Math.max(n.left,r.left),c=Math.min(n.right,r.right),u=o-i,!(l=0<=(a=c-s)&&0<=u&&{top:i,bottom:o,left:s,right:c,width:a,height:u})))break;h=g(h)}return l}},t.prototype._getRootRect=function(){var t;if(this.root)t=_(this.root);else{var e=m.documentElement,n=m.body;t={top:0,left:0,right:e.clientWidth||n.clientWidth,width:e.clientWidth||n.clientWidth,bottom:e.clientHeight||n.clientHeight,height:e.clientHeight||n.clientHeight}}return this._expandRectByRootMargin(t)},t.prototype._expandRectByRootMargin=function(n){var t=this._rootMarginValues.map(function(t,e){return"px"==t.unit?t.value:t.value*(e%2?n.width:n.height)/100}),e={top:n.top-t[0],right:n.right+t[1],bottom:n.bottom+t[2],left:n.left-t[3]};return e.width=e.right-e.left,e.height=e.bottom-e.top,e},t.prototype._hasCrossedThreshold=function(t,e){var n=t&&t.isIntersecting?t.intersectionRatio||0:-1,r=e.isIntersecting?e.intersectionRatio||0:-1;if(n!==r)for(var i=0;i<this.thresholds.length;i++){var o=this.thresholds[i];if(o==n||o==r||o<n!=o<r)return!0}},t.prototype._rootIsInDom=function(){return!this.root||i(m,this.root)},t.prototype._rootContainsTarget=function(t){return i(this.root||m,t)},t.prototype._registerInstance=function(){e.indexOf(this)<0&&e.push(this)},t.prototype._unregisterInstance=function(){var t=e.indexOf(this);-1!=t&&e.splice(t,1)},v.IntersectionObserver=t,v.IntersectionObserverEntry=u}function u(t){this.time=t.time,this.target=t.target,this.rootBounds=t.rootBounds,this.boundingClientRect=t.boundingClientRect,this.intersectionRect=t.intersectionRect||o(),this.isIntersecting=!!t.intersectionRect;var e=this.boundingClientRect,n=e.width*e.height,r=this.intersectionRect,i=r.width*r.height;this.intersectionRatio=n?Number((i/n).toFixed(4)):this.isIntersecting?1:0}function t(t,e){var n,r,i,o=e||{};if("function"!=typeof t)throw new Error("callback must be a function");if(o.root&&1!=o.root.nodeType)throw new Error("root must be an Element");this._checkForIntersections=(n=this._checkForIntersections.bind(this),r=this.THROTTLE_TIMEOUT,i=null,function(){i=i||setTimeout(function(){n(),i=null},r)}),this._callback=t,this._observationTargets=[],this._queuedEntries=[],this._rootMarginValues=this._parseRootMargin(o.rootMargin),this.thresholds=this._initThresholds(o.threshold),this.root=o.root||null,this.rootMargin=this._rootMarginValues.map(function(t){return t.value+t.unit}).join(" ")}function n(t,e,n,r){"function"==typeof t.addEventListener?t.addEventListener(e,n,r||!1):"function"==typeof t.attachEvent&&t.attachEvent("on"+e,n)}function r(t,e,n,r){"function"==typeof t.removeEventListener?t.removeEventListener(e,n,r||!1):"function"==typeof t.detatchEvent&&t.detatchEvent("on"+e,n)}function _(t){var e;try{e=t.getBoundingClientRect()}catch(t){}return e?(e.width&&e.height||(e={top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.right-e.left,height:e.bottom-e.top}),e):o()}function o(){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}function i(t,e){for(var n=e;n;){if(n==t)return!0;n=g(n)}return!1}function g(t){var e=t.parentNode;return e&&11==e.nodeType&&e.host?e.host:e}}(window,document)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(3);e.toArray=r.default;var i=n(4);e.debounce=i.default},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return[].slice.call(t)}},function(t,e,n){"use strict";function r(n,r){var i;return void 0===r&&(r=300),function(){var t=this,e=arguments;clearTimeout(i),i=setTimeout(function(){i=null,n.apply(t,e)},r)}}Object.defineProperty(e,"__esModule",{value:!0}),e.debounce=r,e.default=r}],i.c=r,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="/",i(i.s=0);function i(t){if(r[t])return r[t].exports;var e=r[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,i),e.l=!0,e.exports}var n,r});
\ No newline at end of file \ No newline at end of file
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
"webpack-cli": "^3.1.0" "webpack-cli": "^3.1.0"
}, },
"dependencies": { "dependencies": {
"intersection-observer": "^0.5.0" "intersection-observer": "^0.5.0",
"uglifyjs-webpack-plugin": "^2.2.0"
}, },
"scripts": { "scripts": {
"start": "webpack --watch & browser-sync start -s . -f .", "start": "webpack --watch & browser-sync start -s . -f .",
......
/*! /**!
* Foresight * Foresight
* *
* @author James Ooi <james.ooi@forefront.com.my> * @author James Ooi <james.ooi@forefront.com.my>
...@@ -29,6 +29,7 @@ interface EventData { ...@@ -29,6 +29,7 @@ interface EventData {
action: string; action: string;
label: string; label: string;
interaction: boolean; interaction: boolean;
value?: string | number | null | undefined;
metrics?: { metrics?: {
[key: string]: any; [key: string]: any;
}; };
...@@ -40,10 +41,6 @@ interface EventData { ...@@ -40,10 +41,6 @@ interface EventData {
* Foresight is an analytics library that allows for declarative event tracking. * Foresight is an analytics library that allows for declarative event tracking.
*/ */
declare class Foresight { declare class Foresight {
/**
* Default Options
* @static
*/
static defaultOptions: Partial<ForesightConfig>; static defaultOptions: Partial<ForesightConfig>;
/** /**
* Stores the options of the current Foresight instance. * Stores the options of the current Foresight instance.
...@@ -51,8 +48,8 @@ declare class Foresight { ...@@ -51,8 +48,8 @@ declare class Foresight {
*/ */
options: ForesightConfig; options: ForesightConfig;
/** /**
* Stores a mapping of elements with is respective functions to de-register * Stores a mapping of elements with its respective functions to de-register
* listeners. * the listeners.
* @private * @private
*/ */
private _untrackFns; private _untrackFns;
...@@ -62,6 +59,16 @@ declare class Foresight { ...@@ -62,6 +59,16 @@ declare class Foresight {
*/ */
private _observer; private _observer;
/** /**
* Store the current maximum page scroll amount.
* @private
*/
private _maxScrollY;
/**
* Indicates that the scroll tracker has already been initialised
* @private
*/
private _scrollTrackerInitialised;
/**
* @constructor * @constructor
*/ */
constructor(config?: ForesightConfig); constructor(config?: ForesightConfig);
...@@ -113,5 +120,10 @@ declare class Foresight { ...@@ -113,5 +120,10 @@ declare class Foresight {
* @private * @private
*/ */
private _onTrackedView; private _onTrackedView;
/**
* Handles a scroll event
*/
private _onScroll;
private _onUnload;
} }
export = Foresight; export = Foresight;
/**
* Returns a debounced function that as long as it continues to be invoked,
* will not be triggered until it stops being called for N milliseconds.
*/
declare function debounce(func: Function, wait?: number): () => void;
export default debounce;
export { debounce };
export { default as toArray } from './toArray'; export { default as toArray } from './toArray';
export { default as debounce } from './debounce';
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment