UNPKG

react-analytics-tracker

Version:

react-analytics-tracker is a React component for tracking user interactions and events on your web application. This component captures click and view events, collects various data points, and reports them to a specified endpoint.

3 lines (2 loc) 12.5 kB
import t,{Component as e,createContext as n}from"react";var o=function(t,e){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},o(t,e)};function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var i,a,s=function(){return s=Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++)for(var r in e=arguments[n])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t},s.apply(this,arguments)};function c(t,e,n,o){return new(n||(n=Promise))((function(r,i){function a(t){try{c(o.next(t))}catch(t){i(t)}}function s(t){try{c(o.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((o=o.apply(t,e||[])).next())}))}function u(t,e){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(a=0)),a;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,o=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){a.label=s[1];break}if(6===s[0]&&a.label<r[1]){a.label=r[1],r=s;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(s);break}r[2]&&a.ops.pop(),a.trys.pop();continue}s=e.call(t,a)}catch(t){s=[6,t],o=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function l(t,e,n){if(n||2===arguments.length)for(var o,r=0,i=e.length;r<i;r++)!o&&r in e||(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var p,d,h,f;function v(t,e){var n;return function(){for(var o=[],r=0;r<arguments.length;r++)o[r]=arguments[r];var i=this;clearTimeout(n),n=setTimeout((function(){return t.apply(i,o)}),e)}}!function(t){t.CLICK="click",t.MOUSE_OVER="mouseover",t.MOUSE_OUT="mouseout",t.MOUSE_UP="mouseup",t.MOUSE_DOWN="mousedown",t.MOUSE_MOVE="mousemove",t.MOUSE_ENTER="mouseenter",t.MOUSE_LEAVE="mouseleave",t.MOUSE_OVER_OUT="mouseover mouseout",t.DOUBLE_CLICK="dblclick",t.CONTEXT_MENU="contextmenu"}(p||(p={})),function(t){t.SUBMIT="submit",t.RESET="reset"}(d||(d={})),function(t){t.CHANGE="change",t.FOCUS="focus",t.BLUR="blur",t.KEYPRESS="keypress",t.SELECT="select",t.KEYUP="keyup",t.KEYDOWN="keydown"}(h||(h={})),function(t){t.TOUCH_START="touchstart",t.TOUCH_MOVE="touchmove",t.TOUCH_END="touchend",t.TOUCH_CANCEL="touchcancel"}(f||(f={}));var m=l(l(l(l([],Object.values(p),!0),Object.values(d),!0),Object.values(f),!0),Object.values(h),!0);console.log("EVENTS:",m);var g=function(e){function n(t){var n=e.call(this,t)||this;if(n.sessionId="",n.firebaseEndpoint="https://react-analytics-tracker-firebase.vercel.app/data",n.reportingEndpoint="",n.handleClick=v((function(t){var e=t.target.closest("[data-component]")||"",o=t.target.getAttribute("data-element")||t.target.tagName;if(o&&"click"===t.type){var r=t.target.getAttribute("class")||"",i=t.target.getAttribute("id")||"",a=t.target.getAttribute("data-element-data")||"",s=t.clientX+"x"+t.clientY,c=JSON.stringify({clickCoords:s,data:a,className:r,id:i});n.trackEvent("click",{eventData:c,elementName:o,componentName:e?e.getAttribute("data-component"):""})}}),300),n.handleTriggerEvent=v((function(t){var e=t.target.getAttribute("data-event")||"",o=t.target.closest("[data-component]")||"",r=t.target.getAttribute("data-element")||t.target.tagName;if(e===t.type&&r){var i=t.target.getAttribute("class")||"",a=t.target.getAttribute("id")||"",s=t.target.getAttribute("data-element-data")||"",c=JSON.stringify({data:s,className:i,id:a});n.trackEvent(e,{eventData:c,elementName:r,componentName:o?o.getAttribute("data-component"):""})}}),300),n.handleIntersect=function(t){"undefined"!=typeof window&&t.forEach((function(t){if(t.isIntersecting){var e=t.target.getAttribute("data-component")||"",o=t.target.getAttribute("data-component-data")||"",r=t.target.getAttribute("data-element")||t.target.tagName,i=100*t.intersectionRatio,a=t.target.getBoundingClientRect(),s={x:a.x,y:a.y,width:a.width,height:a.height,top:a.top,right:a.right,bottom:a.bottom,left:a.left},c=window.scrollY||window.pageYOffset,u=JSON.stringify({viewedPercentage:i,scrollPosition:c,bounds:s,data:o||""});n.trackEvent("view",{eventData:u,componentName:e,elementName:r||""})}}))},n.observeNewComponents=function(t){Array.isArray(t)&&t.length>0&&t.forEach((function(t){"childList"===t.type&&t.addedNodes&&t.addedNodes.length>0&&t.addedNodes.forEach((function(t){var e;1===t.nodeType&&t.hasAttribute("data-component")&&(null===(e=n.observer)||void 0===e||e.observe(t));var o=t.querySelectorAll("[data-component]");o&&o.length>0&&o.forEach((function(t){var e;null===(e=n.observer)||void 0===e||e.observe(t)}))}))}))},!t.appName||!t.appVersion)throw new Error("appName and appVersion are required");return n.reportingEndpoint=t.reportingEndpoint||n.firebaseEndpoint,n.heartBeatInterval=t.heartBeatInterval||4e3,"undefined"!=typeof window&&(n.sessionId=window.sessionStorage.getItem("rat:sessionId")||n.generateSessionId(),window.sessionStorage.setItem("rat:sessionId",n.sessionId)),n.eventCollections=[],n}return r(n,e),n.prototype.generateSessionId=function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},n.prototype.getCookieValue=function(t){for(var e=t+"=",n=document.cookie.split(";"),o=0;o<n.length;o++){var r=n[o].trim();if(0===r.indexOf(e))return r.substring(e.length,r.length)}return""},n.prototype.constructPayload=function(){if("undefined"==typeof window)return{referrer:"",url:"",pathname:"",hostname:"",title:"",screen:"",language:"",utmSource:"",utmMedium:"",utmCampaign:"",utmTerm:"",utmContent:"",sessionId:"",network:{isOnline:!1},events:[]};var t=sessionStorage.getItem("rat:storedEvents"),e=l(l([],(t?JSON.parse(t):[]).filter((function(t){return!t.failedCount||t.failedCount<3})),!0),this.eventCollections,!0),n={appName:this.props.appName||"",appVersion:this.props.appVersion||"",referrer:document.referrer||window.location.ancestorOrigins[0]||"",url:window.location.href,pathname:window.location.pathname,hostname:window.location.hostname,title:document.title,screen:window.screen.width+"x"+window.screen.height,language:navigator.language,utmSource:this.getCookieValue("utm_source"),utmMedium:this.getCookieValue("utm_medium"),utmCampaign:this.getCookieValue("utm_campaign"),utmTerm:this.getCookieValue("utm_term"),utmContent:this.getCookieValue("utm_content"),sessionId:this.sessionId,network:this.getNetworkConnectionInfo(),events:null==e?void 0:e.map((function(t){return{component:t.component,element:t.element,data:t.data,event:t.event,timestamp:t.timestamp}}))};return this.props.customPayload&&Object.assign(n,this.props.customPayload),n},n.prototype.report=function(){return c(this,arguments,void 0,(function(t){var e;return void 0===t&&(t=function(){}),u(this,(function(n){switch(n.label){case 0:if(!(this.eventCollections.length>0))return[3,4];n.label=1;case 1:return n.trys.push([1,3,,4]),e=this.constructPayload(),this.props.customPayload&&Object.assign(e,this.props.customPayload),this.props.onReport&&"function"==typeof this.props.onReport&&this.props.onReport(e),[4,fetch(this.reportingEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})];case 2:return n.sent().ok?(this.eventCollections.length=0,sessionStorage.removeItem("rat:storedEvents"),t()):(this.storeEventsInSession(),t()),[3,4];case 3:return n.sent(),this.storeEventsInSession(),t(),[3,4];case 4:return[2]}}))}))},n.prototype.storeEventsInSession=function(){var t=sessionStorage.getItem("rat:storedEvents"),e=t?JSON.parse(t):[],n=this.eventCollections.map((function(t){return s(s({},t),{failedCount:t.failedCount?t.failedCount+1:1})})).filter((function(t){return t.failedCount<3})),o=l(l([],e,!0),n,!0);sessionStorage.setItem("rat:storedEvents",JSON.stringify(o)),this.eventCollections.length=0},n.prototype.getNetworkConnection=function(){return"undefined"==typeof navigator?null:navigator.connection||navigator.mozConnection||navigator.webkitConnection||null},n.prototype.getNetworkConnectionInfo=function(){var t=this.getNetworkConnection();return t?{rtt:t.rtt,type:t.type,saveData:t.saveData,downLink:t.downLink,effectiveType:t.effectiveType,isOnline:navigator.onLine}:{isOnline:"undefined"!=typeof navigator&&navigator.onLine}},n.prototype.trackEvent=function(t,e,n){void 0===n&&(n=!1);var o={data:(null==e?void 0:e.eventData)||"",event:t,element:(null==e?void 0:e.elementName)||"",component:(null==e?void 0:e.componentName)||"",timestamp:Date.now()};this.props.customProperties&&Object.assign(o,this.props.customProperties),this.eventCollections.push(o),"view"===t?this.eventCollections.length>4&&this.report():("click"===t||n)&&this.report()},n.prototype.trackCustomEvent=function(t,e,n){void 0===n&&(n=!1),this.trackEvent(t,e,n)},n.prototype.componentDidMount=function(){var t=this;if("undefined"!=typeof window){this.observer=new IntersectionObserver(this.handleIntersect,{threshold:.1}),this.mutationObserver=new MutationObserver(this.observeNewComponents),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0});var e=document.querySelectorAll("[data-component]");e&&e.length>0&&e.forEach((function(e){var n;return null===(n=t.observer)||void 0===n?void 0:n.observe(e)})),document.addEventListener("click",this.handleClick);var n=document.querySelectorAll("[data-event]");n&&n.length>0&&n.forEach((function(e){var n=e.getAttribute("data-event");e.getAttribute("data-element"),n&&m.includes(n)&&document.addEventListener(n,t.handleTriggerEvent)})),this.handleVisibilityChange=function(){"hidden"===document.visibilityState&&t.report()},void 0!==document.hidden?a="visibilitychange":void 0!==document.msHidden?a="msvisibilitychange":void 0!==document.webkitHidden&&(a="webkitvisibilitychange"),document.addEventListener(a,this.handleVisibilityChange),i=setInterval((function(){t.report()}),this.heartBeatInterval)}},n.prototype.componentWillUnmount=function(){var t,e,n=this;document.removeEventListener("click",this.handleClick),null===(t=this.mutationObserver)||void 0===t||t.disconnect(),null===(e=this.observer)||void 0===e||e.disconnect(),i&&(clearInterval(i),this.report()),document.removeEventListener(a,this.handleVisibilityChange);var o=document.querySelectorAll("[data-event]");o&&o.length>0&&o.forEach((function(t){var e=t.getAttribute("data-event");e&&m.includes(e)&&document.removeEventListener(e,n.handleTriggerEvent)}))},n.prototype.render=function(){return t.createElement(t.Fragment,null,this.props.children)},n}(e),y=n(null),b=function(e){function n(n){var o=e.call(this,n)||this;return o.analyticsTrackerRef=t.createRef(),o}return r(n,e),n.prototype.render=function(){var e=this.props,n=e.children,o=function(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(t);r<o.length;r++)e.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(t,o[r])&&(n[o[r]]=t[o[r]])}return n}(e,["children"]);return t.createElement(y.Provider,{value:{tracker:this.analyticsTrackerRef}},t.createElement(g,s({},o,{ref:this.analyticsTrackerRef}),n))},n}(e),E=function(n){var o;return(o=function(e){function o(t){var n=e.call(this,t)||this;return n.state={tracker:null},n}return r(o,e),o.prototype.componentDidMount=function(){this.context&&this.setState({tracker:this.context.tracker})},o.prototype.render=function(){var e=this.state.tracker;return t.createElement(n,s({},this.props,{tracker:null==e?void 0:e.current}))},o}(e)).contextType=y,o};export{b as AnalyticsProvider,g as AnalyticsTracker,E as withAnalytics}; //# sourceMappingURL=index.es.js.map