Skip to content

Commit ae3bdbe

Browse files
committed
Implement code changes to enhance functionality and improve performance
1 parent 7e0d4b1 commit ae3bdbe

5 files changed

Lines changed: 7233 additions & 3262 deletions

File tree

.vitepress/theme/Analytics.vue

Lines changed: 76 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,50 @@
11
<script setup>
22
import { onMounted, onUnmounted, watch } from 'vue'
33
import { useRoute, useData } from 'vitepress'
4-
import { pageView, trackLinkClick } from './analytics'
4+
import { pageView, trackLinkClick, inHouseAnalytics } from './analytics'
55
66
const route = useRoute()
77
const { page } = useData()
88
99
// Track page view on initial load
1010
onMounted(() => {
11-
pageView(window.location.href)
11+
// Force immediate page view tracking
12+
trackPageView()
13+
14+
// Set up event listeners for interaction tracking
1215
addLinkClickListeners()
16+
addButtonClickListeners()
1317
addScrollTracking()
18+
19+
// Log successful initialization
20+
console.log('Analytics tracking initialized')
1421
})
1522
23+
function trackPageView() {
24+
// Track the page view with current URL and referrer
25+
inHouseAnalytics('pageView', {
26+
url: window.location.href,
27+
path: route.path,
28+
referrer: document.referrer
29+
})
30+
}
31+
1632
// Track page views on route changes
17-
watch(() => route.path, (newPath) => {
18-
setTimeout(() => {
19-
// Small delay to ensure URL is updated in browser
20-
pageView(window.location.href)
21-
}, 100)
33+
// This is the VitePress-compatible way to track route changes
34+
watch(() => route.path, (newPath, oldPath) => {
35+
if (newPath !== oldPath) {
36+
console.log(`Route changed: ${oldPath} -> ${newPath}`)
37+
setTimeout(() => {
38+
// Track page view after route change
39+
trackPageView()
40+
}, 100)
41+
}
2242
})
2343
2444
// Clean up event listeners
2545
onUnmounted(() => {
2646
removeLinkClickListeners()
47+
removeButtonClickListeners()
2748
removeScrollTracking()
2849
})
2950
@@ -39,7 +60,34 @@ function removeLinkClickListeners() {
3960
function handleLinkClick(event) {
4061
const link = event.target.closest('a')
4162
if (link && link.href) {
42-
trackLinkClick(link.href)
63+
// Track all link clicks with href, target, and referrer
64+
inHouseAnalytics('linkClick', {
65+
url: link.href,
66+
text: link.innerText || link.textContent,
67+
referrer: document.referrer || window.location.href
68+
})
69+
}
70+
}
71+
72+
// Track button clicks
73+
function addButtonClickListeners() {
74+
document.addEventListener('click', handleButtonClick)
75+
}
76+
77+
function removeButtonClickListeners() {
78+
document.removeEventListener('click', handleButtonClick)
79+
}
80+
81+
function handleButtonClick(event) {
82+
const button = event.target.closest('button')
83+
if (button) {
84+
// Track all button clicks
85+
inHouseAnalytics('buttonClick', {
86+
text: button.innerText || button.textContent,
87+
id: button.id,
88+
class: button.className,
89+
referrer: document.referrer || window.location.href
90+
})
4391
}
4492
}
4593
@@ -77,19 +125,35 @@ class ScrollDepthTracker {
77125
78126
if (scrollPercent >= 25 && !this.tracked['25']) {
79127
this.tracked['25'] = true
80-
pageView(`${window.location.href}#scroll-25%`)
128+
inHouseAnalytics('scroll', {
129+
depth: '25%',
130+
url: window.location.href,
131+
referrer: document.referrer
132+
})
81133
}
82134
if (scrollPercent >= 50 && !this.tracked['50']) {
83135
this.tracked['50'] = true
84-
pageView(`${window.location.href}#scroll-50%`)
136+
inHouseAnalytics('scroll', {
137+
depth: '50%',
138+
url: window.location.href,
139+
referrer: document.referrer
140+
})
85141
}
86142
if (scrollPercent >= 75 && !this.tracked['75']) {
87143
this.tracked['75'] = true
88-
pageView(`${window.location.href}#scroll-75%`)
144+
inHouseAnalytics('scroll', {
145+
depth: '75%',
146+
url: window.location.href,
147+
referrer: document.referrer
148+
})
89149
}
90150
if (scrollPercent >= 99 && !this.tracked['100']) {
91151
this.tracked['100'] = true
92-
pageView(`${window.location.href}#scroll-100%`)
152+
inHouseAnalytics('scroll', {
153+
depth: '100%',
154+
url: window.location.href,
155+
referrer: document.referrer
156+
})
93157
}
94158
}
95159

.vitepress/theme/analytics.ts

Lines changed: 81 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,28 +13,33 @@ const isBrowser = (): boolean => {
1313
};
1414

1515
export function inHouseAnalytics(event: string, eventRef: Dict) {
16-
if (!isBrowser()) return;
17-
// if localhost, return
18-
if (window.location.hostname === "localhost") return;
16+
if (!isBrowser()) {
17+
console.log('Analytics not sent: Not in browser environment');
18+
return;
19+
}
20+
21+
// Debug logs (remove in production)
22+
// console.log(`Analytics event: ${event}`, eventRef);
1923

24+
// Skip tracking on localhost unless in debug mode
25+
const isLocalhost = window.location.hostname === "localhost";
26+
if (isLocalhost) {
27+
return;
28+
}
29+
event = "docs_"+event
2030
const cId = localStorage.getItem("cId");
21-
let email = localStorage.getItem("aId");
22-
// capture all query params in eventRef
23-
const queryParams = new URLSearchParams(window.location.search);
24-
queryParams.forEach((value, key) => {
25-
if (key !== "oid" && key !== "ot" && key !== "eid") {
26-
eventRef[key] = value;
27-
}
28-
});
31+
let email = localStorage.getItem("email");
2932

3033
if(!email) {
3134
// Generate a unique anonymous ID if email doesn't exist
32-
let anonymousId = localStorage.getItem("aId");
35+
let anonymousId = getQueryParameter("aId") || localStorage.getItem("aId");
36+
3337
if (!anonymousId) {
3438
// Create unique ID combining timestamp and random string
3539
anonymousId = `an_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`;
36-
localStorage.setItem("aId", anonymousId);
40+
// localStorage.setItem("aId", anonymousId);
3741
}
42+
localStorage.setItem("aId", anonymousId);
3843
email = anonymousId; // Use this as the identifier instead of email
3944
}
4045

@@ -53,51 +58,103 @@ export function inHouseAnalytics(event: string, eventRef: Dict) {
5358
url: isBrowser() ? window.location.href : '',
5459
referrer: isBrowser() ? document.referrer : '',
5560
eId: eId,
61+
timestamp: new Date().toISOString(),
62+
userAgent: navigator.userAgent
5663
}),
5764
};
5865

5966
try {
60-
// axiosInstance.post("v1/analytics/track", data);
67+
console.log('Sending analytics data:', data);
68+
6169
fetch("https://production-gateway.snorkell.ai/api/v1/analytics/track", {
6270
method: 'POST',
6371
headers: {
6472
'Content-Type': 'application/json'
6573
},
6674
body: JSON.stringify(data),
75+
// Add these options for better cross-origin support
76+
mode: 'cors',
77+
credentials: 'omit'
6778
})
6879
.then(response => {
69-
// Handle response if needed
80+
console.log('Analytics response status:', response.status);
81+
if (!response.ok) {
82+
console.error('Analytics API error:', response.status);
83+
}
84+
return response.text();
85+
})
86+
.then(text => {
87+
if (text) {
88+
try {
89+
const json = JSON.parse(text);
90+
console.log('Analytics API response:', json);
91+
} catch (e) {
92+
console.log('Analytics API response (text):', text);
93+
}
94+
}
7095
})
7196
.catch(error => {
72-
console.log(error);
97+
console.error('Analytics fetch error:', error);
7398
});
7499
} catch (error) {
75-
console.log(error);
100+
console.error('Analytics error:', error);
76101
}
77102
}
78103

79104
export const pageView = (url: string) => {
80-
inHouseAnalytics("pageView_docs", {url});
105+
inHouseAnalytics("pageView", {url});
81106
};
82107

83108
export const getQueryParameter = (name: string) => {
84-
if (!isBrowser()){console.log("server side rendering"); return null};
109+
if (!isBrowser()){
110+
console.log("Server side rendering - can't access URL parameters");
111+
return null
112+
};
85113
const urlParams = new URLSearchParams(window.location.search);
86114
return urlParams.get(name);
87115
};
88116

89117
export const trackLinkClick = (url: string, email: string = "", cId: string = "") => {
90-
inHouseAnalytics("linkClick_docs",{ url, email, cId, home_url: window.location.href });
118+
inHouseAnalytics("linkClick", {
119+
url,
120+
referrer: document.referrer || window.location.href
121+
});
91122
};
92123

93124
export const trackScroll = (value: number) => {
94-
inHouseAnalytics("scroll_docs", {event:"scrolled 50% on homepage", home_url: window.location.href});
125+
inHouseAnalytics("scroll", {
126+
depth: `${value}%`,
127+
url: window.location.href
128+
});
95129
};
96130

97131
export const trackFormSubmission = (value: [string]) => {
98-
inHouseAnalytics("formSubmission_docs", {event:"contact us form submission", home_url: window.location.href});
132+
inHouseAnalytics("formSubmission", {
133+
event: "contact us form submission",
134+
formData: value
135+
});
99136
};
100137

101138
export const trackVideoStart = (value: boolean) => {
102-
inHouseAnalytics("videoView_docs", {event:"Penify.dev video tuts", home_url: window.location.href});
103-
};
139+
inHouseAnalytics("videoView", {
140+
event: "Penify.dev video tuts",
141+
play: value
142+
});
143+
};
144+
145+
// Enable debug mode for localhost testing
146+
export const enableAnalyticsDebug = () => {
147+
if (isBrowser()) {
148+
sessionStorage.setItem('analytics_debug', 'true');
149+
console.log('Analytics debug mode enabled');
150+
}
151+
};
152+
153+
// Initialize analytics on page load
154+
if (isBrowser()) {
155+
// Auto-initialize
156+
window.addEventListener('load', () => {
157+
console.log('Analytics initialized on page load');
158+
pageView(window.location.href);
159+
});
160+
}

.vitepress/theme/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,20 @@ import ShareButtons from './ShareButtons.vue'
44
import Layout from './Layout.vue'
55
import EmailSignup from './EmailSignup.vue'
66
import Comments from './Comments.vue'
7+
import Analytics from './Analytics.vue'
78

9+
// Setup client-side only code
10+
const clientSetup = () => {
11+
if (typeof window !== 'undefined') {
12+
// Register analytics on client-side only
13+
import('./analytics').then(analytics => {
14+
const { pageView } = analytics;
15+
16+
// Track initial page view
17+
pageView(window.location.href);
18+
});
19+
}
20+
};
821

922
export default {
1023
extends: DefaultTheme,
@@ -13,5 +26,13 @@ export default {
1326
app.component('ShareButtons', ShareButtons)
1427
app.component('EmailSignup', EmailSignup)
1528
app.component('Comments', Comments)
29+
app.component('Analytics', Analytics)
30+
31+
// Call client setup function for initial analytics
32+
clientSetup();
33+
},
34+
setup() {
35+
// VitePress specific router handling is now moved to the Analytics component
36+
// The router.onAfterEach usage was causing an error
1637
}
1738
}

.yarn/install-state.gz

18.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)