-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1155 lines (1013 loc) · 38.6 KB
/
script.js
File metadata and controls
1155 lines (1013 loc) · 38.6 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
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
document.addEventListener('DOMContentLoaded', function() {
// --- LeetCode Configuration ---
// IMPORTANT: Update this with your actual LeetCode username
// This should be your LeetCode username, not your LeetCode ID
// Example: if your LeetCode profile URL is https://leetcode.com/johndoe/
// then your username is 'johndoe'
const LEETCODE_CONFIG = {
username: 'ZDt3Xwkjvl', // This username is working with the API
displayName: 'Aditya Suryawanshi', // Your display name
enableGraphQL: false, // Disabled due to CORS restrictions
enableUnofficialAPI: true, // This API works correctly
enableAlternativeAPI: false, // Disabled to use only Unofficial API
cacheDuration: 5 * 60 * 1000, // 5 minutes cache duration
rateLimitDelay: 1000, // 1 second between API calls
maxRetries: 3, // Maximum retry attempts
enableOfflineMode: true // Enable offline fallback mode
};
// --- LeetCode API State Management ---
const LeetCodeAPI = {
cache: new Map(),
rateLimitQueue: [],
isProcessing: false,
lastCallTime: 0,
retryCount: 0,
offlineData: null
};
// --- Mobile Navigation Logic ---
const sideNav = document.getElementById('side-nav');
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
const navClose = document.getElementById('nav-close');
const navOverlay = document.getElementById('nav-overlay');
const navLinks = document.querySelectorAll('.nav-link-side');
const sections = document.querySelectorAll('section[id]');
const isMobile = window.innerWidth <= 768;
if (mobileMenuToggle) {
mobileMenuToggle.addEventListener('click', () => {
sideNav?.classList.add('active');
navOverlay?.classList.add('active');
document.body.style.overflow = 'hidden';
});
}
function closeMobileMenu() {
sideNav?.classList.remove('active');
navOverlay?.classList.remove('active');
document.body.style.overflow = '';
}
if (navClose) navClose.addEventListener('click', closeMobileMenu);
if (navOverlay) navOverlay.addEventListener('click', closeMobileMenu);
navLinks.forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const targetId = link.getAttribute('href');
const targetSection = document.querySelector(targetId);
if (targetSection) {
if (isMobile) closeMobileMenu();
setTimeout(() => {
const offsetTop = targetSection.offsetTop - (isMobile ? 60 : 0);
window.scrollTo({ top: offsetTop, behavior: 'smooth' });
}, isMobile ? 300 : 0);
}
});
});
function highlightActiveSection() {
const scrollY = window.scrollY + 100;
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.offsetHeight;
const sectionId = section.getAttribute('id');
if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${sectionId}`) {
link.classList.add('active');
}
});
}
});
}
let scrollTimeout;
window.addEventListener('scroll', () => {
if (scrollTimeout) cancelAnimationFrame(scrollTimeout);
scrollTimeout = requestAnimationFrame(highlightActiveSection);
});
// --- Intersection/Scroll Animations (for content visibility) ---
const animationObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('is-visible');
animationObserver.unobserve(entry.target);
}
});
}, { threshold: isMobile ? 0.1 : 0.15, rootMargin: isMobile ? '0px' : '50px' });
document.querySelectorAll('.animate-on-scroll').forEach(el => animationObserver.observe(el));
// --- Three.js Scene Setup ---
const container = document.getElementById('webgl-container');
const pixelRatio = isMobile ? 1 : Math.min(window.devicePixelRatio, 2);
const starCount = isMobile ? 5000 : 15000;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
antialias: !isMobile,
alpha: true,
powerPreference: isMobile ? "low-power" : "high-performance"
});
renderer.setPixelRatio(pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.5;
container.appendChild(renderer.domElement);
// --- Post-processing (desktop only) ---
let composer, bloomPass;
if (!isMobile) {
composer = new EffectComposer(renderer);
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
bloomPass = new UnrealBloomPass(
new THREE.Vector2(window.innerWidth, window.innerHeight),
1.4,
0.6,
0.12
);
composer.addPass(bloomPass);
}
// --- Starfield ---
const starGeometry = new THREE.BufferGeometry();
const starVertices = [];
for (let i = 0; i < starCount; i++) {
starVertices.push(
(Math.random() - 0.5) * 3000,
(Math.random() - 0.5) * 3000,
(Math.random() - 0.5) * 2000
);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const starMaterial = new THREE.PointsMaterial({
size: isMobile ? 1.2 : 1.5,
transparent: true,
opacity: 0.8,
blending: THREE.AdditiveBlending,
color: 0x64748b
});
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
// --- Infinity Curve Tracer (scroll-reactive) ---
class InfinityCurve extends THREE.Curve {
constructor(scale = 1) { super(); this.scale = scale; }
getPoint(t, target = new THREE.Vector3()) {
const a = this.scale;
const t2 = 2 * Math.PI * t;
const x = a * Math.sqrt(2) * Math.cos(t2) / (Math.sin(t2) ** 2 + 1);
const y = a * Math.sqrt(2) * Math.cos(t2) * Math.sin(t2) / (Math.sin(t2) ** 2 + 1);
return target.set(x, y, 0);
}
}
const infinityPath = new InfinityCurve(isMobile ? 10 : 12);
const tubeSegments = isMobile ? 256 : 512;
const tubeRadius = isMobile ? 0.15 : 0.2;
const tubeGeometry = new THREE.TubeGeometry(infinityPath, tubeSegments, tubeRadius, 12, false);
const tracerBaseOpacity = isMobile ? 0.85 : 0.95;
let tubeMaterial;
if (isMobile) {
tubeMaterial = new THREE.MeshBasicMaterial({
color: 0xff0080,
transparent: true,
opacity: tracerBaseOpacity,
blending: THREE.AdditiveBlending,
depthWrite: false
});
} else {
tubeMaterial = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0.0 },
color1: { value: new THREE.Color(0xff0040) },
color2: { value: new THREE.Color(0x0080ff) },
opacity: { value: tracerBaseOpacity }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec2 vUv;
uniform float time;
uniform vec3 color1;
uniform vec3 color2;
uniform float opacity;
void main() {
float p = fract(vUv.x - time);
float intensity = smoothstep(0.0, 0.3, p) * smoothstep(1.0, 0.7, p);
vec3 color = mix(color1, color2, vUv.x);
gl_FragColor = vec4(color * intensity, intensity * opacity);
}
`,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false
});
}
const infinityTracer = new THREE.Mesh(tubeGeometry, tubeMaterial);
scene.add(infinityTracer);
camera.position.z = isMobile ? 40 : 35;
// Position the model slightly to the right on initial load (X-axis only)
const initialTracerXOffset = isMobile ? 2.0 : 3.5;
infinityTracer.position.x = initialTracerXOffset;
// Scroll-reactive rotation and base opacity for the tracer
let targetRotX = Math.PI / 6;
let targetRotY = Math.PI / 8;
let currentRotX = targetRotX;
let currentRotY = targetRotY;
let baseTracerOpacityTarget = tracerBaseOpacity;
let currentTracerOpacity = tracerBaseOpacity;
// Scroll-reactive scale targets for the tracer (grow when scrolling down)
const minTracerScale = isMobile ? 0.95 : 1.0;
const maxTracerScale = isMobile ? 1.15 : 1.35;
let targetTracerScale = minTracerScale;
let currentTracerScale = targetTracerScale;
function updateScrollTargets() {
const scrollY = window.scrollY;
const maxScroll = Math.max(1, document.body.scrollHeight - window.innerHeight);
const scrollPercent = scrollY / maxScroll;
const rxFactor = isMobile ? 0.0003 : 0.0005;
const ryFactor = isMobile ? 0.00015 : 0.00025;
targetRotX = Math.PI / 6 + scrollY * rxFactor;
targetRotY = Math.PI / 8 + scrollY * ryFactor;
const fadeStart = 0.4;
if (scrollPercent > fadeStart) {
const fade = 1.0 - (scrollPercent - fadeStart) / (0.5);
baseTracerOpacityTarget = Math.max(0.2, tracerBaseOpacity * fade);
} else {
baseTracerOpacityTarget = tracerBaseOpacity;
}
// Update scale target based on scroll position (down -> bigger, up -> smaller)
const scaleRange = maxTracerScale - minTracerScale;
targetTracerScale = Math.max(
minTracerScale,
Math.min(maxTracerScale, minTracerScale + scaleRange * scrollPercent)
);
}
window.addEventListener('scroll', updateScrollTargets);
updateScrollTargets();
function setTracerOpacity(op) {
if (tubeMaterial.uniforms && tubeMaterial.uniforms.opacity) {
tubeMaterial.uniforms.opacity.value = op;
} else if ('opacity' in tubeMaterial) {
tubeMaterial.opacity = op;
}
}
// Helpers
const clamp = (x, a, b) => Math.max(a, Math.min(b, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (t) => t * t * (3 - 2 * t);
// --- Animation Loop ---
const clock = new THREE.Clock();
let animationId;
function animate() {
animationId = requestAnimationFrame(animate);
const t = clock.getElapsedTime();
// Infinity tracer motion
if (!isMobile && tubeMaterial.uniforms) {
tubeMaterial.uniforms.time.value = t * 0.2;
}
const rotLerp = 0.08;
currentRotX += (targetRotX - currentRotX) * rotLerp;
currentRotY += (targetRotY - currentRotY) * rotLerp;
infinityTracer.rotation.x = currentRotX;
infinityTracer.rotation.y = currentRotY;
// Smoothly scale the tracer toward the target scale
const scaleLerp = 0.08;
currentTracerScale += (targetTracerScale - currentTracerScale) * scaleLerp;
infinityTracer.scale.set(currentTracerScale, currentTracerScale, currentTracerScale);
// Stars
stars.rotation.y += isMobile ? 0.00005 : 0.0001;
camera.lookAt(0, 0, 0);
if (composer && !isMobile) {
composer.render();
} else {
renderer.render(scene, camera);
}
}
animate();
// --- Handle Resize ---
function handleResize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
if (composer && !isMobile) composer.setSize(width, height);
}
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(handleResize, 250);
});
// --- Typing Effect ---
const phrases = [
"I build things for the web.",
"I create intelligent solutions.",
"I solve complex problems.",
"I turn ideas into reality."
];
let phraseIndex = 0, charIndex = 0, isDeleting = false;
const typingElement = document.getElementById('typing-text');
if (typingElement) {
function typeEffect() {
const currentPhrase = phrases[phraseIndex];
if (isDeleting) {
typingElement.textContent = currentPhrase.substring(0, charIndex - 1);
charIndex--;
} else {
typingElement.textContent = currentPhrase.substring(0, charIndex + 1);
charIndex++;
}
let typeSpeed = isDeleting ? 50 : 100;
if (!isDeleting && charIndex === currentPhrase.length) {
typeSpeed = 2000;
isDeleting = true;
} else if (isDeleting && charIndex === 0) {
isDeleting = false;
phraseIndex = (phraseIndex + 1) % phrases.length;
}
setTimeout(typeEffect, typeSpeed);
}
typeEffect();
}
// --- Performance: pause when tab hidden on mobile ---
if (isMobile) {
document.addEventListener('visibilitychange', () => {
if (document.hidden) cancelAnimationFrame(animationId)
else animate();
});
}
// --- Skills Progress Bar Animation ---
function initializeSkillProgressBars() {
const skillProgressBars = document.querySelectorAll('.skill-progress');
skillProgressBars.forEach(progressBar => {
const width = progressBar.getAttribute('data-width');
if (width) {
// Set the CSS custom property for the progress bar width
progressBar.style.setProperty('--width', `${width}%`);
// Add a small delay to trigger the animation when the element becomes visible
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Trigger the animation by temporarily resetting and then setting the width
progressBar.style.setProperty('--width', '0%');
setTimeout(() => {
progressBar.style.setProperty('--width', `${width}%`);
}, 100);
observer.unobserve(entry.target);
}
});
}, { threshold: 0.1 });
observer.observe(progressBar);
}
});
}
// Initialize skill progress bars and fetch LeetCode data when the page loads
// Note: We're already inside DOMContentLoaded, so call directly.
setTimeout(initializeSkillProgressBars, 500);
// Defer initial fetch to end of current tick so modal DOM refs are initialized
setTimeout(() => {
try {
fetchLeetCodeData();
} catch (_) {
// no-op
}
}, 0);
// Also initialize when the skills section becomes visible
const skillsSection = document.getElementById('skills');
if (skillsSection) {
const skillsObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
initializeSkillProgressBars();
skillsObserver.unobserve(entry.target);
}
});
}, { threshold: 0.1 });
skillsObserver.observe(skillsSection);
}
// --- LeetCode Modal Functionality ---
const leetcodeModal = document.getElementById('leetcode-modal');
const leetcodeStatsBtn = document.getElementById('leetcode-stats-btn');
const leetcodeModalClose = document.getElementById('leetcode-modal-close');
const leetcodeModalOverlay = document.querySelector('.leetcode-modal-overlay');
const leetcodeLoading = document.getElementById('leetcode-loading');
const leetcodeContent = document.getElementById('leetcode-content');
function openLeetCodeModal() {
leetcodeModal.classList.add('active');
document.body.style.overflow = 'hidden';
fetchLeetCodeData();
}
function closeLeetCodeModal() {
leetcodeModal.classList.remove('active');
document.body.style.overflow = '';
}
// Event listeners for modal
if (leetcodeStatsBtn) {
leetcodeStatsBtn.addEventListener('click', openLeetCodeModal);
}
if (leetcodeModalClose) {
leetcodeModalClose.addEventListener('click', closeLeetCodeModal);
}
if (leetcodeModalOverlay) {
leetcodeModalOverlay.addEventListener('click', closeLeetCodeModal);
}
// Close modal on escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && leetcodeModal.classList.contains('active')) {
closeLeetCodeModal();
}
});
// --- LeetCode API Utility Functions ---
// Cache management
function getCachedData(key) {
const cached = LeetCodeAPI.cache.get(key);
if (cached && Date.now() - cached.timestamp < LEETCODE_CONFIG.cacheDuration) {
return cached.data;
}
LeetCodeAPI.cache.delete(key);
return null;
}
function setCachedData(key, data) {
const dataWithMetadata = {
...data,
_source: 'cache',
_timestamp: Date.now()
};
LeetCodeAPI.cache.set(key, {
data: dataWithMetadata,
timestamp: Date.now()
});
}
// Rate limiting
async function rateLimitedCall(fn) {
return new Promise((resolve, reject) => {
const now = Date.now();
const timeSinceLastCall = now - LeetCodeAPI.lastCallTime;
if (timeSinceLastCall < LEETCODE_CONFIG.rateLimitDelay) {
const delay = LEETCODE_CONFIG.rateLimitDelay - timeSinceLastCall;
setTimeout(() => executeCall(fn, resolve, reject), delay);
} else {
executeCall(fn, resolve, reject);
}
});
}
async function executeCall(fn, resolve, reject) {
try {
LeetCodeAPI.lastCallTime = Date.now();
const result = await fn();
resolve(result);
} catch (error) {
reject(error);
}
}
// Retry mechanism with exponential backoff
async function retryWithBackoff(fn, maxRetries = LEETCODE_CONFIG.maxRetries) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
const delay = Math.min(1000 * Math.pow(2, attempt), 5000);
console.log(`API call failed, retrying in ${delay}ms... (attempt ${attempt + 1}/${maxRetries + 1})`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Offline mode management
function saveOfflineData(data) {
try {
const dataWithMetadata = {
...data,
_source: 'offline',
_timestamp: Date.now()
};
localStorage.setItem('leetcode_offline_data', JSON.stringify({
data: dataWithMetadata,
timestamp: Date.now()
}));
LeetCodeAPI.offlineData = dataWithMetadata;
} catch (error) {
console.warn('Failed to save offline data:', error);
}
}
function getOfflineData() {
try {
const cached = localStorage.getItem('leetcode_offline_data');
if (cached) {
const parsed = JSON.parse(cached);
// Use offline data if it's less than 24 hours old
if (Date.now() - parsed.timestamp < 24 * 60 * 60 * 1000) {
return parsed.data;
}
}
} catch (error) {
console.warn('Failed to load offline data:', error);
}
return null;
}
// Enhanced LeetCode API Integration with proper error handling
async function fetchLeetCodeData() {
const username = LEETCODE_CONFIG.username;
// Validate username
if (!username || username === 'YOUR_ACTUAL_USERNAME' || username === '') {
displayLeetCodeError('Please configure your LeetCode username in the script');
return;
}
try {
// Show loading state
leetcodeLoading.style.display = 'block';
leetcodeContent.style.display = 'none';
// Check cache first
const cacheKey = `leetcode_${username}`;
const cachedData = getCachedData(cacheKey);
if (cachedData) {
console.log('Using cached LeetCode data');
displayLeetCodeData(cachedData);
return;
}
// Check offline data if no cache
if (LEETCODE_CONFIG.enableOfflineMode) {
const offlineData = getOfflineData();
if (offlineData) {
console.log('Using offline LeetCode data');
displayLeetCodeData(offlineData);
// Still try to fetch fresh data in background
fetchFreshDataInBackground(username, cacheKey);
return;
}
}
// Try multiple username formats if the first one fails
const usernameFormats = [
username,
username.toLowerCase(),
username.replace(/[^a-zA-Z0-9]/g, ''),
'ZDt3Xwkjvl' // Original ID as fallback
];
let profileData = null;
let lastError = null;
for (const testUsername of usernameFormats) {
console.log(`Trying username format: ${testUsername}`);
// Method 1: Try unofficial API (prioritize this since it works correctly)
if (LEETCODE_CONFIG.enableUnofficialAPI) {
try {
profileData = await rateLimitedCall(() =>
retryWithBackoff(() => fetchFromUnofficialsAPI(testUsername))
);
if (profileData && profileData.status === 'success') {
console.log(`Success with Unofficial API for username: ${testUsername}`);
break; // Exit the loop once we get successful data from Unofficial API
}
} catch (error) {
console.log(`Unofficial API failed for ${testUsername}:`, error);
lastError = error;
}
}
// Method 2: Try alternative API only if Unofficial API fails
if (!profileData && LEETCODE_CONFIG.enableAlternativeAPI) {
try {
profileData = await rateLimitedCall(() =>
retryWithBackoff(() => fetchFromAlternativeAPI(testUsername))
);
if (profileData) {
console.log(`Success with Alternative API for username: ${testUsername}`);
break;
}
} catch (error) {
console.log(`Alternative API failed for ${testUsername}:`, error);
lastError = error;
}
}
}
if (!profileData) {
throw new Error(lastError?.message || 'All configured API methods failed');
}
if (profileData) {
// Cache the successful result
setCachedData(cacheKey, profileData);
// Save for offline mode
if (LEETCODE_CONFIG.enableOfflineMode) {
saveOfflineData(profileData);
}
displayLeetCodeData(profileData);
} else {
throw new Error('No data received');
}
} catch (error) {
console.error('Error fetching LeetCode data:', error);
displayLeetCodeError(error.message);
}
}
// Expose for inline Retry button inside modal error content
// (module scope prevents global by default)
// eslint-disable-next-line no-undef
window.fetchLeetCodeData = fetchLeetCodeData;
// Background fetch for offline mode
async function fetchFreshDataInBackground(username, cacheKey) {
try {
let profileData = null;
// Try to fetch fresh data silently
if (LEETCODE_CONFIG.enableGraphQL) {
try {
profileData = await rateLimitedCall(() =>
retryWithBackoff(() => fetchFromGraphQL(username))
);
} catch (error) {
console.log('Background GraphQL fetch failed:', error);
}
}
if (!profileData && LEETCODE_CONFIG.enableUnofficialAPI) {
try {
profileData = await rateLimitedCall(() =>
retryWithBackoff(() => fetchFromUnofficialsAPI(username))
);
} catch (error) {
console.log('Background unofficial API fetch failed:', error);
}
}
if (!profileData && LEETCODE_CONFIG.enableAlternativeAPI) {
try {
profileData = await rateLimitedCall(() =>
retryWithBackoff(() => fetchFromAlternativeAPI(username))
);
} catch (error) {
console.log('Background alternative API fetch failed:', error);
}
}
if (profileData) {
// Update cache and offline data silently
setCachedData(cacheKey, profileData);
if (LEETCODE_CONFIG.enableOfflineMode) {
saveOfflineData(profileData);
}
console.log('Background data fetch successful');
}
} catch (error) {
console.log('Background fetch failed:', error);
}
}
// Method 1: Direct GraphQL API (Primary)
async function fetchFromGraphQL(username) {
const query = `
query getUserProfile($username: String!) {
allQuestionsCount {
difficulty
count
}
matchedUser(username: $username) {
username
profile {
realName
avatar
ranking
}
submitStats {
acSubmissionNum {
difficulty
count
}
totalSubmissionNum {
difficulty
count
}
}
contributions {
points
}
}
}
`;
const response = await fetch('https://leetcode.com/graphql/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Referer': 'https://leetcode.com',
},
body: JSON.stringify({
query,
variables: { username },
}),
});
if (!response.ok) {
throw new Error(`GraphQL API returned ${response.status}`);
}
const data = await response.json();
if (!data.data || !data.data.matchedUser) {
throw new Error('User not found or profile is private');
}
// Transform GraphQL data to expected format
const user = data.data.matchedUser;
const stats = user.submitStats;
const easy = stats.acSubmissionNum.find(s => s.difficulty === 'Easy')?.count || 0;
const medium = stats.acSubmissionNum.find(s => s.difficulty === 'Medium')?.count || 0;
const hard = stats.acSubmissionNum.find(s => s.difficulty === 'Hard')?.count || 0;
return {
status: 'Success',
username: user.username,
realName: user.profile.realName,
avatar: user.profile.avatar,
ranking: user.profile.ranking,
totalSolved: easy + medium + hard,
easySolved: easy,
mediumSolved: medium,
hardSolved: hard,
contributionPoints: user.contributions?.points || 0,
reputation: 0, // GraphQL doesn't provide this easily
_source: 'live',
_timestamp: Date.now()
};
}
// Method 2: Unofficial API (Fallback)
async function fetchFromUnofficialsAPI(username) {
const response = await fetch(`https://leetcode-stats-api.herokuapp.com/${username}`);
if (!response.ok) {
throw new Error(`Unofficial API returned ${response.status}`);
}
const data = await response.json();
console.log('Unofficial API response:', data); // Debug log
if (data.status !== 'Success' && data.status !== 'success') {
throw new Error(data.message || 'API returned error status');
}
return {
...data,
_source: 'live',
_timestamp: Date.now(),
_apiSource: 'unofficial' // Add source identifier
};
}
// Method 3: Alternative unofficial API
async function fetchFromAlternativeAPI(username) {
const response = await fetch(`https://alfa-leetcode-api.onrender.com/${username}`);
if (!response.ok) {
throw new Error(`Alternative API returned ${response.status}`);
}
const data = await response.json();
console.log('Alternative API response:', data); // Debug log
// Transform the response to match expected format
return {
status: 'Success',
username: data.username,
totalSolved: data.solvedProblem || 0,
easySolved: data.easySolved || 0,
mediumSolved: data.mediumSolved || 0,
hardSolved: data.hardSolved || 0,
ranking: data.ranking || 'N/A',
contributionPoints: data.contributionPoint || 0,
reputation: data.reputation || 0,
_source: 'live',
_timestamp: Date.now()
};
}
// Method 4: CORS-safe API (using JSONP-like approach)
async function fetchFromCorsSafeAPI(username) {
try {
// Use a CORS proxy or alternative endpoint
const response = await fetch(`https://leetcode-stats-api.herokuapp.com/${username}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`CORS-safe API returned ${response.status}`);
}
const data = await response.json();
if (data.status !== 'Success') {
throw new Error(data.message || 'API returned error status');
}
return {
...data,
_source: 'live',
_timestamp: Date.now()
};
} catch (error) {
console.log('CORS-safe API failed:', error);
throw error;
}
}
// Enhanced display function with better error handling
function displayLeetCodeData(data) {
try {
console.log('Displaying LeetCode data:', data); // Debug log
console.log('API Source:', data._apiSource || 'unknown'); // Show which API was used
// Hide loading, show content
leetcodeLoading.style.display = 'none';
leetcodeContent.style.display = 'block';
// Small delay to ensure DOM is ready
setTimeout(() => {
// Update profile info with fallbacks
const nameElement = document.getElementById('leetcode-name');
const usernameElement = document.getElementById('leetcode-username');
if (nameElement) {
nameElement.textContent = data.realName || LEETCODE_CONFIG.displayName || data.username || 'LeetCode User';
}
if (usernameElement) {
usernameElement.textContent = `@${data.username || 'unknown'}`;
}
// Update statistics with proper field mapping based on API response
const totalSolved = data.totalSolved || 0;
const ranking = data.ranking || 'N/A';
const contributionPoints = data.contributionPoints || 0;
const reputation = data.reputation || 0;
console.log('Statistics to update:', { totalSolved, ranking, contributionPoints, reputation }); // Debug log
updateElementText('leetcode-total-solved', totalSolved);
// Update the Problems Solved heading with exact total solved count
const solvedHeading = document.getElementById('leetcode-problems-solved-heading');
if (solvedHeading) {
solvedHeading.textContent = `${totalSolved} Problems Solved`;
}
updateElementText('leetcode-ranking', ranking);
updateElementText('leetcode-contribution', contributionPoints);
updateElementText('leetcode-reputation', reputation);
// Update difficulty breakdown with correct field mapping
const easyCount = data.easySolved || 0;
const mediumCount = data.mediumSolved || 0;
const hardCount = data.hardSolved || 0;
const total = easyCount + mediumCount + hardCount;
console.log('Difficulty breakdown:', { easyCount, mediumCount, hardCount, total }); // Debug log
updateElementText('leetcode-easy-count', easyCount);
updateElementText('leetcode-medium-count', mediumCount);
updateElementText('leetcode-hard-count', hardCount);
// Animate progress bars with safety checks
setTimeout(() => {
if (total > 0) {
updateProgressBar('leetcode-easy-bar', (easyCount / total) * 100);
updateProgressBar('leetcode-medium-bar', (mediumCount / total) * 100);
updateProgressBar('leetcode-hard-bar', (hardCount / total) * 100);
}
}, 100);
// Generate recent activity (since real data might not be available)
generateRecentActivity(data);
}, 50); // Small delay to ensure DOM is ready
} catch (error) {
console.error('Error displaying LeetCode data:', error);
displayLeetCodeError('Error displaying data');
}
}
// Helper functions
function formatProblemsSolvedBucket(total) {
if (!Number.isFinite(total) || total <= 0) return '0';
const maxCap = 1000;
const capped = Math.min(total, maxCap);
const bucket = Math.floor(capped / 10) * 10;
if (bucket < 10) return '0';
return `${bucket}+`;
}
function updateElementText(elementId, value) {
const element = document.getElementById(elementId);
if (element) {
console.log(`Updating ${elementId} with value: ${value}`); // Debug log
element.textContent = value;
} else {
console.error(`Element with id '${elementId}' not found`); // Debug error
}
}
function updateProgressBar(elementId, percentage) {