-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathheatmaps.ts
222 lines (179 loc) · 7.08 KB
/
heatmaps.ts
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import RageClick from './extensions/rageclick'
import { DeadClickCandidate, Properties, RemoteConfig } from './types'
import { PostHog } from './posthog-core'
import { document, window } from './utils/globals'
import { getEventTarget, getParentElement } from './autocapture-utils'
import { HEATMAPS_ENABLED_SERVER_SIDE } from './constants'
import { isEmptyObject, isNumber, isObject, isUndefined } from './utils/type-utils'
import { createLogger } from './utils/logger'
import { isElementInToolbar, isElementNode, isTag } from './utils/element-utils'
import { DeadClicksAutocapture, isDeadClicksEnabledForHeatmaps } from './extensions/dead-clicks-autocapture'
import { includes } from './utils/string-utils'
import { addEventListener } from './utils'
const DEFAULT_FLUSH_INTERVAL = 5000
const logger = createLogger('[Heatmaps]')
type HeatmapEventBuffer =
| {
[key: string]: Properties[]
}
| undefined
function elementOrParentPositionMatches(el: Element | null, matches: string[], breakOnElement?: Element): boolean {
let curEl: Element | null | false = el
while (curEl && isElementNode(curEl) && !isTag(curEl, 'body')) {
if (curEl === breakOnElement) {
return false
}
if (includes(matches, window?.getComputedStyle(curEl).position)) {
return true
}
curEl = getParentElement(curEl)
}
return false
}
function isValidMouseEvent(e: unknown): e is MouseEvent {
return isObject(e) && 'clientX' in e && 'clientY' in e && isNumber(e.clientX) && isNumber(e.clientY)
}
export class Heatmaps {
instance: PostHog
rageclicks = new RageClick()
_enabledServerSide: boolean = false
_initialized = false
_mouseMoveTimeout: ReturnType<typeof setTimeout> | undefined
// TODO: Periodically flush this if no other event has taken care of it
private _buffer: HeatmapEventBuffer
private _flushInterval: ReturnType<typeof setInterval> | null = null
private _deadClicksCapture: DeadClicksAutocapture | undefined
constructor(instance: PostHog) {
this.instance = instance
this._enabledServerSide = !!this.instance.persistence?.props[HEATMAPS_ENABLED_SERVER_SIDE]
}
public get flushIntervalMilliseconds(): number {
let flushInterval = DEFAULT_FLUSH_INTERVAL
if (
isObject(this.instance.config.capture_heatmaps) &&
this.instance.config.capture_heatmaps.flush_interval_milliseconds
) {
flushInterval = this.instance.config.capture_heatmaps.flush_interval_milliseconds
}
return flushInterval
}
public get isEnabled(): boolean {
if (!isUndefined(this.instance.config.capture_heatmaps)) {
return this.instance.config.capture_heatmaps !== false
}
if (!isUndefined(this.instance.config.enable_heatmaps)) {
return this.instance.config.enable_heatmaps
}
return this._enabledServerSide
}
public startIfEnabled(): void {
if (this.isEnabled) {
// nested if here since we only want to run the else
// if this.enabled === false
// not if this method is called more than once
if (this._initialized) {
return
}
logger.info('starting...')
this._setupListeners()
this._flushInterval = setInterval(this._flush.bind(this), this.flushIntervalMilliseconds)
} else {
clearInterval(this._flushInterval ?? undefined)
this._deadClicksCapture?.stop()
this.getAndClearBuffer()
}
}
public onRemoteConfig(response: RemoteConfig) {
const optIn = !!response['heatmaps']
if (this.instance.persistence) {
this.instance.persistence.register({
[HEATMAPS_ENABLED_SERVER_SIDE]: optIn,
})
}
// store this in-memory in case persistence is disabled
this._enabledServerSide = optIn
this.startIfEnabled()
}
public getAndClearBuffer(): HeatmapEventBuffer {
const buffer = this._buffer
this._buffer = undefined
return buffer
}
private _onDeadClick(click: DeadClickCandidate): void {
this._onClick(click.originalEvent, 'deadclick')
}
private _setupListeners(): void {
if (!window || !document) {
return
}
addEventListener(window, 'beforeunload', this._flush.bind(this))
addEventListener(document, 'click', (e) => this._onClick((e || window?.event) as MouseEvent), { capture: true })
addEventListener(document, 'mousemove', (e) => this._onMouseMove((e || window?.event) as MouseEvent), {
capture: true,
})
this._deadClicksCapture = new DeadClicksAutocapture(
this.instance,
isDeadClicksEnabledForHeatmaps,
this._onDeadClick.bind(this)
)
this._deadClicksCapture.startIfEnabled()
this._initialized = true
}
private _getProperties(e: MouseEvent, type: string): Properties {
// We need to know if the target element is fixed or not
// If fixed then we won't account for scrolling
// If not then we will account for scrolling
const scrollY = this.instance.scrollManager.scrollY()
const scrollX = this.instance.scrollManager.scrollX()
const scrollElement = this.instance.scrollManager.scrollElement()
const isFixedOrSticky = elementOrParentPositionMatches(getEventTarget(e), ['fixed', 'sticky'], scrollElement)
return {
x: e.clientX + (isFixedOrSticky ? 0 : scrollX),
y: e.clientY + (isFixedOrSticky ? 0 : scrollY),
target_fixed: isFixedOrSticky,
type,
}
}
private _onClick(e: MouseEvent, type: string = 'click'): void {
if (isElementInToolbar(e.target) || !isValidMouseEvent(e)) {
return
}
const properties = this._getProperties(e, type)
if (this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())) {
this._capture({
...properties,
type: 'rageclick',
})
}
this._capture(properties)
}
private _onMouseMove(e: Event): void {
if (isElementInToolbar(e.target) || !isValidMouseEvent(e)) {
return
}
clearTimeout(this._mouseMoveTimeout)
this._mouseMoveTimeout = setTimeout(() => {
this._capture(this._getProperties(e as MouseEvent, 'mousemove'))
}, 500)
}
private _capture(properties: Properties): void {
if (!window) {
return
}
// TODO we should be able to mask this
const url = window.location.href
this._buffer = this._buffer || {}
if (!this._buffer[url]) {
this._buffer[url] = []
}
this._buffer[url].push(properties)
}
private _flush(): void {
if (!this._buffer || isEmptyObject(this._buffer)) {
return
}
this.instance.capture('$$heatmap', {
$heatmap_data: this.getAndClearBuffer(),
})
}
}