docs/.vitepress/theme/internal/browser.ts
180 lines · 4621 bytes
1import type {
2 InternalOptions as InternalBaseOptions,
3 TrackProperties
4} from './api'
5import { InternalAPI as InternalBase } from './api'
6
7export type InternalOptions = InternalBaseOptions & {
8 trackOutgoingLinks?: boolean
9 trackScreenViews?: boolean
10 trackAttributes?: boolean
11 trackHashChanges?: boolean
12}
13
14function toCamelCase(str: string) {
15 return str.replace(/([-_][a-z])/gi, ($1) =>
16 $1.toUpperCase().replace('-', '').replace('_', '')
17 )
18}
19
20export class Internal extends InternalBase {
21 private lastPath = ''
22 private debounceTimer: any
23
24 constructor(public options: InternalOptions) {
25 super({
26 sdk: 'web',
27 sdkVersion: process.env.WEB_VERSION!,
28 ...options
29 })
30
31 if (!this.isServer()) {
32 this.setGlobalProperties({
33 __referrer: document.referrer
34 })
35
36 if (this.options.trackScreenViews) {
37 this.trackScreenViews()
38 setTimeout(() => this.screenView(), 0)
39 }
40
41 if (this.options.trackOutgoingLinks) {
42 this.trackOutgoingLinks()
43 }
44
45 if (this.options.trackAttributes) {
46 this.trackAttributes()
47 }
48 }
49 }
50
51 private debounce(func: () => void, delay: number) {
52 clearTimeout(this.debounceTimer)
53 this.debounceTimer = setTimeout(func, delay)
54 }
55
56 private isServer() {
57 return typeof document === 'undefined'
58 }
59
60 public trackOutgoingLinks() {
61 if (this.isServer()) {
62 return
63 }
64
65 document.addEventListener('click', (event) => {
66 const target = event.target as HTMLElement
67 const link = target.closest('a')
68 if (link && target) {
69 const href = link.getAttribute('href')
70 if (href?.startsWith('http')) {
71 super.track('link_out', {
72 href,
73 text:
74 link.innerText ||
75 link.getAttribute('title') ||
76 target.getAttribute('alt') ||
77 target.getAttribute('title')
78 })
79 }
80 }
81 })
82 }
83
84 public trackScreenViews() {
85 if (this.isServer()) {
86 return
87 }
88
89 const oldPushState = history.pushState
90 history.pushState = function pushState(...args) {
91 const ret = oldPushState.apply(this, args)
92 window.dispatchEvent(new Event('pushstate'))
93 window.dispatchEvent(new Event('locationchange'))
94 return ret
95 }
96
97 const oldReplaceState = history.replaceState
98 history.replaceState = function replaceState(...args) {
99 const ret = oldReplaceState.apply(this, args)
100 window.dispatchEvent(new Event('replacestate'))
101 window.dispatchEvent(new Event('locationchange'))
102 return ret
103 }
104
105 window.addEventListener('popstate', () => {
106 window.dispatchEvent(new Event('locationchange'))
107 })
108
109 const eventHandler = () => this.debounce(() => this.screenView(), 50)
110
111 if (this.options.trackHashChanges) {
112 window.addEventListener('hashchange', eventHandler)
113 } else {
114 window.addEventListener('locationchange', eventHandler)
115 }
116 }
117
118 public trackAttributes() {
119 if (this.isServer()) {
120 return
121 }
122
123 document.addEventListener('click', (event) => {
124 const target = event.target as HTMLElement
125 const btn = target.closest('button')
126 const anchor = target.closest('a')
127 const element = btn?.getAttribute('data-track')
128 ? btn
129 : anchor?.getAttribute('data-track')
130 ? anchor
131 : null
132 if (element) {
133 const properties: Record<string, unknown> = {}
134 for (const attr of Array.from(element.attributes)) {
135 if (attr.name.startsWith('data-') && attr.name !== 'data-track') {
136 properties[toCamelCase(attr.name.replace(/^data-/, ''))] =
137 attr.value
138 }
139 }
140 const name = element.getAttribute('data-track')
141 if (name) {
142 super.track(name, properties)
143 }
144 }
145 })
146 }
147
148 screenView(properties?: TrackProperties): void
149 screenView(path: string, properties?: TrackProperties): void
150 screenView(
151 pathOrProperties?: string | TrackProperties,
152 propertiesOrUndefined?: TrackProperties
153 ): void {
154 if (this.isServer()) {
155 return
156 }
157
158 let path: string
159 let properties: TrackProperties | undefined
160
161 if (typeof pathOrProperties === 'string') {
162 path = pathOrProperties
163 properties = propertiesOrUndefined
164 } else {
165 path = window.location.href
166 properties = pathOrProperties
167 }
168
169 if (this.lastPath === path) {
170 return
171 }
172
173 this.lastPath = path
174 super.track('screen_view', {
175 ...(properties ?? {}),
176 __path: path,
177 __title: document.title
178 })
179 }
180}