All files / src/analytics Autocollector.ts

59% Statements 59/100
44.29% Branches 31/70
47.06% Functions 8/17
60.22% Lines 56/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188            1x       1x 1x 1x     1x       1x             17x 17x 17x 17x 4x 1x 1x 1x 1x 1x       1x       1x       4x 1x               1x 13x 13x 13x 13x                       1x 3x 3x 3x 3x       3x     1x 3x         1x 1x 1x 1x   1x 1x 1x       1x 1x 1x 1x 1x           1x       1x 1x 1x 1x   1x 1x 1x       1x                                                                                           1x                             1x  
/**
* Autocollector.ts
* @author Abhilash Panwar (abpanwar) Hector Hernandez (hectorh)
* @copyright Microsoft 2020
* File containing class for autocollecting signals for EI.
*/
import { Utils, getLocation, getDocument, isDocumentObjectAvailable, getWindow, isWindowObjectAvailable } from '@microsoft/1ds-core-js';
import Analytics from '../Analytics';
import { IView, IAutoCapture, IAction, ISource } from './DataModels';
import { IScreenResolution } from './InternalDataModels';
import { _isRightClick, _isLeftClick, _isMiddleClick, _isKeyboardEnter, _isKeyboardSpace, _clickCaptureInputTypes, _getClickTarget, _getContent, } from './AnalyticsHelper';
import { ActionType } from './Enums';
import { _emptyString, _SourceEventName, _sourceEventVersion } from '../properties/Constants';
import { IEvent, IReferrer } from '../Index';
 
const clickCaptureElements = { A: true, BUTTON: true, AREA: true, INPUT: true };
/**
 * Class for autocollecting signals.
 */
export default class Autocollector {
  private _analytics: Analytics;
  /**
   * Autocollects signals based on the config passed.
   * @param analytics The analytics class to use to send signals.
   * @param config The config detailing what needs to be auto collected.   
   */
  _autocollect(analytics: Analytics, config: IAutoCapture) {    
    this._analytics = analytics;
    let captureView = this._captureView.bind(this);
    if (config && Utils.isObject(config)) {
      if (config.view) {
        captureView();
        let win = getWindow();
        const _replaceState = win.history.replaceState;
        const _pushState = win.history.pushState;
        win.history.replaceState = function () {
          _replaceState.apply(win.history, arguments);
          captureView();
        };
        win.history.pushState = function () {
          _pushState.apply(win.history, arguments);
          captureView();
        };
        win.addEventListener('load', (event)=>{
          this._sendSourceCodeEvent();
        });
      }
      if (config.click) {
        this._captureClicks();
      }
    }
  }
 
  /**
   * Gets the screen resolution.
   */
  _getScreenResolution(): IScreenResolution {
    Eif (isDocumentObjectAvailable && isWindowObjectAvailable) {
      let win = getWindow();
      let doc = getDocument();
      return {
        h: screen.height,
        w: screen.width,
        cd: screen.colorDepth,
        vW: Math.max(doc.documentElement.clientWidth, win.innerWidth || 0),
        vH: Math.max(doc.documentElement.clientHeight, win.innerHeight || 0),
        sR: screen.height && screen.width ? screen.height + 'X' + screen.width : _emptyString
      };
    }
    return null;
  }
 
  _getPageNameFromPath(pageName: string): string {
    pageName = pageName.replace(/\/$/, "");
    let fragments = pageName.split('/');
    Eif (fragments && fragments[fragments.length - 1] !== _emptyString) {
      pageName = fragments[fragments.length - 1];
    } else {
      pageName = '/';
    }
    return pageName;
  }
 
  _getReferrer(doc: Document): IReferrer {
    return {
      uri: doc.referrer
    };
  }
 
  _removeAllListeners() {
    let win = getWindow();
    let doc = getDocument();
    Eif (win && win.addEventListener) {
        // IE9 onwards addEventListener is available, 'click' event captures mouse click. mousedown works on other browsers
        var event = (navigator.appVersion.indexOf('MSIE') !== -1) ? 'click' : 'mousedown';
        win.removeEventListener(event, (evt) => { this._processClick(evt); }, false);
        win.removeEventListener('keyup', (evt) => { this._processClick(evt); }, false);
    }
  }
 
  private _captureView() {
    let loc = getLocation();
    Eif (isDocumentObjectAvailable && loc) {
      let doc = getDocument();     
      let view: IView = {
        uri: loc.href,
        title: doc.title.substring(0, 150),
        name: this._getPageNameFromPath(loc.pathname || _emptyString),
        referrer: this._getReferrer(doc)
      };
      this._analytics.trackView(view);
    }
  }
 
  private _captureClicks() {
    let win = getWindow();
    let doc = getDocument();
    Eif (win && win.addEventListener) {
        // IE9 onwards addEventListener is available, 'click' event captures mouse click. mousedown works on other browsers
        var event = (navigator.appVersion.indexOf('MSIE') !== -1) ? 'click' : 'mousedown';
        win.addEventListener(event, (evt) => { this._processClick(evt); }, false);
        win.addEventListener('keyup', (evt) => { this._processClick(evt); }, false);
    }
  }
 
  private _processClick(clickEvent: any) {
    let element = clickEvent.srcElement || clickEvent.target; 
    let sendAction = false;  
    // Check if we should capture the element
    while (element && element.tagName) {
      if (element.control && clickCaptureElements[element.control.tagName.toUpperCase()]) {
        element = element.control;
      }
      if (!clickCaptureElements[element.tagName.toUpperCase()]) {
        element = element.parentElement || element.parentNode;
        continue;
      } else {
        // Check allowed INPUT types
        sendAction = element.tagName.toUpperCase() === 'INPUT' ? _clickCaptureInputTypes[element.type.toUpperCase()] : true;
        break;
      }
    }
    if (sendAction) {
      // Capture the action type
      let actionType: string;
      if (_isRightClick(clickEvent as MouseEvent)) {
        actionType = ActionType.rightClick;
      } else if (_isLeftClick(clickEvent as MouseEvent)) {
        actionType = ActionType.leftClick;
      } else if (_isKeyboardEnter(clickEvent as KeyboardEvent)) {
        actionType = ActionType.keyboardEnter;
      } else if (_isKeyboardSpace(clickEvent as KeyboardEvent)) {
        actionType = ActionType.keyboardSpace;
      } else if (_isMiddleClick(clickEvent as MouseEvent)) {
        actionType = ActionType.middleClick;
      } else {
        return;
      }    
      const content = _getContent(element);
      const action: IAction = {
        name: content.n,
        type: actionType,
        clickCoordinates: clickEvent.pageX + 'X' + clickEvent.pageY,
        class: content.c,
        elementId: content.id,
        viewTarget: _getClickTarget(element)
      };
      this._analytics.trackAction(action);
    }
  }
 
  private _sendSourceCodeEvent() {
    let doc = getDocument();
    let loc = getLocation();
    const event: IEvent = {
      name: _SourceEventName,
      version: _sourceEventVersion,
      timestamp: new Date(),
      properties: {
        pageName: this._getPageNameFromPath(loc.pathname || _emptyString),
        uri: loc.href,
        sourceHtml: doc.documentElement.innerHTML
      }
    }
    this._analytics.trackEvent(event);
  }
}