Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

events.ts 6.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. /* eslint-disable camelcase */
  2. import { v4 as uuidv4 } from 'uuid'
  3. import Cookies from 'js-cookie'
  4. import getCsrf from './get-csrf'
  5. import parseUserAgent from './user-agent'
  6. const COOKIE_NAME = '_docs-events'
  7. const startVisitTime = Date.now()
  8. let cookieValue: string | undefined
  9. let pageEventId: string | undefined
  10. let maxScrollY = 0
  11. let pauseScrolling = false
  12. let sentExit = false
  13. export function getUserEventsId() {
  14. if (cookieValue) return cookieValue
  15. cookieValue = Cookies.get(COOKIE_NAME)
  16. if (cookieValue) return cookieValue
  17. cookieValue = uuidv4()
  18. Cookies.set(COOKIE_NAME, cookieValue, {
  19. secure: true,
  20. sameSite: 'strict',
  21. expires: 365,
  22. })
  23. return cookieValue
  24. }
  25. export enum EventType {
  26. page = 'page',
  27. exit = 'exit',
  28. link = 'link',
  29. search = 'search',
  30. navigate = 'navigate',
  31. survey = 'survey',
  32. experiment = 'experiment',
  33. preference = 'preference',
  34. clipboard = 'clipboard',
  35. print = 'print',
  36. }
  37. type SendEventProps = {
  38. type: EventType
  39. version?: string
  40. exit_render_duration?: number
  41. exit_first_paint?: number
  42. exit_dom_interactive?: number
  43. exit_dom_complete?: number
  44. exit_visit_duration?: number
  45. exit_scroll_length?: number
  46. link_url?: string
  47. search_query?: string
  48. search_context?: string
  49. navigate_label?: string
  50. survey_token?: string // Honeypot, doesn't exist in schema
  51. survey_vote?: boolean
  52. survey_comment?: string
  53. survey_email?: string
  54. experiment_name?: string
  55. experiment_variation?: string
  56. experiment_success?: boolean
  57. clipboard_operation?: string
  58. preference_name?: string
  59. preference_value?: string
  60. }
  61. export function sendEvent({ type, version = '1.0.0', ...props }: SendEventProps) {
  62. const body = {
  63. _csrf: getCsrf(),
  64. type,
  65. context: {
  66. // Primitives
  67. event_id: uuidv4(),
  68. user: getUserEventsId(),
  69. version,
  70. created: new Date().toISOString(),
  71. page_event_id: pageEventId,
  72. // Content information
  73. path: location.pathname,
  74. hostname: location.hostname,
  75. referrer: document.referrer,
  76. search: location.search,
  77. href: location.href,
  78. site_language: location.pathname.split('/')[1],
  79. // Device information
  80. // os, os_version, browser, browser_version:
  81. ...parseUserAgent(),
  82. viewport_width: document.documentElement.clientWidth,
  83. viewport_height: document.documentElement.clientHeight,
  84. // Location information
  85. timezone: new Date().getTimezoneOffset() / -60,
  86. user_language: navigator.language,
  87. // Preference information
  88. application_preference: Cookies.get('toolPreferred'),
  89. },
  90. ...props,
  91. }
  92. const blob = new Blob([JSON.stringify(body)], { type: 'application/json' })
  93. navigator.sendBeacon('/events', blob)
  94. return body
  95. }
  96. function getPerformance() {
  97. const paint = performance
  98. ?.getEntriesByType('paint')
  99. ?.find(({ name }) => name === 'first-contentful-paint')
  100. const nav = performance?.getEntriesByType('navigation')?.[0] as
  101. | PerformanceNavigationTiming
  102. | undefined
  103. return {
  104. firstContentfulPaint: paint ? paint.startTime / 1000 : undefined,
  105. domInteractive: nav ? nav.domInteractive / 1000 : undefined,
  106. domComplete: nav ? nav.domComplete / 1000 : undefined,
  107. render: nav ? (nav.responseEnd - nav.requestStart) / 1000 : undefined,
  108. }
  109. }
  110. function trackScroll() {
  111. // Throttle the calculations to no more than five per second
  112. if (pauseScrolling) return
  113. pauseScrolling = true
  114. setTimeout(() => {
  115. pauseScrolling = false
  116. }, 200)
  117. // Update maximum scroll position reached
  118. const scrollPixels = window.scrollY + window.innerHeight
  119. const scrollPosition = scrollPixels / document.documentElement.scrollHeight
  120. if (scrollPosition > maxScrollY) maxScrollY = scrollPosition
  121. }
  122. function sendExit() {
  123. if (sentExit) return
  124. if (document.visibilityState !== 'hidden') return
  125. sentExit = true
  126. const { render, firstContentfulPaint, domInteractive, domComplete } = getPerformance()
  127. return sendEvent({
  128. type: EventType.exit,
  129. exit_render_duration: render,
  130. exit_first_paint: firstContentfulPaint,
  131. exit_dom_interactive: domInteractive,
  132. exit_dom_complete: domComplete,
  133. exit_visit_duration: (Date.now() - startVisitTime) / 1000,
  134. exit_scroll_length: maxScrollY,
  135. })
  136. }
  137. function initPageEvent() {
  138. const pageEvent = sendEvent({ type: EventType.page })
  139. pageEventId = pageEvent?.context?.event_id
  140. }
  141. function initClipboardEvent() {
  142. ;['copy', 'cut', 'paste'].forEach((verb) => {
  143. document.documentElement.addEventListener(verb, () => {
  144. sendEvent({ type: EventType.clipboard, clipboard_operation: verb })
  145. })
  146. })
  147. }
  148. function initLinkEvent() {
  149. document.documentElement.addEventListener('click', (evt) => {
  150. const target = evt.target as HTMLElement
  151. const link = target.closest('a[href^="http"]') as HTMLAnchorElement
  152. if (!link) return
  153. sendEvent({
  154. type: EventType.link,
  155. link_url: link.href,
  156. })
  157. })
  158. }
  159. function initExitEvent() {
  160. window.addEventListener('scroll', trackScroll)
  161. document.addEventListener('visibilitychange', sendExit)
  162. }
  163. function initNavigateEvent() {
  164. if (!document.querySelector('.sidebar-products')) return
  165. Array.from(document.querySelectorAll('.sidebar-products details')).forEach((details) =>
  166. details.addEventListener('toggle', (evt) => {
  167. const target = evt.target as HTMLDetailsElement
  168. sendEvent({
  169. type: EventType.navigate,
  170. navigate_label: `details ${target.open ? 'open' : 'close'}: ${
  171. target?.querySelector('summary')?.innerText
  172. }`,
  173. })
  174. })
  175. )
  176. document.querySelector('.sidebar-products')?.addEventListener('click', (evt) => {
  177. const target = evt.target as HTMLElement
  178. const link = target.closest('a') as HTMLAnchorElement
  179. if (!link) return
  180. sendEvent({
  181. type: EventType.navigate,
  182. navigate_label: `link: ${link.href}`,
  183. })
  184. })
  185. }
  186. export default function initializeEvents() {
  187. initPageEvent() // must come first
  188. initExitEvent()
  189. initLinkEvent()
  190. initClipboardEvent()
  191. initNavigateEvent()
  192. // print event in ./print.js
  193. // survey event in ./survey.js
  194. // experiment event in ./experiment.js
  195. // search event in ./search.js
  196. // redirect event in middleware/record-redirect.js
  197. // preference event in ./display-tool-specific-content.js
  198. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...