-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
738 lines (618 loc) · 26 KB
/
script.js
File metadata and controls
738 lines (618 loc) · 26 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// Silicon Vault - Interactive Learning Platform
// Progress tracking, search, and accordion functionality
import { inject, track } from '@vercel/analytics';
class SiliconVault {
constructor() {
this.progress = this.loadProgress();
this.init();
}
init() {
try {
this.setupAccordion();
this.setupSearch();
this.setupProgressTracking();
this.setupThemeToggle();
this.setupPopup();
this.updateAllProgress();
this.setupSmoothScroll();
this.setupRoadmap();
this.updatePlacementYear();
this.setupVisitorStats();
// Initialize Vercel Analytics
inject();
} catch (error) {
console.error('Initialization error:', error);
}
}
// Accordion functionality
setupAccordion() {
const accordionBtns = document.querySelectorAll('.accordion-btn');
accordionBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
// Don't trigger if clicking checkbox
if (e.target.closest('.checkbox-container')) return;
const item = btn.closest('.accordion-item');
const content = item.querySelector('.accordion-content');
const icon = btn.querySelector('.fa-chevron-down');
// Toggle active state
const isActive = item.classList.contains('active');
if (isActive) {
// Close
item.classList.remove('active');
content.style.maxHeight = null;
icon.style.transform = "rotate(0deg)";
} else {
// Open
item.classList.add('active');
content.style.maxHeight = content.scrollHeight + "px";
icon.style.transform = "rotate(180deg)";
}
});
});
}
// Search functionality
setupSearch() {
const searchBox = document.getElementById('searchBox');
const items = document.querySelectorAll('.accordion-item');
const searchCount = document.getElementById('searchCount');
const totalQuestions = items.length;
searchBox.addEventListener('input', (e) => {
const term = e.target.value.toLowerCase().trim();
let visibleCount = 0;
items.forEach(item => {
const text = item.innerText.toLowerCase();
if (term === '' || text.includes(term)) {
item.style.display = "block";
visibleCount++;
} else {
item.style.display = "none";
}
});
// Track search event if term is long enough (avoid tracking every keystroke)
if (term.length > 3) {
// Throttle this in a real scenario, but for now:
track('Search', { query: term });
}
// Update search count
if (term === '') {
searchCount.textContent = '';
} else {
searchCount.textContent = `${visibleCount}/${totalQuestions}`;
}
// Show/hide category groups based on visible items
this.updateCategoryVisibility();
});
// Initial count display
searchCount.textContent = '';
}
updateCategoryVisibility() {
const categoryGroups = document.querySelectorAll('.category-group');
categoryGroups.forEach(group => {
const visibleItems = group.querySelectorAll('.accordion-item[style*="display: block"], .accordion-item:not([style*="display"])');
if (visibleItems.length === 0) {
group.style.display = 'none';
} else {
group.style.display = 'block';
}
});
}
// Progress tracking
setupProgressTracking() {
const checkboxes = document.querySelectorAll('.question-checkbox');
checkboxes.forEach(checkbox => {
const questionId = checkbox.closest('.accordion-item').dataset.id;
// Set initial state from saved progress
if (this.progress[questionId]) {
checkbox.checked = true;
}
// Listen for changes
checkbox.addEventListener('change', (e) => {
this.progress[questionId] = e.target.checked;
this.saveProgress();
this.updateAllProgress();
// Add celebration animation for completion
if (e.target.checked) {
this.celebrateCompletion(checkbox);
track('Progress_Complete', { itemId: questionId });
} else {
track('Progress_Incomplete', { itemId: questionId });
}
});
});
// Reset progress button
const resetBtn = document.getElementById('resetProgress');
resetBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to reset all progress? This cannot be undone.')) {
this.resetProgress();
}
});
}
celebrateCompletion(checkbox) {
const item = checkbox.closest('.accordion-item');
item.style.transition = 'transform 0.3s ease';
item.style.transform = 'scale(1.02)';
setTimeout(() => {
item.style.transform = 'scale(1)';
}, 300);
}
updateAllProgress() {
// Calculate overall progress
const totalQuestions = document.querySelectorAll('.question-checkbox').length;
const completedQuestions = Object.values(this.progress).filter(v => v).length;
const overallPercentage = totalQuestions > 0 ? Math.round((completedQuestions / totalQuestions) * 100) : 0;
// Update overall progress circle
this.updateProgressCircle(overallPercentage);
// Update category progress
const logicCount = document.querySelectorAll('#logic .accordion-item').length;
const archCount = document.querySelectorAll('#arch .accordion-item').length;
const pythonCount = document.querySelectorAll('[data-category="python"] .accordion-item, #coding .accordion-item').length;
const progCount = document.querySelectorAll('[data-category="programming"] .accordion-item').length;
this.updateCategoryProgress('logic', logicCount);
this.updateCategoryProgress('arch', archCount);
this.updateCategoryProgress('python', pythonCount);
this.updateCategoryProgress('programming', progCount);
}
updateProgressCircle(percentage) {
const circle = document.getElementById('overallProgressCircle');
const percentageText = document.getElementById('overallPercentage');
const circumference = 2 * Math.PI * 45; // radius = 45
const offset = circumference - (percentage / 100) * circumference;
circle.style.strokeDashoffset = offset;
percentageText.textContent = `${percentage}%`;
}
updateCategoryProgress(category, totalQuestions) {
const categoryGroup = document.querySelector(`[data-category="${category}"]`);
if (!categoryGroup) return;
const items = categoryGroup.querySelectorAll('.accordion-item');
const completed = Array.from(items).filter(item => {
const checkbox = item.querySelector('.question-checkbox');
return checkbox && checkbox.checked;
}).length;
const percentage = totalQuestions > 0 ? Math.round((completed / totalQuestions) * 100) : 0;
// Update progress bar
const progressBar = document.getElementById(`${category}Progress`);
if (progressBar) {
progressBar.style.width = `${percentage}%`;
}
// Update count
const countElement = document.getElementById(`${category}Count`);
if (countElement) {
countElement.textContent = `${completed}/${totalQuestions}`;
}
}
// Local storage management
loadProgress() {
const saved = localStorage.getItem('siliconVaultProgress');
return saved ? JSON.parse(saved) : {};
}
saveProgress() {
localStorage.setItem('siliconVaultProgress', JSON.stringify(this.progress));
}
resetProgress() {
this.progress = {};
this.saveProgress();
// Uncheck all checkboxes
document.querySelectorAll('.question-checkbox').forEach(checkbox => {
checkbox.checked = false;
});
this.updateAllProgress();
// Show confirmation
this.showNotification('Progress reset successfully!');
}
showNotification(message) {
// Create notification element
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
color: white;
padding: 15px 25px;
border-radius: 8px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
z-index: 10000;
font-weight: 600;
animation: slideIn 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Theme toggle (dark mode is default, could add light mode)
setupThemeToggle() {
const themeToggle = document.getElementById('themeToggle');
let isDark = true;
themeToggle.addEventListener('click', () => {
isDark = !isDark;
if (isDark) {
themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
// Dark mode is default, no changes needed
} else {
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
// Could implement light mode here
this.showNotification('Light mode coming soon! 🌞');
}
});
}
// Smooth scroll for navigation
setupSmoothScroll() {
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
const offset = 100; // Account for sticky nav
const targetPosition = target.offsetTop - offset;
window.scrollTo({
top: targetPosition,
behavior: 'smooth'
});
}
});
});
}
// Follow Me Popup
setupPopup() {
const popup = document.getElementById('followPopup');
const closeBtn = document.querySelector('.close-popup');
// Use sessionStorage so it shows once per browsing session (tab/window)
// If you want it on EVERY page load, remove the storage check entirely.
// Assuming "visiting website" means once per session to avoid checking it every refresh.
const hasSeenSession = sessionStorage.getItem('siliconVaultPopupSeen');
if (!hasSeenSession && popup) {
// Show after 2 seconds
setTimeout(() => {
popup.classList.add('show');
}, 2000);
}
if (popup && closeBtn) {
closeBtn.addEventListener('click', () => {
popup.classList.remove('show');
sessionStorage.setItem('siliconVaultPopupSeen', 'true');
});
// Close when clicking outside
popup.addEventListener('click', (e) => {
if (e.target === popup) {
popup.classList.remove('show');
sessionStorage.setItem('siliconVaultPopupSeen', 'true');
}
});
}
}
// Roadmap Interaction
setupRoadmap() {
const cards = document.querySelectorAll('.phase-card.interactive');
cards.forEach(card => {
card.addEventListener('click', (e) => {
// Prevent closing if clicking a link
if (e.target.tagName === 'A' || e.target.closest('a')) return;
const details = card.querySelector('.phase-details');
const icon = card.querySelector('.expand-icon');
const isActive = card.classList.contains('active');
// Close other cards for a clean look
cards.forEach(c => {
if (c !== card) {
c.classList.remove('active');
const otherDetails = c.querySelector('.phase-details');
if (otherDetails) otherDetails.style.maxHeight = null;
const otherIcon = c.querySelector('.expand-icon');
if (otherIcon) otherIcon.style.transform = "rotate(0deg)";
}
});
// Toggle current
if (isActive) {
card.classList.remove('active');
if (details) details.style.maxHeight = null;
if (icon) icon.style.transform = "rotate(0deg)";
} else {
card.classList.add('active');
if (details) details.style.maxHeight = details.scrollHeight + "px";
if (icon) icon.style.transform = "rotate(180deg)";
track('Roadmap_Expand', { phase: card.dataset.phase });
}
});
});
}
// Auto-update placement year
updatePlacementYear() {
const yearElement = document.getElementById('placement-year');
if (yearElement) {
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth(); // 0-11
// Placement season typically runs from July (month 6) to June
// If current month is July or after, show current-next year
// Otherwise show previous-current year
let placementYear;
if (currentMonth >= 6) {
placementYear = `${currentYear}-${currentYear + 1}`;
} else {
placementYear = `${currentYear - 1}-${currentYear}`;
}
yearElement.textContent = placementYear;
}
}
// Visitor Statistics
setupVisitorStats() {
const statsToggle = document.getElementById('visitorStatsToggle');
const statsDropdown = document.getElementById('visitorStatsDropdown');
const closeStats = document.getElementById('closeStats');
// Toggle dropdown
statsToggle.addEventListener('click', (e) => {
e.stopPropagation();
statsDropdown.classList.toggle('active');
});
// Close dropdown
closeStats.addEventListener('click', () => {
statsDropdown.classList.remove('active');
});
// Close when clicking outside
document.addEventListener('click', (e) => {
if (!statsDropdown.contains(e.target) && !statsToggle.contains(e.target)) {
statsDropdown.classList.remove('active');
}
});
// Initialize visitor tracking
this.trackVisit();
}
async trackVisit() {
try {
// Check if this is a new session (to avoid counting same user multiple times)
const lastVisit = sessionStorage.getItem('lastVisitTimestamp');
const now = Date.now();
// Only track if this is a new session (or more than 30 minutes since last count)
const shouldTrack = !lastVisit || (now - parseInt(lastVisit)) > 1800000;
if (shouldTrack) {
// Get visitor's country using ipapi.co (free, no API key needed)
const geoResponse = await fetch('https://ipapi.co/json/');
const geoData = await geoResponse.json();
// Extract country information
const country = geoData.country_name || 'Unknown';
const countryCode = geoData.country_code || 'XX';
// Get flag emoji for the country
const flag = this.getCountryFlag(countryCode);
// Try to use backend functions
try {
// Try Netlify path first, then Cloudflare path, then Vercel path
let response = await fetch('/.netlify/functions/track-visit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ country, countryCode, flag })
});
// If Netlify fails, try Cloudflare path
if (!response.ok) {
response = await fetch('/track-visit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ country, countryCode, flag })
});
}
// If Cloudflare fails, try Vercel path
if (!response.ok) {
response = await fetch('/api/track-visit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ country, countryCode, flag })
});
}
if (response.ok) {
const data = await response.json();
this.updateVisitorDisplay(data.totalVisitors);
this.updateCountriesDisplay(data.countries);
sessionStorage.setItem('lastVisitTimestamp', now.toString());
// Sync with Vercel Analytics
track('Visitor_Visit', {
country,
countryCode,
source: 'backend'
});
return;
}
} catch (functionError) {
console.log('Backend functions not available, using fallback...', functionError);
}
// Fallback to CountAPI if Netlify function is not available (local development)
this.fallbackAPITracking(country, countryCode, flag);
sessionStorage.setItem('lastVisitTimestamp', now.toString());
} else {
// Just load existing data without tracking new visit
this.loadVisitorStats();
}
} catch (error) {
console.error('Error tracking visit:', error);
// Final fallback to localStorage only
this.fallbackLocalTracking();
}
}
async loadVisitorStats() {
try {
// Try to load from backend functions
let response = await fetch('/.netlify/functions/track-visit');
if (!response.ok) {
response = await fetch('/track-visit');
}
if (!response.ok) {
response = await fetch('/api/track-visit');
}
if (response.ok) {
const data = await response.json();
this.updateVisitorDisplay(data.totalVisitors);
this.updateCountriesDisplay(data.countries);
return;
}
} catch (error) {
console.log('Loading stats from fallback sources...');
}
// Fallback to CountAPI for global count
try {
const namespace = 'silicon-vault';
const key = 'total-visitors';
const countResponse = await fetch(`https://api.countapi.xyz/get/${namespace}/${key}`);
const countData = await countResponse.json();
this.updateVisitorDisplay(countData.value || 0);
} catch (error) {
console.error('Error loading visitor count:', error);
}
// Load countries from localStorage
const countriesData = this.getCountriesData();
this.updateCountriesDisplay(countriesData);
}
async fallbackAPITracking(country, countryCode, flag) {
// Use CountAPI for global visitor counting (fallback for local development)
const namespace = 'silicon-vault';
const key = 'total-visitors';
try {
const countResponse = await fetch(`https://api.countapi.xyz/hit/${namespace}/${key}`);
const countData = await countResponse.json();
this.updateVisitorDisplay(countData.value);
// Track fallback in Vercel
track('Visitor_Visit_Fallback', {
country,
countryCode,
source: 'countapi'
});
} catch (error) {
console.error('CountAPI error:', error);
}
// Store country visit in localStorage
this.recordCountryVisit(country, countryCode, flag);
}
getCountryFlag(countryCode) {
// Convert country code to flag emoji
if (!countryCode || countryCode === 'XX') return '🌍';
const codePoints = countryCode
.toUpperCase()
.split('')
.map(char => 127397 + char.charCodeAt());
return String.fromCodePoint(...codePoints);
}
recordCountryVisit(countryName, countryCode, flag) {
// Get existing country data from localStorage
const countriesData = this.getCountriesData();
// Check if this is a new session (to avoid counting same user multiple times)
const lastVisit = sessionStorage.getItem('lastVisitTimestamp');
const now = Date.now();
// Only count if this is a new session (or more than 30 minutes since last count)
if (!lastVisit || (now - parseInt(lastVisit)) > 1800000) {
if (!countriesData[countryCode]) {
countriesData[countryCode] = {
name: countryName,
flag: flag,
count: 0
};
}
countriesData[countryCode].count++;
// Save updated data
localStorage.setItem('visitorCountries', JSON.stringify(countriesData));
sessionStorage.setItem('lastVisitTimestamp', now.toString());
}
// Update the countries display
this.updateCountriesDisplay(countriesData);
}
getCountriesData() {
const saved = localStorage.getItem('visitorCountries');
return saved ? JSON.parse(saved) : {};
}
updateVisitorDisplay(totalVisitors) {
// Update badge
const badge = document.getElementById('visitorCountBadge');
if (badge) {
badge.textContent = totalVisitors > 999 ? '999+' : totalVisitors;
}
// Update total visitors in dropdown
const totalElement = document.getElementById('totalVisitors');
if (totalElement) {
totalElement.textContent = totalVisitors.toLocaleString();
}
}
updateCountriesDisplay(countriesData) {
const countriesList = document.getElementById('countriesList');
if (!countriesList) return;
// Sort countries by count (descending)
const sortedCountries = Object.entries(countriesData)
.map(([code, data]) => ({ code, ...data }))
.sort((a, b) => b.count - a.count);
if (sortedCountries.length === 0) {
countriesList.innerHTML = '<div class="no-data">No country data yet...</div>';
return;
}
// Build HTML for countries list
const html = sortedCountries.map(country => `
<div class="country-item">
<div class="country-name">
<span class="country-flag">${country.flag}</span>
<span>${country.name}</span>
</div>
<div class="country-count">${country.count}</div>
</div>
`).join('');
countriesList.innerHTML = html;
}
fallbackLocalTracking() {
// Final fallback if all APIs fail
const fallbackCount = localStorage.getItem('fallbackVisitorCount') || '0';
const newCount = parseInt(fallbackCount) + 1;
localStorage.setItem('fallbackVisitorCount', newCount.toString());
this.updateVisitorDisplay(newCount);
// Try to get basic country info from browser language
const language = navigator.language || 'en-US';
const countryCode = language.split('-')[1] || 'XX';
const flag = this.getCountryFlag(countryCode);
this.recordCountryVisit('Unknown', countryCode, flag);
}
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Ctrl/Cmd + K to focus search
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
document.getElementById('searchBox').focus();
}
// Escape to clear search
if (e.key === 'Escape') {
const searchBox = document.getElementById('searchBox');
if (searchBox.value) {
searchBox.value = '';
searchBox.dispatchEvent(new Event('input'));
}
}
});
// Add CSS animations for notifications
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
new SiliconVault();
});
} else {
new SiliconVault();
}
// Export for potential future use
window.SiliconVault = SiliconVault;