-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1854 lines (1602 loc) · 73.2 KB
/
script.js
File metadata and controls
1854 lines (1602 loc) · 73.2 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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Problem2Project - Advanced SEO & Performance Optimized Application
// World-class optimization for Google rankings and user experience
// Performance & SEO Optimization Class
class OptimizationManager {
constructor() {
this.metrics = {};
this.userSession = {};
this.performanceObserver = null;
this.init();
}
init() {
this.initPerformanceTracking();
this.initUserTracking();
this.initEngagementTracking();
this.initSearchTracking();
}
// Core Web Vitals tracking for Google ranking factors
initPerformanceTracking() {
// Track Largest Contentful Paint (LCP)
if ('PerformanceObserver' in window) {
this.performanceObserver = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
if (entry.entryType === 'largest-contentful-paint') {
this.metrics.lcp = entry.startTime;
this.sendMetric('LCP', entry.startTime);
}
if (entry.entryType === 'first-input') {
this.metrics.fid = entry.processingStart - entry.startTime;
this.sendMetric('FID', this.metrics.fid);
}
});
});
try {
this.performanceObserver.observe({ entryTypes: ['largest-contentful-paint', 'first-input'] });
} catch (e) {
// Fallback for older browsers
console.log('Performance observer not fully supported');
}
}
// Track Cumulative Layout Shift (CLS)
let clsValue = 0;
let clsEntries = [];
if ('PerformanceObserver' in window) {
const clsObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
clsEntries.push(entry);
}
}
this.metrics.cls = clsValue;
if (typeof gtag !== 'undefined') {
gtag('event', 'CLS', {
event_category: 'Web Vitals',
value: Math.round(clsValue * 1000),
non_interaction: true
});
}
});
try {
clsObserver.observe({ entryTypes: ['layout-shift'] });
} catch (e) {
console.log('Layout shift observer not supported');
}
}
}
// Advanced user behavior tracking
initUserTracking() {
this.userSession = {
startTime: Date.now(),
pageViews: 1,
interactions: 0,
scrollDepth: 0,
timeOnPage: 0,
returningUser: this.isReturningUser(),
device: this.getDeviceInfo(),
source: this.getTrafficSource()
};
// Track scroll depth for engagement
let maxScroll = 0;
window.addEventListener('scroll', () => {
const scrollPercent = Math.round((window.scrollY + window.innerHeight) / document.body.offsetHeight * 100);
if (scrollPercent > maxScroll) {
maxScroll = scrollPercent;
this.userSession.scrollDepth = maxScroll;
// Track milestone scroll depths
if ([25, 50, 75, 90].includes(maxScroll)) {
this.trackEvent('scroll_depth', 'engagement', `${maxScroll}%`);
}
}
});
// Track time on page
setInterval(() => {
this.userSession.timeOnPage = Math.round((Date.now() - this.userSession.startTime) / 1000);
}, 1000);
// Track page visibility
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.trackEvent('page_hidden', 'engagement', this.userSession.timeOnPage);
} else {
this.trackEvent('page_visible', 'engagement', this.userSession.timeOnPage);
}
});
}
// Advanced engagement tracking
initEngagementTracking() {
// Track clicks with heatmap data
document.addEventListener('click', (e) => {
this.userSession.interactions++;
const elementInfo = {
tag: e.target.tagName,
class: e.target.className,
id: e.target.id,
text: e.target.textContent?.substring(0, 50) || '',
x: e.clientX,
y: e.clientY
};
this.trackEvent('click', 'interaction', JSON.stringify(elementInfo));
});
// Track form interactions
document.addEventListener('input', (e) => {
if (e.target.type === 'search' || e.target.classList.contains('search')) {
this.trackEvent('search_input', 'search', e.target.value.length);
}
});
// Track sharing activities
document.addEventListener('click', (e) => {
if (e.target.classList.contains('share-btn')) {
this.trackEvent('share_attempt', 'social', 'problem_share');
}
if (e.target.classList.contains('bookmark-btn')) {
this.trackEvent('bookmark_toggle', 'engagement', 'problem_bookmark');
}
});
}
// Search behavior tracking for SEO insights
initSearchTracking() {
let searchTimeout;
document.addEventListener('input', (e) => {
if (e.target.type === 'search') {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
const searchTerm = e.target.value.trim();
if (searchTerm.length > 2) {
this.trackEvent('search_performed', 'search', searchTerm);
this.trackSearchTerm(searchTerm);
}
}, 500);
}
});
}
// Utility methods
sendMetric(name, value) {
if (typeof gtag !== 'undefined') {
gtag('event', name, {
event_category: 'Web Vitals',
value: Math.round(value),
non_interaction: true
});
}
}
trackEvent(action, category, label, value = 1) {
if (typeof gtag !== 'undefined') {
gtag('event', action, {
event_category: category,
event_label: label,
value: value,
custom_parameter_1: this.userSession.device,
custom_parameter_2: this.userSession.source
});
}
}
trackSearchTerm(term) {
const searches = JSON.parse(localStorage.getItem('p2p_searches') || '[]');
searches.push({
term: term,
timestamp: Date.now(),
session: this.userSession.startTime
});
// Keep only last 100 searches
if (searches.length > 100) {
searches.splice(0, searches.length - 100);
}
localStorage.setItem('p2p_searches', JSON.stringify(searches));
}
isReturningUser() {
const lastVisit = localStorage.getItem('p2p_last_visit');
localStorage.setItem('p2p_last_visit', Date.now());
return !!lastVisit;
}
getDeviceInfo() {
const width = window.innerWidth;
if (width < 768) return 'mobile';
if (width < 1024) return 'tablet';
return 'desktop';
}
getTrafficSource() {
const referrer = document.referrer;
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('utm_source')) return urlParams.get('utm_source');
if (referrer.includes('google')) return 'google';
if (referrer.includes('bing')) return 'bing';
if (referrer.includes('facebook')) return 'facebook';
if (referrer.includes('twitter')) return 'twitter';
if (referrer === '') return 'direct';
return 'referral';
}
// Session summary for analytics
getSessionSummary() {
return {
...this.userSession,
metrics: this.metrics,
timestamp: Date.now()
};
}
}
// Initialize optimization manager
const optimizationManager = new OptimizationManager();
// Problem2Project - Modern JavaScript Application
// Enhanced functionality for problem discovery and exploration
class Problem2Project {
constructor() {
this.problems = [];
this.allProblems = [];
this.currentCategory = null;
this.currentView = 'grid';
this.domains = {};
this.bookmarkedProblems = this.getBookmarkedProblems();
this.ignoreNextHashChange = false;
// SEO & Performance enhancements
this.searchIndex = new Map(); // For faster search
this.intersectionObserver = null; // For lazy loading
this.lastSearchTerm = '';
this.searchResults = [];
this.pageLoadTime = Date.now();
this.init();
}
async init() {
try {
// Initialize theme first
this.initializeTheme();
// Track page load performance
optimizationManager.trackEvent('page_load_start', 'performance', 'init');
// Load problems data using the data manager
await loadProblemsData();
this.loadData();
// Build search index for performance
this.buildSearchIndex();
this.generateCategoriesGrid();
this.setupEventListeners();
this.updateProblemCounts();
this.hideLoadingScreen();
this.setupIntersectionObserver();
this.setupLazyLoading();
// Track successful initialization
const loadTime = Date.now() - this.pageLoadTime;
optimizationManager.trackEvent('page_load_complete', 'performance', `${loadTime}ms`);
// Initialize bookmarks with a small delay to ensure DOM is ready
setTimeout(() => {
this.updateBookmarkCounts();
this.updateBookmarkLists();
}, 100);
// Handle shared problem links
this.handleSharedProblemLink();
// Handle random problem trigger from other pages
this.handleRandomProblemTrigger();
} catch (error) {
console.error('Failed to initialize application:', error);
this.hideLoadingScreen();
}
}
loadData() {
try {
// Use the embedded DataManager to get problems data
this.problems = PROBLEMS_DATA.problems;
this.allProblems = [...PROBLEMS_DATA.problems];
this.domains = PROBLEMS_DATA.domains;
// Update total problems count
const totalProblemsEl = document.getElementById('total-problems');
if (totalProblemsEl) {
totalProblemsEl.textContent = `${this.problems.length}+`;
}
} catch (error) {
console.error('Error loading data:', error);
throw error;
}
}
generateCategoriesGrid() {
const categoriesGrid = document.getElementById('categories-grid');
if (!categoriesGrid) {
console.warn('Categories grid element not found');
return;
}
try {
// Clear existing content
categoriesGrid.innerHTML = '';
// Generate category cards for all 20 domains
Object.entries(DOMAINS).forEach(([domainId, domainInfo]) => {
const categoryCard = this.createCategoryCard(domainId, domainInfo);
if (categoryCard) {
categoriesGrid.appendChild(categoryCard);
}
});
} catch (error) {
console.error('Error generating categories grid:', error);
}
}
createCategoryCard(domainId, domainInfo) {
if (!domainId || !domainInfo) {
console.warn('Invalid domain data:', domainId, domainInfo);
return null;
}
try {
const cardDiv = document.createElement('div');
cardDiv.className = 'category-card group';
cardDiv.setAttribute('data-category', domainInfo.category || '');
cardDiv.setAttribute('data-domain', domainId);
cardDiv.innerHTML = `
<div class="relative overflow-hidden bg-gradient-to-br ${domainInfo.gradient} dark:from-gray-800 dark:to-gray-700 rounded-2xl p-6 h-full cursor-pointer transition-all duration-300 hover:-translate-y-2 hover:shadow-xl border border-${domainInfo.color}-100 dark:border-gray-600 hover:border-${domainInfo.color}-300 dark:hover:border-${domainInfo.color}-400">
<div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-${domainInfo.color}-400/10 to-${domainInfo.color === 'yellow' ? 'amber' : domainInfo.color}-400/10 dark:from-${domainInfo.color}-400/20 dark:to-${domainInfo.color === 'yellow' ? 'amber' : domainInfo.color}-400/20 rounded-full -translate-y-16 translate-x-16"></div>
<div class="relative z-10">
<div class="w-12 h-12 bg-gradient-to-br ${domainInfo.iconGradient} rounded-xl flex items-center justify-center mb-4">
<i class="${domainInfo.icon} text-white text-xl"></i>
</div>
<h3 class="font-bold text-lg text-gray-900 dark:text-gray-100 mb-2">${domainInfo.shortName}</h3>
<p class="text-gray-600 dark:text-gray-300 text-sm mb-4">${domainInfo.description}</p>
<div class="flex items-center justify-between">
<span class="text-${domainInfo.textColor} dark:text-${domainInfo.textColor.replace('-600', '-400')} font-semibold" id="count-${domainId}">0 problems</span>
<i class="fas fa-arrow-right text-gray-400 dark:text-gray-500 group-hover:text-${domainInfo.textColor.replace('-600', '-500')} dark:group-hover:text-${domainInfo.textColor.replace('-600', '-400')} group-hover:translate-x-1 transition-all"></i>
</div>
</div>
</div>
`;
// Add click event listener
cardDiv.addEventListener('click', () => {
this.selectCategory(domainInfo.category, domainId);
});
return cardDiv;
} catch (error) {
console.error('Error creating category card for domain:', domainId, error);
return null;
}
}
hideLoadingScreen() {
const loadingScreen = document.getElementById('loading-screen');
if (loadingScreen) {
setTimeout(() => {
loadingScreen.style.opacity = '0';
setTimeout(() => {
loadingScreen.style.display = 'none';
}, 500);
}, 1500);
}
}
setupEventListeners() {
// Navigation
this.setupNavigation();
// Search functionality
this.setupSearch();
// Category cards
this.setupCategoryCards();
// Problem interactions
this.setupProblemInteractions();
// Modal functionality
this.setupModal();
// Contact form
this.setupContactForm();
// Utility functions
this.setupUtilities();
// Hash change handling for shared links
window.addEventListener('hashchange', () => {
if (this.ignoreNextHashChange) {
this.ignoreNextHashChange = false;
return;
}
this.handleSharedProblemLink();
});
}
setupNavigation() {
// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', (e) => {
e.preventDefault();
const target = document.querySelector(anchor.getAttribute('href'));
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
});
// Scroll to top button
const scrollToTopButton = document.getElementById('scrollToTop');
window.addEventListener('scroll', () => {
if (window.scrollY > 300) {
scrollToTopButton.classList.remove('opacity-0', 'invisible');
} else {
scrollToTopButton.classList.add('opacity-0', 'invisible');
}
});
scrollToTopButton?.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
setupSearch() {
// Global search overlay
const searchToggle = document.getElementById('search-toggle');
const searchOverlay = document.getElementById('search-overlay');
const searchClose = document.getElementById('search-close');
const globalSearch = document.getElementById('global-search');
searchToggle?.addEventListener('click', () => {
searchOverlay.classList.remove('hidden');
globalSearch.focus();
});
searchClose?.addEventListener('click', () => {
searchOverlay.classList.add('hidden');
});
searchOverlay?.addEventListener('click', (e) => {
if (e.target === searchOverlay) {
searchOverlay.classList.add('hidden');
}
});
// Global search functionality
globalSearch?.addEventListener('input', (e) => {
this.performGlobalSearch(e.target.value);
});
// Search suggestions
document.querySelectorAll('.search-suggestion').forEach(suggestion => {
suggestion.addEventListener('click', () => {
globalSearch.value = suggestion.textContent;
this.performGlobalSearch(suggestion.textContent);
});
});
// Category search
const categorySearch = document.getElementById('category-search');
categorySearch?.addEventListener('input', (e) => {
this.filterCategories(e.target.value);
});
// Problems search
const problemsSearch = document.getElementById('problems-search');
problemsSearch?.addEventListener('input', (e) => {
this.filterProblems(e.target.value);
});
}
setupCategoryCards() {
// Category cards are now dynamically generated and have their event listeners
// attached in the createCategoryCard method
// View toggle for categories
const viewToggle = document.getElementById('view-toggle');
viewToggle?.addEventListener('click', () => {
this.toggleCategoryView();
});
// Sort categories
const sortCategories = document.getElementById('sort-categories');
sortCategories?.addEventListener('change', (e) => {
this.sortCategories(e.target.value);
});
}
setupProblemInteractions() {
// View toggle for problems
const gridView = document.getElementById('grid-view');
const listView = document.getElementById('list-view');
gridView?.addEventListener('click', () => {
this.currentView = 'grid';
gridView.classList.add('bg-blue-600', 'text-white');
gridView.classList.remove('bg-gray-200', 'text-gray-600');
listView.classList.add('bg-gray-200', 'text-gray-600');
listView.classList.remove('bg-blue-600', 'text-white');
this.displayProblems(this.problems);
});
listView?.addEventListener('click', () => {
this.currentView = 'list';
listView.classList.add('bg-blue-600', 'text-white');
listView.classList.remove('bg-gray-200', 'text-gray-600');
gridView.classList.add('bg-gray-200', 'text-gray-600');
gridView.classList.remove('bg-blue-600', 'text-white');
this.displayProblems(this.problems);
});
// Sort problems
const problemsSort = document.getElementById('problems-sort');
problemsSort?.addEventListener('change', (e) => {
this.sortProblems(e.target.value);
});
// Load more button
const loadMore = document.getElementById('load-more');
loadMore?.addEventListener('click', () => {
this.loadMoreProblems();
});
}
setupModal() {
const modal = document.getElementById('problemModal');
// Close modal events
modal?.addEventListener('click', (e) => {
if (e.target === modal) {
this.closeModal();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
this.closeModal();
}
});
// Bookmark functionality (desktop)
const bookmarkBtn = document.getElementById('bookmark-btn');
bookmarkBtn?.addEventListener('click', () => {
this.toggleBookmark();
});
// Bookmark functionality (mobile)
const bookmarkBtnMobile = document.getElementById('bookmark-btn-mobile');
bookmarkBtnMobile?.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
this.toggleBookmark();
});
// Add touch event for better mobile responsiveness
bookmarkBtnMobile?.addEventListener('touchend', (e) => {
e.preventDefault();
e.stopPropagation();
this.toggleBookmark();
});
// Share functionality (desktop)
const shareBtn = document.getElementById('share-btn');
shareBtn?.addEventListener('click', () => {
this.shareProblem();
});
// Share functionality (mobile)
const shareBtnMobile = document.getElementById('share-btn-mobile');
shareBtnMobile?.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
this.shareProblem();
});
// Add touch event for better mobile responsiveness
shareBtnMobile?.addEventListener('touchend', (e) => {
e.preventDefault();
e.stopPropagation();
this.shareProblem();
});
}
setupContactForm() {
const contactForm = document.getElementById('contactForm');
contactForm?.addEventListener('submit', (e) => {
e.preventDefault();
this.handleContactForm(e.target);
});
}
setupUtilities() {
// Theme toggle for desktop
const themeToggle = document.getElementById('theme-toggle');
themeToggle?.addEventListener('click', () => {
this.toggleTheme();
});
// Theme toggle for mobile (in top navbar)
const themeToggleMobile = document.getElementById('theme-toggle-mobile');
themeToggleMobile?.addEventListener('click', () => {
this.toggleTheme();
});
// Search toggle for mobile (in top navbar)
const searchToggleMobile = document.getElementById('search-toggle-mobile');
const searchOverlay = document.getElementById('search-overlay');
const globalSearch = document.getElementById('global-search');
searchToggleMobile?.addEventListener('click', () => {
searchOverlay?.classList.remove('hidden');
globalSearch?.focus();
});
// Bookmarks dropdown for desktop
const bookmarksToggle = document.getElementById('bookmarks-toggle');
const bookmarksDropdown = document.getElementById('bookmarks-dropdown');
bookmarksToggle?.addEventListener('click', (e) => {
e.stopPropagation();
this.toggleBookmarksDropdown();
});
// Bookmarks overlay for mobile
const bookmarksToggleMobileBottom = document.getElementById('bookmarks-toggle-mobile-bottom');
const bookmarksOverlay = document.getElementById('bookmarks-overlay');
const bookmarksClose = document.getElementById('bookmarks-close');
bookmarksToggleMobileBottom?.addEventListener('click', () => {
this.showBookmarksOverlay();
});
bookmarksClose?.addEventListener('click', () => {
this.hideBookmarksOverlay();
});
bookmarksOverlay?.addEventListener('click', (e) => {
if (e.target === bookmarksOverlay) {
this.hideBookmarksOverlay();
}
});
// Close dropdowns when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('#bookmarks-toggle') && !e.target.closest('#bookmarks-dropdown')) {
this.hideBookmarksDropdown();
}
});
// Random problem button
window.showRandomProblem = () => {
this.showRandomProblem();
};
// Related problems
window.showRelatedProblems = () => {
this.showRelatedProblems();
};
}
setupIntersectionObserver() {
// Animate elements on scroll
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-fade-in-up');
// Track element visibility for engagement
optimizationManager.trackEvent('element_viewed', 'engagement', entry.target.className);
}
});
}, observerOptions);
document.querySelectorAll('.category-card, .problem-card').forEach(el => {
observer.observe(el);
});
this.intersectionObserver = observer;
}
// SEO & Performance Optimization Methods
buildSearchIndex() {
// Create optimized search index for instant search
this.searchIndex.clear();
this.allProblems.forEach((problem, index) => {
const searchText = [
problem.title,
problem.description,
problem.domain,
problem.tags?.join(' ') || '',
problem.keywords?.join(' ') || ''
].join(' ').toLowerCase();
// Split into keywords for better matching
const keywords = searchText.split(/\s+/).filter(word => word.length > 2);
keywords.forEach(keyword => {
if (!this.searchIndex.has(keyword)) {
this.searchIndex.set(keyword, []);
}
this.searchIndex.get(keyword).push(index);
});
});
console.log(`Search index built with ${this.searchIndex.size} keywords`);
}
setupLazyLoading() {
// Implement lazy loading for images and content
if ('IntersectionObserver' in window) {
const lazyImageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy-load');
img.classList.add('loaded');
lazyImageObserver.unobserve(img);
}
}
});
});
// Observe all lazy images
document.querySelectorAll('img[data-src]').forEach(img => {
lazyImageObserver.observe(img);
});
}
}
optimizedSearch(query) {
// High-performance search using the index
if (query.length < 2) return this.allProblems;
const searchTerms = query.toLowerCase().split(/\s+/).filter(term => term.length > 1);
const scoreMap = new Map();
searchTerms.forEach(term => {
// Exact matches
if (this.searchIndex.has(term)) {
this.searchIndex.get(term).forEach(index => {
scoreMap.set(index, (scoreMap.get(index) || 0) + 3);
});
}
// Partial matches
for (const [keyword, indices] of this.searchIndex.entries()) {
if (keyword.includes(term) && keyword !== term) {
indices.forEach(index => {
scoreMap.set(index, (scoreMap.get(index) || 0) + 1);
});
}
}
});
// Sort by relevance score
const sortedResults = Array.from(scoreMap.entries())
.sort((a, b) => b[1] - a[1])
.map(([index]) => this.allProblems[index]);
// Track search performance
optimizationManager.trackEvent('search_performed', 'search', `${query} (${sortedResults.length} results)`);
return sortedResults;
}
trackProblemView(problem) {
// Enhanced problem view tracking
optimizationManager.trackEvent('problem_viewed', 'content', problem.domain);
optimizationManager.trackEvent('problem_detail', 'engagement', `ID:${problem.id}`);
// Track problem popularity
const views = JSON.parse(localStorage.getItem('p2p_problem_views') || '{}');
views[problem.id] = (views[problem.id] || 0) + 1;
localStorage.setItem('p2p_problem_views', JSON.stringify(views));
// Update page title for SEO
document.title = `${problem.title} - Problem2Project Innovation Opportunity`;
// Update meta description dynamically
let metaDesc = document.querySelector('meta[name="description"]');
if (metaDesc) {
metaDesc.content = `${problem.description.substring(0, 150)}... | Explore this innovation opportunity on Problem2Project.`;
}
}
enhanceSearchExperience() {
// Implement search suggestions and autocomplete
const searchInput = document.querySelector('input[type="search"]');
if (searchInput) {
let searchTimeout;
searchInput.addEventListener('input', (e) => {
clearTimeout(searchTimeout);
const query = e.target.value.trim();
searchTimeout = setTimeout(() => {
if (query.length > 1) {
this.showSearchSuggestions(query);
this.performOptimizedSearch(query);
} else {
this.hideSearchSuggestions();
}
}, 150); // Debounce for performance
});
}
}
performOptimizedSearch(query) {
// Use optimized search method
const results = this.optimizedSearch(query);
this.searchResults = results;
this.problems = results;
this.renderProblems();
// Update URL for SEO
const url = new URL(window.location);
if (query) {
url.searchParams.set('search', query);
} else {
url.searchParams.delete('search');
}
window.history.pushState({}, '', url);
}
updateProblemCounts() {
// Update domain-specific problem counts
Object.keys(this.domains).forEach(domainId => {
const count = this.problems.filter(p => p.domain === domainId).length;
const countElement = document.getElementById(`count-${domainId}`);
if (countElement) {
countElement.textContent = `${count} problems`;
}
});
// Update total domains count
const totalDomainsElement = document.getElementById('total-domains-about');
if (totalDomainsElement && window.DOMAINS) {
const domainsCount = Object.keys(window.DOMAINS).length;
totalDomainsElement.textContent = `${domainsCount}+`;
}
// Update total keyword count in index page
const totalKeywordsElement = document.getElementById('total-keywords-about');
if (totalKeywordsElement && this.allProblems) {
const keywordSet = new Set();
this.allProblems.forEach(problem => {
if (problem.keywords && Array.isArray(problem.keywords)) {
problem.keywords.forEach(keyword => {
keywordSet.add(keyword.toLowerCase().trim());
});
}
});
const uniqueKeywordsCount = keywordSet.size;
totalKeywordsElement.textContent = `${uniqueKeywordsCount}+`;
}
}
selectCategory(category, domain) {
this.currentCategory = { category, domain };
// Filter problems by domain
const filteredProblems = this.allProblems.filter(p => p.domain === domain);
this.problems = filteredProblems;
// Update UI
this.displayCategoryKeywords(category);
this.displayProblems(filteredProblems);
this.showProblemsSection(category);
// Scroll to problems section
setTimeout(() => {
document.getElementById('problems').scrollIntoView({ behavior: 'smooth' });
}, 100);
}
displayCategoryKeywords(category) {
const keywordsContainer = document.getElementById('keywords-container');
const keywordsList = document.getElementById('keywords-list');
const categoryName = document.getElementById('selected-category-name');
// Get keywords using the DataManager
const keywords = this.getCategoryKeywords(category);
const domainInfo = Object.values(DOMAINS).find(d => d.category === category);
categoryName.textContent = domainInfo ? domainInfo.shortName : category.charAt(0).toUpperCase() + category.slice(1).replace('-', ' ');
keywordsList.innerHTML = '';
keywords.forEach(keyword => {
const span = document.createElement('span');
span.className = 'px-4 py-2 bg-white border border-blue-200 text-blue-800 rounded-full text-sm cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-all duration-300';
span.textContent = keyword;
span.addEventListener('click', () => {
this.filterProblemsByKeyword(keyword);
});
keywordsList.appendChild(span);
});
keywordsContainer.classList.remove('hidden');
}
getCategoryKeywords(category) {
// Map category names to domain keyword keys
const categoryToKeywordMap = {
'programming': 'Programming_Algorithms',
'math': 'Math',
'physics': 'Physics',
'chemistry': 'Chemistry',
'biology': 'Biology',
'data-science': 'DataScience',
'electronics': 'Electronics',
'robotics': 'Robotics',
'mechanical': 'Mechanical',
'civil': 'Civil',
'healthcare': 'Healthcare',
'ux-design': 'UXDesign',
'business': 'Business',
'security': 'Security',
'iot': 'IoT',
'education': 'Education',
'energy': 'Energy',
'agriculture': 'Agriculture',
'legal': 'Legal',
'social-impact': 'SocialImpact',
// New domains
'aerospace': 'Aerospace',
'automotive': 'Automotive',
'finance': 'Finance',
'gaming': 'Gaming',
'materials': 'Materials',
'telecom': 'Telecom',
'pharma': 'Pharma',
'media': 'Media',
'logistics': 'Logistics',
'climate': 'Climate',
'vr-metaverse': 'VRMetaverse',
'quantum': 'Quantum'
};
const keywordKey = categoryToKeywordMap[category];
if (keywordKey && DOMAIN_KEYWORDS[keywordKey]) {
return DOMAIN_KEYWORDS[keywordKey].keywords.slice(0, 12); // Show first 12 keywords
}
// Fallback keywords
return ['Innovation', 'Technology', 'Problem Solving', 'Research', 'Development'];
}
displayProblems(problems) {
const problemsGrid = document.getElementById('problems-grid');
const loading = document.getElementById('loading');
const noProblems = document.getElementById('no-problems');
loading.classList.add('hidden');
noProblems.classList.add('hidden');
problemsGrid.innerHTML = '';