-
-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathanalytics.ts
More file actions
235 lines (198 loc) · 5.45 KB
/
Copy pathanalytics.ts
File metadata and controls
235 lines (198 loc) · 5.45 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
import * as React from 'react'
import { googleAnalyticsProvider } from './analytics/providers/google'
import type {
AnalyticsEventName,
AnalyticsEventProps,
} from './analytics/events'
import type { AnalyticsPropertyValue, EventPayload } from './analytics/types'
export type {
AnalyticsEvent,
AnalyticsEventName,
AnalyticsEventProps,
BuilderAction,
BuilderFailureStage,
BuilderMode,
BuilderSessionContext,
BuilderSurface,
PartnerClickDestination,
PartnerFilterChange,
PartnerPlacement,
} from './analytics/events'
export { defaultBuilderSessionContext } from './analytics/events'
interface ImpressionOptions<TName extends AnalyticsEventName> {
enabled?: boolean
event: TName
props: AnalyticsEventProps<TName>
threshold?: number
}
function getPageType(pathname: string) {
if (pathname === '/') {
return 'home'
}
if (pathname.startsWith('/partners/')) {
return pathname === '/partners/' || pathname === '/partners'
? 'partners_index'
: 'partner_detail'
}
if (pathname.startsWith('/blog/')) {
return pathname === '/blog/' || pathname === '/blog'
? 'blog_index'
: 'blog_post'
}
if (pathname.startsWith('/docs/') || pathname.includes('/docs/')) {
return 'docs'
}
if (pathname.startsWith('/partners-embed')) {
return 'partners_embed'
}
if (
pathname === '/builder' ||
pathname === '/builder/' ||
pathname.startsWith('/builder/')
) {
return 'application_builder'
}
return 'page'
}
function normalizeAnalyticsValue(
value: unknown,
): AnalyticsPropertyValue | undefined {
if (
typeof value === 'boolean' ||
typeof value === 'number' ||
typeof value === 'string'
) {
return value
}
if (value === null || value === undefined) {
return undefined
}
if (Array.isArray(value)) {
const normalizedEntries = value
.map((entry) => normalizeAnalyticsValue(entry))
.filter((entry) => entry !== undefined)
return normalizedEntries.join(',')
}
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}
// Accepts any object — call sites pass typed event props which carry
// specific keys. We just iterate string-keyed values, so an exact shape
// isn't needed.
function buildEventPayload(props: object): EventPayload {
const payload: EventPayload = {}
if (typeof window !== 'undefined') {
payload.page_location = window.location.href
payload.page_path = window.location.pathname
payload.page_title = document.title
payload.page_type = getPageType(window.location.pathname)
}
for (const [key, value] of Object.entries(props)) {
const normalized = normalizeAnalyticsValue(value)
if (normalized === undefined) {
continue
}
payload[key] = normalized
}
return payload
}
const analyticsProviders = [googleAnalyticsProvider]
/**
* Track an analytics event. Type-safe — the event name determines which
* properties are required. See `.agents/analytics.md` for what each event
* means in the user flow.
*
* @example
* trackEvent('partner_clicked', {
* partner_id: 'vercel',
* placement: 'directory',
* destination: 'internal_detail',
* })
*/
export function trackEvent<TName extends AnalyticsEventName>(
name: TName,
props: AnalyticsEventProps<TName>,
): void {
const payload = buildEventPayload(props)
for (const provider of analyticsProviders) {
try {
provider.trackEvent(name, payload)
} catch {
// Analytics failures should never affect user flows.
}
}
}
/**
* Track an SPA page view. Called from the root route on navigation.
*/
export function trackPageView(pagePath: string) {
trackEvent('page_view', {
page_location: window.location.href,
page_path: pagePath,
page_title: document.title,
})
}
/**
* Fire a typed event when an element scrolls into view. Fires once per
* element-mount per session (the IntersectionObserver disconnects after
* the first crossing of the threshold).
*
* Note on behavior: when the host element unmounts and remounts (e.g.
* because of a parent's filter change), the impression re-fires. Dedup
* in BigQuery if you need session-unique impression counts.
*/
export function useTrackedImpression<
TName extends AnalyticsEventName,
TElement extends Element = Element,
>({ enabled = true, event, props, threshold = 0.5 }: ImpressionOptions<TName>) {
const ref = React.useRef<TElement | null>(null)
const hasTrackedRef = React.useRef(false)
const propsRef = React.useRef(props)
React.useEffect(() => {
propsRef.current = props
}, [props])
React.useEffect(() => {
if (!enabled || hasTrackedRef.current) {
return
}
const element = ref.current
if (!element) {
return
}
const track = () => {
if (hasTrackedRef.current) {
return
}
hasTrackedRef.current = true
trackEvent(event, propsRef.current)
}
if (typeof IntersectionObserver === 'undefined') {
track()
return
}
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) {
continue
}
if (entry.intersectionRatio < threshold) {
continue
}
track()
observer.disconnect()
return
}
},
{ threshold: [threshold] },
)
observer.observe(element)
return () => {
observer.disconnect()
}
}, [enabled, event, threshold])
return ref
}