All files / owid-grapher/grapher/core GrapherAnalytics.ts

55.37% Statements 67/121
100% Branches 4/4
20% Functions 2/10
55.37% Lines 67/121

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 1651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 218x 218x 218x 1x 1x 1x 1x 1x       1x 1x               1x 1x 1x 1x 1x 1x     1x 1x             1x 1x     1x 1x     1x 1x                                           1x 1x                                                                                                              
import { findDOMParent } from "../../clientUtils/Util"
 
const DEBUG = false
 
declare let window: any
 
// Docs on GA's event interface: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
interface GAEvent {
    hitType: string
    eventCategory: string
    eventAction: string
    eventLabel?: string
    eventValue?: number
}
 
enum Categories {
    GrapherError = "GrapherErrors",
    GrapherUsage = "GrapherUsage",
    GlobalEntitySelectorUsage = "GlobalEntitySelector",
    SiteClick = "SiteClick",
    KeyboardShortcut = "KeyboardShortcut",
}
 
enum EventNames {
    grapherViewError = "GRAPHER_VIEW_ERROR",
    entitiesNotFound = "ENTITIES_NOT_FOUND",
    timelinePlay = "TimelinePlay",
}
 
type entityControlEvent = "open" | "change" | "close"
type countrySelectorEvent =
    | "enter"
    | "select"
    | "deselect"
    | "sortBy"
    | "sortOrder"
 
// Note: consent-based blocking dealt with at the Google Tag Manager level.
// Events are discarded if consent not given.
export class GrapherAnalytics {
    constructor(environment: string = "", version = "1.0.0") {
        this.isDev = environment === "development"
        this.version = version
    }
 
    private version: string // Ideally the Git hash commit
    private isDev: boolean
 
    logGrapherViewError(error: any, info: any): void {
        this.logToAmplitude(EventNames.grapherViewError, { error, info })
        this.logToGA(Categories.GrapherError, EventNames.grapherViewError)
    }
 
    logEntitiesNotFoundError(entities: string[]): void {
        this.logToAmplitude(EventNames.entitiesNotFound, { entities })
        this.logToGA(
            Categories.GrapherError,
            EventNames.entitiesNotFound,
            JSON.stringify(entities)
        )
    }
 
    logGrapherTimelinePlay(slug?: string): void {
        this.logToGA(Categories.GrapherUsage, EventNames.timelinePlay, slug)
    }
 
    logGlobalEntitySelector(action: entityControlEvent, note?: string): void {
        this.logToGA(Categories.GlobalEntitySelectorUsage, action, note)
    }
 
    logEntityPickerEvent(
        pickerSlug: string,
        action: countrySelectorEvent,
        note?: string
    ): void {
        this.logToGA(`${pickerSlug}ExplorerCountrySelectorUsage`, action, note)
    }
 
    logSiteClick(action: string = "unknown-action", label: string): void {
        this.logToGA(Categories.SiteClick, action, label)
    }
 
    logKeyboardShortcut(shortcut: string, combo: string): void {
        this.logToGA(Categories.KeyboardShortcut, shortcut, combo)
    }
 
    startClickTracking(): void {
        // Todo: add a Story and tests for this OR even better remove and use Google Tag Manager or similar fully SAAS tracking.
        // Todo: have different Attributes for Grapher charts vs Site.
        const dataTrackAttr = "data-track-note"
        document.addEventListener("click", async (ev) => {
            const targetElement = ev.target as HTMLElement
            const trackedElement = findDOMParent(
                targetElement,
                (el: HTMLElement) => el.getAttribute(dataTrackAttr) !== null
            )
            if (!trackedElement) return

            // Note that browsers will cancel all pending requests once a user
            // navigates away from a page. An earlier implementation had a
            // timeout to send the event before navigating, but it broke
            // CMD+CLICK for opening a new tab.
            this.logSiteClick(
                trackedElement.getAttribute(dataTrackAttr) || undefined,
                trackedElement.innerText
            )
        })
    }
 
    protected logToAmplitude(name: string, props?: any): void {
        const allProps = {
            context: {
                siteVersion: this.version,
                pageHref: window.location.href,
                pagePath: window.location.pathname,
                pageTitle: document.title.replace(/ - [^-]+/, ""),
            },
            ...props,
        }

        if (DEBUG && this.isDev) {
            // eslint-disable-next-line no-console
            console.log("Analytics.logToAmplitude", name, allProps)
            return
        }
 
        if (!window.amplitude) return
        window.amplitude.getInstance().logEvent(name, allProps)
    }
 
    protected logToGA(
        eventCategory: string,
        eventAction: string,
        eventLabel?: string,
        eventValue?: number
    ): void {
        // Todo: send the Grapher (or site) version to Git
        const event: GAEvent = {
            hitType: "event",
            eventCategory,
            eventAction,
            eventLabel,
            eventValue,
        }
        if (DEBUG && this.isDev) {
            // eslint-disable-next-line no-console
            console.log("Analytics.logToGA", event)
            return
        }
 
        if (!window.ga) return
 
        // https://developers.google.com/analytics/devguides/collection/analyticsjs/ga-object-methods-reference
        window.ga(function () {
            const tracker = window.ga.getAll()[0]
            // @types/google.analytics seems to suggest this usage is invalid but we know Google
            // Analytics logs these events correctly.
            // I have avoided changing the implementation for now, but we should look into this as
            // we use Google Analytics more.
            // -@danielgavrilov 2020-04-23
            if (tracker) tracker.send(event as any)
        })
    }
}