summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/tracking.js
blob: a852f937eec9d7c9606a3a909a98500e461c16cb (plain)
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
import $ from 'jquery';

const extractData = (el, opts = {}) => {
  const { trackEvent, trackLabel = '', trackProperty = '' } = el.dataset;
  let trackValue = el.dataset.trackValue || el.value || '';
  if (el.type === 'checkbox' && !el.checked) trackValue = false;
  return [
    trackEvent + (opts.suffix || ''),
    {
      label: trackLabel,
      property: trackProperty,
      value: trackValue,
    },
  ];
};

export default class Tracking {
  static trackable() {
    return !['1', 'yes'].includes(
      window.doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack,
    );
  }

  static enabled() {
    return typeof window.snowplow === 'function' && this.trackable();
  }

  static event(category = document.body.dataset.page, event = 'generic', data = {}) {
    if (!this.enabled()) return false;
    // eslint-disable-next-line @gitlab/i18n/no-non-i18n-strings
    if (!category) throw new Error('Tracking: no category provided for tracking.');

    return window.snowplow(
      'trackStructEvent',
      category,
      event,
      Object.assign({}, { label: '', property: '', value: '' }, data),
    );
  }

  constructor(category = document.body.dataset.page) {
    this.category = category;
  }

  bind(container = document) {
    if (!this.constructor.enabled()) return;
    container.querySelectorAll(`[data-track-event]`).forEach(el => {
      if (this.customHandlingFor(el)) return;
      // jquery is required for select2, so we use it always
      // see: https://github.com/select2/select2/issues/4686
      $(el).on('click', this.eventHandler(this.category));
    });
  }

  customHandlingFor(el) {
    const classes = el.classList;

    // bootstrap dropdowns
    if (classes.contains('dropdown')) {
      $(el).on('show.bs.dropdown', this.eventHandler(this.category, { suffix: '_show' }));
      $(el).on('hide.bs.dropdown', this.eventHandler(this.category, { suffix: '_hide' }));
      return true;
    }

    return false;
  }

  eventHandler(category = null, opts = {}) {
    return e => {
      this.constructor.event(category || this.category, ...extractData(e.currentTarget, opts));
    };
  }
}