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
|
- /* eslint-disable camelcase */
- import { v4 as uuidv4 } from 'uuid'
- import Cookies from 'js-cookie'
- import getCsrf from './get-csrf'
- import parseUserAgent from './user-agent'
- const COOKIE_NAME = '_docs-events'
- const startVisitTime = Date.now()
- let cookieValue: string | undefined
- let pageEventId: string | undefined
- let maxScrollY = 0
- let pauseScrolling = false
- let sentExit = false
- export function getUserEventsId() {
- if (cookieValue) return cookieValue
- cookieValue = Cookies.get(COOKIE_NAME)
- if (cookieValue) return cookieValue
- cookieValue = uuidv4()
- Cookies.set(COOKIE_NAME, cookieValue, {
- secure: true,
- sameSite: 'strict',
- expires: 365,
- })
- return cookieValue
- }
- export enum EventType {
- page = 'page',
- exit = 'exit',
- link = 'link',
- search = 'search',
- navigate = 'navigate',
- survey = 'survey',
- experiment = 'experiment',
- preference = 'preference',
- clipboard = 'clipboard',
- print = 'print',
- }
- type SendEventProps = {
- type: EventType
- version?: string
- exit_render_duration?: number
- exit_first_paint?: number
- exit_dom_interactive?: number
- exit_dom_complete?: number
- exit_visit_duration?: number
- exit_scroll_length?: number
- link_url?: string
- search_query?: string
- search_context?: string
- navigate_label?: string
- survey_token?: string // Honeypot, doesn't exist in schema
- survey_vote?: boolean
- survey_comment?: string
- survey_email?: string
- experiment_name?: string
- experiment_variation?: string
- experiment_success?: boolean
- clipboard_operation?: string
- preference_name?: string
- preference_value?: string
- }
- export function sendEvent({ type, version = '1.0.0', ...props }: SendEventProps) {
- const body = {
- _csrf: getCsrf(),
- type,
- context: {
- // Primitives
- event_id: uuidv4(),
- user: getUserEventsId(),
- version,
- created: new Date().toISOString(),
- page_event_id: pageEventId,
- // Content information
- path: location.pathname,
- hostname: location.hostname,
- referrer: document.referrer,
- search: location.search,
- href: location.href,
- site_language: location.pathname.split('/')[1],
- // Device information
- // os, os_version, browser, browser_version:
- ...parseUserAgent(),
- viewport_width: document.documentElement.clientWidth,
- viewport_height: document.documentElement.clientHeight,
- // Location information
- timezone: new Date().getTimezoneOffset() / -60,
- user_language: navigator.language,
- // Preference information
- application_preference: Cookies.get('toolPreferred'),
- },
- ...props,
- }
- const blob = new Blob([JSON.stringify(body)], { type: 'application/json' })
- navigator.sendBeacon('/events', blob)
- return body
- }
- function getPerformance() {
- const paint = performance
- ?.getEntriesByType('paint')
- ?.find(({ name }) => name === 'first-contentful-paint')
- const nav = performance?.getEntriesByType('navigation')?.[0] as
- | PerformanceNavigationTiming
- | undefined
- return {
- firstContentfulPaint: paint ? paint.startTime / 1000 : undefined,
- domInteractive: nav ? nav.domInteractive / 1000 : undefined,
- domComplete: nav ? nav.domComplete / 1000 : undefined,
- render: nav ? (nav.responseEnd - nav.requestStart) / 1000 : undefined,
- }
- }
- function trackScroll() {
- // Throttle the calculations to no more than five per second
- if (pauseScrolling) return
- pauseScrolling = true
- setTimeout(() => {
- pauseScrolling = false
- }, 200)
- // Update maximum scroll position reached
- const scrollPixels = window.scrollY + window.innerHeight
- const scrollPosition = scrollPixels / document.documentElement.scrollHeight
- if (scrollPosition > maxScrollY) maxScrollY = scrollPosition
- }
- function sendExit() {
- if (sentExit) return
- if (document.visibilityState !== 'hidden') return
- sentExit = true
- const { render, firstContentfulPaint, domInteractive, domComplete } = getPerformance()
- return sendEvent({
- type: EventType.exit,
- exit_render_duration: render,
- exit_first_paint: firstContentfulPaint,
- exit_dom_interactive: domInteractive,
- exit_dom_complete: domComplete,
- exit_visit_duration: (Date.now() - startVisitTime) / 1000,
- exit_scroll_length: maxScrollY,
- })
- }
- function initPageEvent() {
- const pageEvent = sendEvent({ type: EventType.page })
- pageEventId = pageEvent?.context?.event_id
- }
- function initClipboardEvent() {
- ;['copy', 'cut', 'paste'].forEach((verb) => {
- document.documentElement.addEventListener(verb, () => {
- sendEvent({ type: EventType.clipboard, clipboard_operation: verb })
- })
- })
- }
- function initLinkEvent() {
- document.documentElement.addEventListener('click', (evt) => {
- const target = evt.target as HTMLElement
- const link = target.closest('a[href^="http"]') as HTMLAnchorElement
- if (!link) return
- sendEvent({
- type: EventType.link,
- link_url: link.href,
- })
- })
- }
- function initExitEvent() {
- window.addEventListener('scroll', trackScroll)
- document.addEventListener('visibilitychange', sendExit)
- }
- function initNavigateEvent() {
- if (!document.querySelector('.sidebar-products')) return
- Array.from(document.querySelectorAll('.sidebar-products details')).forEach((details) =>
- details.addEventListener('toggle', (evt) => {
- const target = evt.target as HTMLDetailsElement
- sendEvent({
- type: EventType.navigate,
- navigate_label: `details ${target.open ? 'open' : 'close'}: ${
- target?.querySelector('summary')?.innerText
- }`,
- })
- })
- )
- document.querySelector('.sidebar-products')?.addEventListener('click', (evt) => {
- const target = evt.target as HTMLElement
- const link = target.closest('a') as HTMLAnchorElement
- if (!link) return
- sendEvent({
- type: EventType.navigate,
- navigate_label: `link: ${link.href}`,
- })
- })
- }
- export default function initializeEvents() {
- initPageEvent() // must come first
- initExitEvent()
- initLinkEvent()
- initClipboardEvent()
- initNavigateEvent()
- // print event in ./print.js
- // survey event in ./survey.js
- // experiment event in ./experiment.js
- // search event in ./search.js
- // redirect event in middleware/record-redirect.js
- // preference event in ./display-tool-specific-content.js
- }
|