-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathtrackClickActions.ts
More file actions
405 lines (359 loc) · 12.5 KB
/
trackClickActions.ts
File metadata and controls
405 lines (359 loc) · 12.5 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import type { Duration, ClocksState, RelativeTime, TimeStamp, ValueHistory } from '@datadog/browser-core'
import {
timeStampNow,
Observable,
getRelativeTime,
ONE_MINUTE,
generateUUID,
elapsed,
createValueHistory,
PageExitReason,
relativeToClocks,
} from '@datadog/browser-core'
import { isNodeShadowHost } from '../../browser/htmlDomUtils'
import type { FrustrationType } from '../../rawRumEvent.types'
import { ActionType } from '../../rawRumEvent.types'
import type { LifeCycle } from '../lifeCycle'
import { LifeCycleEventType } from '../lifeCycle'
import { trackEventCounts } from '../trackEventCounts'
import { PAGE_ACTIVITY_VALIDATION_DELAY, waitPageActivityEnd } from '../waitPageActivityEnd'
import { getSelectorFromElement } from '../getSelectorFromElement'
import { getNodePrivacyLevel } from '../privacy'
import { NodePrivacyLevel } from '../privacyConstants'
import type { RumConfiguration } from '../configuration'
import type { RumMutationRecord } from '../../browser/domMutationObservable'
import type { ClickChain } from './clickChain'
import { createClickChain } from './clickChain'
import { getActionNameFromElement } from './getActionNameFromElement'
import type { ActionNameSource } from './actionNameConstants'
import type { MouseEventOnElement, UserActivity } from './listenActionEvents'
import { listenActionEvents } from './listenActionEvents'
import { computeFrustration } from './computeFrustration'
import { CLICK_ACTION_MAX_DURATION, updateInteractionSelector } from './interactionSelectorCache'
interface ActionCounts {
errorCount: number
longTaskCount: number
resourceCount: number
}
export interface ClickAction {
type: typeof ActionType.CLICK
id: string
name: string
nameSource: ActionNameSource
target?: {
selector: string | undefined
width: number
height: number
}
position?: { x: number; y: number }
startClocks: ClocksState
duration?: Duration
counts: ActionCounts
event: MouseEventOnElement
frustrationTypes: FrustrationType[]
events: Event[]
}
export interface ActionContexts {
findActionId: (startTime?: RelativeTime) => string | string[] | undefined
}
type ClickActionIdHistory = ValueHistory<ClickAction['id']>
export const ACTION_CONTEXT_TIME_OUT_DELAY = 5 * ONE_MINUTE // arbitrary
export function trackClickActions(
lifeCycle: LifeCycle,
domMutationObservable: Observable<RumMutationRecord[]>,
windowOpenObservable: Observable<void>,
configuration: RumConfiguration
) {
const history: ClickActionIdHistory = createValueHistory({ expireDelay: ACTION_CONTEXT_TIME_OUT_DELAY })
const stopObservable = new Observable<void>()
let currentClickChain: ClickChain | undefined
lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {
history.reset()
})
lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, stopClickChain)
lifeCycle.subscribe(LifeCycleEventType.PAGE_MAY_EXIT, (event) => {
if (event.reason === PageExitReason.UNLOADING) {
stopClickChain()
}
})
const { stop: stopActionEventsListener } = listenActionEvents<{
clickActionBase: ClickActionBase
hadActivityOnPointerDown: () => boolean
}>(configuration, {
onPointerDown: (pointerDownEvent) =>
processPointerDown(configuration, lifeCycle, domMutationObservable, pointerDownEvent, windowOpenObservable),
onPointerUp: ({ clickActionBase, hadActivityOnPointerDown }, startEvent, getUserActivity) => {
startClickAction(
configuration,
lifeCycle,
domMutationObservable,
windowOpenObservable,
history,
stopObservable,
appendClickToClickChain,
clickActionBase,
startEvent,
getUserActivity,
hadActivityOnPointerDown
)
},
})
const actionContexts: ActionContexts = {
findActionId: (startTime?: RelativeTime) => history.findAll(startTime),
}
return {
stop: () => {
stopClickChain()
stopObservable.notify()
stopActionEventsListener()
},
actionContexts,
}
function appendClickToClickChain(click: Click) {
if (!currentClickChain || !currentClickChain.tryAppend(click)) {
const rageClick = click.clone()
currentClickChain = createClickChain(click, (clicks) => {
finalizeClicks(clicks, rageClick)
// Clear the reference to allow garbage collection. Without this, the finalize callback
// retains a closure reference to the old click chain, preventing it from being cleaned up
// and causing a memory leak as click chains accumulate over time.
currentClickChain = undefined
})
}
}
function stopClickChain() {
if (currentClickChain) {
currentClickChain.stop()
}
}
}
function processPointerDown(
configuration: RumConfiguration,
lifeCycle: LifeCycle,
domMutationObservable: Observable<RumMutationRecord[]>,
pointerDownEvent: MouseEventOnElement,
windowOpenObservable: Observable<void>
) {
const targetForPrivacy = configuration.betaTrackActionsInShadowDom
? getEventTarget(pointerDownEvent)
: pointerDownEvent.target
let nodePrivacyLevel: NodePrivacyLevel
if (configuration.enablePrivacyForActionName) {
nodePrivacyLevel = getNodePrivacyLevel(targetForPrivacy, configuration.defaultPrivacyLevel)
} else {
nodePrivacyLevel = NodePrivacyLevel.ALLOW
}
if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {
return undefined
}
const clickActionBase = computeClickActionBase(pointerDownEvent, nodePrivacyLevel, configuration)
let hadActivityOnPointerDown = false
waitPageActivityEnd(
lifeCycle,
domMutationObservable,
windowOpenObservable,
configuration,
(pageActivityEndEvent) => {
hadActivityOnPointerDown = pageActivityEndEvent.hadActivity
},
// We don't care about the activity duration, we just want to know whether an activity did happen
// within the "validation delay" or not. Limit the duration so the callback is called sooner.
PAGE_ACTIVITY_VALIDATION_DELAY
)
return { clickActionBase, hadActivityOnPointerDown: () => hadActivityOnPointerDown }
}
function startClickAction(
configuration: RumConfiguration,
lifeCycle: LifeCycle,
domMutationObservable: Observable<RumMutationRecord[]>,
windowOpenObservable: Observable<void>,
history: ClickActionIdHistory,
stopObservable: Observable<void>,
appendClickToClickChain: (click: Click) => void,
clickActionBase: ClickActionBase,
startEvent: MouseEventOnElement,
getUserActivity: () => UserActivity,
hadActivityOnPointerDown: () => boolean
) {
const click = newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent)
appendClickToClickChain(click)
const selector = clickActionBase?.target?.selector
if (selector) {
updateInteractionSelector(startEvent.timeStamp, selector)
}
const { stop: stopWaitPageActivityEnd } = waitPageActivityEnd(
lifeCycle,
domMutationObservable,
windowOpenObservable,
configuration,
(pageActivityEndEvent) => {
if (pageActivityEndEvent.hadActivity && pageActivityEndEvent.end < click.startClocks.timeStamp) {
// If the clock is looking weird, just discard the click
click.discard()
} else {
if (pageActivityEndEvent.hadActivity) {
click.stop(pageActivityEndEvent.end)
} else if (hadActivityOnPointerDown()) {
click.stop(
// using the click start as activity end, so the click will have some activity but its
// duration will be 0 (as the activity started before the click start)
click.startClocks.timeStamp
)
} else {
click.stop()
}
}
},
CLICK_ACTION_MAX_DURATION
)
const viewEndedSubscription = lifeCycle.subscribe(LifeCycleEventType.VIEW_ENDED, ({ endClocks }) => {
click.stop(endClocks.timeStamp)
})
const stopSubscription = stopObservable.subscribe(() => {
click.stop()
})
click.stopObservable.subscribe(() => {
viewEndedSubscription.unsubscribe()
stopWaitPageActivityEnd()
stopSubscription.unsubscribe()
})
}
type ClickActionBase = Pick<ClickAction, 'type' | 'name' | 'nameSource' | 'target' | 'position'>
function computeClickActionBase(
event: MouseEventOnElement,
nodePrivacyLevel: NodePrivacyLevel,
configuration: RumConfiguration
): ClickActionBase {
const selectorTarget = event.target
const rect = selectorTarget.getBoundingClientRect()
const selector = getSelectorFromElement(selectorTarget, configuration.actionNameAttribute)
if (selector) {
updateInteractionSelector(event.timeStamp, selector)
}
const nameTarget = configuration.betaTrackActionsInShadowDom ? getEventTarget(event) : event.target
const { name, nameSource } = getActionNameFromElement(nameTarget, configuration, nodePrivacyLevel)
return {
type: ActionType.CLICK,
target: {
width: Math.round(rect.width),
height: Math.round(rect.height),
selector,
},
position: {
// Use clientX and Y because for SVG element offsetX and Y are relatives to the <svg> element
x: Math.round(event.clientX - rect.left),
y: Math.round(event.clientY - rect.top),
},
name,
nameSource,
}
}
function getEventTarget(event: MouseEventOnElement): Element {
if (event.composed && isNodeShadowHost(event.target) && typeof event.composedPath === 'function') {
const composedPath = event.composedPath()
if (composedPath.length > 0 && composedPath[0] instanceof Element) {
return composedPath[0]
}
}
return event.target
}
const enum ClickStatus {
// Initial state, the click is still ongoing.
ONGOING,
// The click is no more ongoing but still needs to be validated or discarded.
STOPPED,
// Final state, the click has been stopped and validated or discarded.
FINALIZED,
}
export type Click = ReturnType<typeof newClick>
function newClick(
lifeCycle: LifeCycle,
history: ClickActionIdHistory,
getUserActivity: () => UserActivity,
clickActionBase: ClickActionBase,
startEvent: MouseEventOnElement
) {
const id = generateUUID()
const startClocks = relativeToClocks(startEvent.timeStamp)
const historyEntry = history.add(id, startClocks.relative)
const eventCountsSubscription = trackEventCounts({
lifeCycle,
isChildEvent: (event) =>
event.action !== undefined &&
(Array.isArray(event.action.id) ? event.action.id.includes(id) : event.action.id === id),
})
let status = ClickStatus.ONGOING
let activityEndTime: undefined | TimeStamp
const frustrationTypes: FrustrationType[] = []
const stopObservable = new Observable<void>()
function stop(newActivityEndTime?: TimeStamp) {
if (status !== ClickStatus.ONGOING) {
return
}
activityEndTime = newActivityEndTime
status = ClickStatus.STOPPED
if (activityEndTime) {
historyEntry.close(getRelativeTime(activityEndTime))
} else {
historyEntry.remove()
}
eventCountsSubscription.stop()
stopObservable.notify()
}
return {
event: startEvent,
stop,
stopObservable,
get hasError() {
return eventCountsSubscription.eventCounts.errorCount > 0
},
get hasPageActivity() {
return activityEndTime !== undefined
},
getUserActivity,
addFrustration: (frustrationType: FrustrationType) => {
frustrationTypes.push(frustrationType)
},
startClocks,
isStopped: () => status === ClickStatus.STOPPED || status === ClickStatus.FINALIZED,
clone: () => newClick(lifeCycle, history, getUserActivity, clickActionBase, startEvent),
validate: (domEvents?: Event[]) => {
stop()
if (status !== ClickStatus.STOPPED) {
return
}
const { resourceCount, errorCount, longTaskCount } = eventCountsSubscription.eventCounts
const clickAction: ClickAction = {
duration: activityEndTime && elapsed(startClocks.timeStamp, activityEndTime),
startClocks,
id,
frustrationTypes,
counts: {
resourceCount,
errorCount,
longTaskCount,
},
events: domEvents ?? [startEvent],
event: startEvent,
...clickActionBase,
}
lifeCycle.notify(LifeCycleEventType.AUTO_ACTION_COMPLETED, clickAction)
status = ClickStatus.FINALIZED
},
discard: () => {
stop()
status = ClickStatus.FINALIZED
},
}
}
export function finalizeClicks(clicks: Click[], rageClick: Click) {
const { isRage } = computeFrustration(clicks, rageClick)
if (isRage) {
clicks.forEach((click) => click.discard())
rageClick.stop(timeStampNow())
rageClick.validate(clicks.map((click) => click.event))
} else {
rageClick.discard()
clicks.forEach((click) => click.validate())
}
}