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