-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1140 lines (979 loc) · 44.3 KB
/
Copy pathscript.js
File metadata and controls
1140 lines (979 loc) · 44.3 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
/* ============================================
Interactive Particle Name + Loader
============================================ */
(function () {
'use strict';
// --- Configuration ---
const CONFIG = {
mediaCdn: 'https://pub-695d82c26b22440cbaeea34343fc0bec.r2.dev', // R2 CDN Base URL
particleColor: { r: 0, g: 242, b: 254 }, // Peacock Neon Cyan
particleColorDim: { r: 5, g: 117, b: 230 }, // Peacock Deep Blue
particleSize: 2,
particleGap: 5, // Gap between sampled pixels (tighter = more particles)
mouseRadius: 100, // How far mouse pushes particles
returnSpeed: 0.07, // How quickly particles spring back (slower = more dramatic)
friction: 0.88,
name: 'KUSHAL DHOLA',
fontWeight: '900',
fontFamily: 'Outfit, sans-serif',
lineDistance: 120,
bgParticleCount: 150,
};
// --- Global Instances ---
let lenis;
let globalUpdateStickyScroll = null;
// --- Utility ---
const lerp = (a, b, t) => a + (b - a) * t;
const dist = (x1, y1, x2, y2) => Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
const resolveMediaUrl = (path, folder = '') => {
if (!path) return '';
const trimmed = path.trim();
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) return trimmed;
let cleanPath = trimmed.replace(/^assets\//, '').replace(/^\//, '');
if (folder) {
const cleanFolder = folder.trim().replace(/\/$/, '').replace(/^assets\//, '').replace(/^\//, '');
if (cleanFolder && !cleanPath.startsWith(cleanFolder + '/')) {
cleanPath = `${cleanFolder}/${cleanPath}`;
}
}
if (CONFIG.mediaCdn) {
const base = CONFIG.mediaCdn.endsWith('/') ? CONFIG.mediaCdn.slice(0, -1) : CONFIG.mediaCdn;
return `${base}/${cleanPath}`;
}
return `assets/${cleanPath}`;
};
// --- Particle Class ---
class Particle {
constructor(x, y, originX, originY, baseSize = CONFIG.particleSize) {
this.x = x;
this.y = y;
this.originX = originX;
this.originY = originY;
this.vx = 0;
this.vy = 0;
this.opacity = 0;
this.size = baseSize + Math.random() * (baseSize * 0.2);
this.colorMix = Math.random(); // blend between accent and dim
}
update(mouseX, mouseY, hasMouseInteraction) {
// Mouse repulsion
if (hasMouseInteraction) {
const dx = this.x - mouseX;
const dy = this.y - mouseY;
const d = dist(this.x, this.y, mouseX, mouseY);
if (d < CONFIG.mouseRadius) {
const force = (CONFIG.mouseRadius - d) / CONFIG.mouseRadius;
const angle = Math.atan2(dy, dx);
this.vx += Math.cos(angle) * force * 12;
this.vy += Math.sin(angle) * force * 12;
}
}
// Spring back to origin
this.vx += (this.originX - this.x) * CONFIG.returnSpeed;
this.vy += (this.originY - this.y) * CONFIG.returnSpeed;
// Friction
this.vx *= CONFIG.friction;
this.vy *= CONFIG.friction;
// Update position
this.x += this.vx;
this.y += this.vy;
}
applyWaveForce(wave) {
const dx = this.x - wave.x;
const dy = this.y - wave.y;
const d = dist(this.x, this.y, wave.x, wave.y);
// Check if particle is near the wave front (the "edge" of the energy circle)
const thickness = 15;
if (d > wave.radius - thickness && d < wave.radius + thickness) {
const force = (1 - Math.abs(d - wave.radius) / thickness) * wave.currentPower;
const angle = Math.atan2(dy, dx);
this.vx += Math.cos(angle) * force;
this.vy += Math.sin(angle) * force;
}
}
draw(ctx) {
const c = CONFIG.particleColor;
const cd = CONFIG.particleColorDim;
const r = Math.round(lerp(cd.r, c.r, this.colorMix));
const g = Math.round(lerp(cd.g, c.g, this.colorMix));
const b = Math.round(lerp(cd.b, c.b, this.colorMix));
ctx.fillStyle = `rgba(${r},${g},${b},${this.opacity})`;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
// --- Particle System ---
class ParticleSystem {
constructor(canvas, isLoader = false) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.particles = [];
this.bgParticles = [];
this.mouse = { x: -9999, y: -9999, active: false };
this.waves = []; // Active energy waves
this.isLoader = isLoader;
this.progress = 0; // 0 = scattered, 1 = formed
this.running = true;
this.dpr = Math.min(window.devicePixelRatio || 1, 2);
this.resize();
this.initText();
if (!isLoader) this.initBackground();
}
initBackground() {
this.bgParticles = [];
for (let i = 0; i < CONFIG.bgParticleCount; i++) {
this.bgParticles.push({
x: Math.random() * this.width,
y: Math.random() * this.height,
vx: (Math.random() - 0.5) * 0.5,
vy: (Math.random() - 0.5) * 0.5,
size: Math.random() * 2 + 1
});
}
}
resize() {
const rect = this.canvas.parentElement.getBoundingClientRect();
this.width = rect.width;
this.height = rect.height;
this.canvas.width = this.width * this.dpr;
this.canvas.height = this.height * this.dpr;
this.canvas.style.width = this.width + 'px';
this.canvas.style.height = this.height + 'px';
this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
}
initText() {
this.particles = [];
const ctx = this.ctx;
const text = CONFIG.name;
// Determine font size based on canvas width
let fontSize = Math.min(this.width * 0.12, 100);
if (this.width < 768) fontSize = Math.min(this.width * 0.14, 56);
if (this.width < 480) fontSize = Math.min(this.width * 0.16, 42);
ctx.save();
ctx.font = `${CONFIG.fontWeight} ${fontSize}px ${CONFIG.fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#fff';
// Clear and draw text to sample pixels
ctx.clearRect(0, 0, this.width, this.height);
ctx.fillText(text, this.width / 2, this.height / 2);
// Sample pixels
const imageData = ctx.getImageData(
0, 0,
this.canvas.width, this.canvas.height
);
const data = imageData.data;
// Responsive gap and size for particles
let gap = CONFIG.particleGap;
let pSize = CONFIG.particleSize;
if (this.width < 768) {
gap = 3;
pSize = 1.2;
}
if (this.width < 480) {
gap = 2;
pSize = 0.9;
}
for (let y = 0; y < this.canvas.height; y += gap) {
for (let x = 0; x < this.canvas.width; x += gap) {
const i = (y * this.canvas.width + x) * 4;
if (data[i + 3] > 128) {
const px = x / this.dpr;
const py = y / this.dpr;
// Start position: random scatter for loader, at origin for hero
let startX, startY;
if (this.isLoader) {
startX = Math.random() * this.width;
startY = Math.random() * this.height;
} else {
startX = px;
startY = py;
}
this.particles.push(new Particle(startX, startY, px, py, pSize));
}
}
}
ctx.restore();
ctx.clearRect(0, 0, this.width, this.height);
}
setMouse(x, y) {
this.mouse.x = x;
this.mouse.y = y;
this.mouse.active = true;
}
clearMouse() {
this.mouse.active = false;
this.mouse.x = -9999;
this.mouse.y = -9999;
}
update() {
// Update particle opacity based on progress
for (let i = 0; i < this.particles.length; i++) {
const p = this.particles[i];
const targetOpacity = this.isLoader ? this.progress : 1;
p.opacity = lerp(p.opacity, targetOpacity, 0.05);
p.update(this.mouse.x, this.mouse.y, this.mouse.active);
}
// Update background particles
for (let bp of this.bgParticles) {
bp.x += bp.vx;
bp.y += bp.vy;
// Bounce off edges
if (bp.x < 0 || bp.x > this.width) bp.vx *= -1;
if (bp.y < 0 || bp.y > this.height) bp.vy *= -1;
// Mouse interaction for background dots (Stronger Repulsion)
if (this.mouse.active) {
const d = dist(bp.x, bp.y, this.mouse.x, this.mouse.y);
if (d < 180) {
const force = (180 - d) / 180;
const angle = Math.atan2(bp.y - this.mouse.y, bp.x - this.mouse.x);
bp.vx += Math.cos(angle) * force * 0.8;
bp.vy += Math.sin(angle) * force * 0.8;
}
}
// Constant slow friction
bp.vx *= 0.96;
bp.vy *= 0.96;
}
// Update and clean up waves (disabled)
this.waves = [];
}
draw() {
this.ctx.clearRect(0, 0, this.width, this.height);
// 1. Draw connections first (localized to mouse)
if (!this.isLoader && this.mouse.active) {
this.ctx.beginPath();
this.ctx.strokeStyle = `rgba(${CONFIG.particleColor.r}, ${CONFIG.particleColor.g}, ${CONFIG.particleColor.b}, 0.2)`;
this.ctx.lineWidth = 0.8;
for (let i = 0; i < this.bgParticles.length; i++) {
const p1 = this.bgParticles[i];
const dMouse1 = dist(p1.x, p1.y, this.mouse.x, this.mouse.y);
if (dMouse1 < CONFIG.lineDistance * 1.5) {
// Connect to mouse
this.ctx.moveTo(p1.x, p1.y);
this.ctx.lineTo(this.mouse.x, this.mouse.y);
// Connect to other nearby particles only if they are also near mouse
for (let j = i + 1; j < this.bgParticles.length; j++) {
const p2 = this.bgParticles[j];
const dMouse2 = dist(p2.x, p2.y, this.mouse.x, this.mouse.y);
if (dMouse2 < CONFIG.lineDistance * 1.5) {
const d = dist(p1.x, p1.y, p2.x, p2.y);
if (d < CONFIG.lineDistance) {
this.ctx.moveTo(p1.x, p1.y);
this.ctx.lineTo(p2.x, p2.y);
}
}
}
}
}
this.ctx.stroke();
}
// 2. Draw background particles
for (let bp of this.bgParticles) {
this.ctx.fillStyle = `rgba(${CONFIG.particleColor.r}, ${CONFIG.particleColor.g}, ${CONFIG.particleColor.b}, 0.4)`;
this.ctx.beginPath();
this.ctx.arc(bp.x, bp.y, bp.size, 0, Math.PI * 2);
this.ctx.fill();
}
// 3. Draw text particles
for (let i = 0; i < this.particles.length; i++) {
this.particles[i].draw(this.ctx);
}
}
animate() {
if (!this.running) return;
this.update();
this.draw();
requestAnimationFrame(() => this.animate());
}
destroy() {
this.running = false;
this.particles = [];
}
}
// --- Initialize ---
let loaderSystem, heroSystem;
let loaderDone = false;
function initLoader() {
const canvas = document.getElementById('loaderCanvas');
if (!canvas) return;
loaderSystem = new ParticleSystem(canvas, true);
// Animate formation: progress from 0 → 1 over ~2.5 seconds
let startTime = performance.now();
const duration = 2500;
function animateFormation() {
const elapsed = performance.now() - startTime;
loaderSystem.progress = Math.min(elapsed / duration, 1);
// Also gradually move particles toward their origins
for (let p of loaderSystem.particles) {
const t = loaderSystem.progress * loaderSystem.progress; // ease-in-quad
p.x = lerp(p.x, p.originX, 0.02 + t * 0.06);
p.y = lerp(p.y, p.originY, 0.02 + t * 0.06);
}
if (loaderSystem.progress < 1) {
requestAnimationFrame(animateFormation);
} else {
// Hold for a moment then transition
setTimeout(finishLoader, 600);
}
}
// Add subtle mouse interaction even on loader
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
loaderSystem.setMouse(e.clientX - rect.left, e.clientY - rect.top);
});
canvas.addEventListener('mouseleave', () => loaderSystem.clearMouse());
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
loaderSystem.createWave(e.clientX - rect.left, e.clientY - rect.top);
});
loaderSystem.animate();
requestAnimationFrame(animateFormation);
}
function finishLoader() {
loaderDone = true;
const loader = document.getElementById('loader');
if (loader) loader.classList.add('done');
document.documentElement.classList.remove('no-scroll');
document.body.classList.remove('no-scroll');
// Destroy loader system after transition
setTimeout(() => {
if (loaderSystem) loaderSystem.destroy();
}, 800);
// Show nav
document.querySelector('.nav')?.classList.add('visible');
// Trigger hero animations
setTimeout(initHeroAnimations, 200);
}
function initHero() {
const hero = document.getElementById('hero');
if (hero) {
hero.style.height = window.innerHeight + 'px';
hero.style.minHeight = 'auto';
}
const canvas = document.getElementById('heroCanvas');
if (!canvas) return;
heroSystem = new ParticleSystem(canvas, false);
// Set initial opacity
for (let p of heroSystem.particles) {
p.opacity = 0;
}
// Mouse interaction
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
heroSystem.setMouse(e.clientX - rect.left, e.clientY - rect.top);
});
canvas.addEventListener('mouseleave', () => heroSystem.clearMouse());
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
heroSystem.createWave(e.clientX - rect.left, e.clientY - rect.top);
});
// Touch support (tap to trigger wave)
canvas.addEventListener('touchstart', (e) => {
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
heroSystem.createWave(touch.clientX - rect.left, touch.clientY - rect.top);
}, { passive: true });
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
heroSystem.setMouse(touch.clientX - rect.left, touch.clientY - rect.top);
}, { passive: false });
canvas.addEventListener('touchend', () => heroSystem.clearMouse());
heroSystem.animate();
}
function initHeroAnimations() {
// Fade in hero particles
if (heroSystem) {
for (let p of heroSystem.particles) {
p.opacity = 0;
}
// Gradually reveal
let revealStart = performance.now();
function revealParticles() {
const elapsed = performance.now() - revealStart;
const progress = Math.min(elapsed / 1200, 1);
for (let p of heroSystem.particles) {
p.opacity = progress;
}
if (progress < 1) requestAnimationFrame(revealParticles);
}
requestAnimationFrame(revealParticles);
}
// Animate other hero elements
document.querySelector('.hero-tag')?.classList.add('show');
setTimeout(() => document.querySelector('.hero-desc')?.classList.add('show'), 300);
setTimeout(() => document.querySelector('.hero-cta')?.classList.add('show'), 500);
}
// --- Handle Resize ---
let resizeTimer;
let lastWidth = window.innerWidth;
window.addEventListener('resize', () => {
if (window.innerWidth === lastWidth) return;
lastWidth = window.innerWidth;
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
if (heroSystem && heroSystem.running) {
heroSystem.resize();
heroSystem.initText();
heroSystem.initBackground();
for (let p of heroSystem.particles) p.opacity = 1;
}
if (loaderSystem && loaderSystem.running) {
loaderSystem.resize();
loaderSystem.initText();
}
}, 250);
});
// --- Scroll Reveal ---
function initScrollReveal() {
const reveals = document.querySelectorAll('.section-label, .section-title, .about-text, .about-stats, .project-card, .service-card, .contact-inner, .experience-card, .skill-item, .skills-grid');
reveals.forEach(el => el.classList.add('reveal'));
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
}, { threshold: 0.15 });
reveals.forEach(el => observer.observe(el));
}
// --- Nav Scroll Behavior & Active Section Scrollspy ---
function initNav() {
const nav = document.querySelector('.nav');
let lastScroll = 0;
const sections = document.querySelectorAll('section[id]');
const desktopNavLinks = document.querySelectorAll('.nav-links a');
const mobileNavLinks = document.querySelectorAll('.mobile-menu-links a');
function updateActiveNav() {
const isAtBottom = (window.innerHeight + window.scrollY) >= (document.documentElement.scrollHeight - 50);
if (isAtBottom && desktopNavLinks.length > 0) {
const lastSectionId = sections[sections.length - 1]?.getAttribute('id');
desktopNavLinks.forEach(link => {
link.classList.toggle('active', link.getAttribute('href') === `#${lastSectionId}`);
});
mobileNavLinks.forEach(link => {
link.classList.toggle('active', link.getAttribute('href') === `#${lastSectionId}`);
});
return;
}
const scrollY = window.scrollY + 200;
sections.forEach(section => {
const sectionHeight = section.offsetHeight;
const sectionTop = section.offsetTop;
const sectionId = section.getAttribute('id');
if (scrollY >= sectionTop && scrollY < sectionTop + sectionHeight) {
desktopNavLinks.forEach(link => {
link.classList.toggle('active', link.getAttribute('href') === `#${sectionId}`);
});
mobileNavLinks.forEach(link => {
link.classList.toggle('active', link.getAttribute('href') === `#${sectionId}`);
});
}
});
}
window.addEventListener('scroll', () => {
const st = window.scrollY;
if (st > 100 && !loaderDone) return;
if (st > 100) {
nav?.classList.add('visible');
}
lastScroll = st;
updateActiveNav();
}, { passive: true });
updateActiveNav();
// Mobile menu toggle
const toggle = document.getElementById('navToggle');
const mobile = document.getElementById('mobileMenu');
if (toggle && mobile) {
toggle.addEventListener('click', () => {
toggle.classList.toggle('active');
mobile.classList.toggle('open');
document.body.style.overflow = mobile.classList.contains('open') ? 'hidden' : '';
});
mobile.querySelectorAll('a').forEach(a => {
a.addEventListener('click', () => {
toggle.classList.remove('active');
mobile.classList.remove('open');
document.body.style.overflow = '';
});
});
}
}
// --- Smooth scroll for anchor links ---
function initSmoothScroll() {
if (typeof Lenis !== 'undefined' && window.innerWidth > 1024) {
lenis = new Lenis({
duration: 1.2,
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
direction: 'vertical',
gestureDirection: 'vertical',
smooth: true,
mouseMultiplier: 1,
smoothTouch: false,
touchMultiplier: 2,
infinite: false,
});
lenis.on('scroll', () => {
if (globalUpdateStickyScroll) {
globalUpdateStickyScroll();
}
});
function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);
}
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', (e) => {
const targetId = a.getAttribute('href');
if (targetId === '#') return;
const target = document.querySelector(targetId);
if (target) {
e.preventDefault();
if (lenis) {
lenis.scrollTo(target);
} else {
target.scrollIntoView({ behavior: 'smooth' });
}
// Close mobile menu if open
const mobileMenu = document.getElementById('mobileMenu');
const toggle = document.getElementById('navToggle');
if (mobileMenu && mobileMenu.classList.contains('open')) {
mobileMenu.classList.remove('open');
toggle.classList.remove('active');
}
}
});
});
}
// --- Project Showcase: Horizontal Scroll, Filters, Modal, Lightbox ---
function initProjectShowcase() {
const filterBtns = document.querySelectorAll('.filter-btn');
const cards = document.querySelectorAll('.showcase-card');
const scrollTrack = document.getElementById('projectsScrollTrack');
const workSection = document.getElementById('work');
const modal = document.getElementById('projectModal');
const modalBackdrop = document.getElementById('modalBackdrop');
const modalClose = document.getElementById('modalClose');
const lightbox = document.getElementById('lightbox');
const lightboxMedia = document.getElementById('lightboxMedia');
const lightboxClose = document.getElementById('lightboxClose');
const lightboxPrev = document.getElementById('lightboxPrev');
const lightboxNext = document.getElementById('lightboxNext');
const lightboxCounter = document.getElementById('lightboxCounter');
let currentMedia = [];
let currentMediaIndex = 0;
// --- Smooth Horizontal Scroll via CSS Sticky ---
let wasDesktop = window.innerWidth > 1024;
function updateStickyScroll() {
if (!scrollTrack || !workSection) return;
const scrollInner = document.getElementById('projectsScrollInner');
if (!scrollInner) return;
const maxScroll = Math.max(0, scrollInner.scrollWidth - scrollTrack.clientWidth);
const isDesktop = window.innerWidth > 1024;
if (isDesktop) {
// Set height so the section is sticky for the duration of the horizontal scroll
workSection.style.height = `calc(100vh - 72px + ${maxScroll}px)`;
const rect = workSection.getBoundingClientRect();
const offset = 72;
const scrolled = offset - rect.top;
const targetX = Math.max(0, Math.min(maxScroll, scrolled));
// Use hardware-accelerated transform on desktop for buttery-smooth horizontal scrolling
scrollInner.style.transform = `translate3d(${-targetX}px, 0, 0)`;
// Remove lenis prevent on desktop so scrolling over the track scrolls the page
scrollTrack.removeAttribute('data-lenis-prevent');
wasDesktop = true;
} else {
workSection.style.height = 'auto';
// Add lenis prevent on mobile to allow native swiping without Lenis interference
scrollTrack.setAttribute('data-lenis-prevent', 'true');
if (wasDesktop) {
// Reset transform and scroll position on mobile/tablet fallback
scrollInner.style.transform = 'none';
scrollTrack.scrollLeft = 0;
wasDesktop = false;
}
}
}
globalUpdateStickyScroll = updateStickyScroll;
if (!lenis && window.innerWidth > 1024) {
window.addEventListener('scroll', updateStickyScroll);
}
window.addEventListener('resize', updateStickyScroll);
window.addEventListener('load', updateStickyScroll);
// Run once on init
updateStickyScroll();
setTimeout(updateStickyScroll, 100);
// --- Filter Logic ---
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const filter = btn.getAttribute('data-filter');
// Smoothly scroll vertical viewport back to the top of the work section (offset by header)
if (workSection) {
const offset = 72;
const targetScroll = workSection.offsetTop - offset;
if (lenis) {
lenis.scrollTo(targetScroll, { duration: 0.4 });
} else {
window.scrollTo({ top: targetScroll, behavior: 'smooth' });
}
}
cards.forEach(card => {
const cat = card.getAttribute('data-category');
if (filter === 'all' || cat === filter) {
card.classList.remove('filtering-out');
setTimeout(() => card.classList.remove('hidden'), 10);
} else {
card.classList.add('filtering-out');
setTimeout(() => card.classList.add('hidden'), 350);
}
});
// Reset/clamp scroll on filter after animation finishes
setTimeout(() => {
updateStickyScroll();
}, 400);
});
});
// Helper to get project folder from card attributes
const getCardFolder = (card) => {
if (!card) return '';
return card.getAttribute('data-folder') ||
card.querySelector('.project-media')?.getAttribute('data-folder') ||
'';
};
// --- Auto-resolve Card Thumbnails to CDN ---
cards.forEach(card => {
const folder = getCardFolder(card);
const thumbImg = card.querySelector('.showcase-thumb img');
if (thumbImg) {
const rawSrc = thumbImg.getAttribute('src');
if (rawSrc) {
thumbImg.src = resolveMediaUrl(rawSrc, folder);
}
}
});
// --- Parse media items from child tags or data-media attribute ---
function parseMedia(card) {
if (!card) return [];
const folder = getCardFolder(card);
const mediaList = [];
// 1. Easy Method: Check for child <div class="project-media" hidden> container
const mediaContainer = card.querySelector('.project-media');
if (mediaContainer) {
const elements = mediaContainer.querySelectorAll('img, video, source');
elements.forEach(el => {
const tagName = el.tagName.toLowerCase();
const rawSrc = el.getAttribute('src');
if (!rawSrc) return;
const type = (tagName === 'video' || tagName === 'source') ? 'video' : 'image';
mediaList.push({ type, src: resolveMediaUrl(rawSrc, folder) });
});
if (mediaList.length > 0) return mediaList;
}
// 2. Attribute Method: Check data-media attribute on <article>
const str = card.getAttribute('data-media');
if (!str) return [];
// 2a. Legacy pipe format: "image:path1|video:path2"
if (str.includes('|') || str.includes('image:') || str.includes('video:')) {
return str.split('|').map(item => {
const parts = item.split(':');
if (parts.length >= 2) {
const type = parts[0].trim();
const rawSrc = parts.slice(1).join(':').trim();
return { type, src: resolveMediaUrl(rawSrc, folder) };
}
const rawSrc = item.trim();
const isVideo = /\.(mp4|webm|ogg|mov)$/i.test(rawSrc);
return { type: isVideo ? 'video' : 'image', src: resolveMediaUrl(rawSrc, folder) };
});
}
// 2b. Simple comma or newline-separated format: "path1.png, path2.png"
return str.split(/[\n,]+/).map(item => {
const rawSrc = item.trim();
if (!rawSrc) return null;
const isVideo = /\.(mp4|webm|ogg|mov)$/i.test(rawSrc);
return { type: isVideo ? 'video' : 'image', src: resolveMediaUrl(rawSrc, folder) };
}).filter(Boolean);
}
// --- Modal Logic ---
function openModal(card) {
if (!modal) return;
const title = card.getAttribute('data-title');
const desc = card.getAttribute('data-desc');
const tech = card.getAttribute('data-tech');
const link = card.getAttribute('data-link');
const cat = card.querySelector('.showcase-cat')?.textContent;
document.getElementById('modalTitle').textContent = title;
document.getElementById('modalDesc').textContent = desc;
document.getElementById('modalCat').textContent = cat || '';
document.getElementById('modalLink').href = link;
const techWrap = document.getElementById('modalTech');
techWrap.innerHTML = '';
if (tech) {
tech.split(',').forEach(t => {
const span = document.createElement('span');
span.textContent = t.trim();
techWrap.appendChild(span);
});
}
// Build thumbnail gallery
currentMedia = parseMedia(card);
const gallery = document.getElementById('modalGallery');
gallery.innerHTML = '';
const frag = document.createDocumentFragment();
const maxVisibleThumbs = 4;
const limit = Math.min(currentMedia.length, maxVisibleThumbs);
for (let index = 0; index < limit; index++) {
const item = currentMedia[index];
const thumb = document.createElement('div');
thumb.className = 'gallery-thumb';
thumb.setAttribute('data-index', index);
if (item.type === 'video') {
const vid = document.createElement('video');
vid.src = item.src;
vid.muted = true;
vid.preload = 'metadata';
thumb.appendChild(vid);
// Play icon
const play = document.createElement('div');
play.className = 'thumb-play';
play.innerHTML = '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>';
thumb.appendChild(play);
} else {
const img = document.createElement('img');
img.src = item.src;
img.alt = title + ' screenshot ' + (index + 1);
img.loading = 'lazy';
thumb.appendChild(img);
}
// If it is the 4th thumbnail and there are more images in total, show "+X" overlay
if (index === 3 && currentMedia.length > maxVisibleThumbs) {
thumb.classList.add('has-more-overlay');
const overlay = document.createElement('div');
overlay.className = 'more-overlay';
overlay.innerHTML = `<span>+${currentMedia.length - 3}</span>`;
thumb.appendChild(overlay);
} else {
// Zoom icon (only show if not the "+X" overlay thumb)
const zoom = document.createElement('div');
zoom.className = 'thumb-zoom';
zoom.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>';
thumb.appendChild(zoom);
}
thumb.addEventListener('click', (e) => {
e.stopPropagation();
openLightbox(index);
});
frag.appendChild(thumb);
}
gallery.appendChild(frag);
// Defer open class to next frame so browser can paint the content first
document.body.classList.add('no-scroll');
document.documentElement.classList.add('no-scroll');
requestAnimationFrame(() => {
modal.classList.add('open');
});
}
function closeModal() {
if (!modal) return;
modal.classList.remove('open');
document.body.classList.remove('no-scroll');
document.documentElement.classList.remove('no-scroll');
}
// --- Lightbox Logic ---
function openLightbox(index) {
if (!lightbox || !currentMedia.length) return;
currentMediaIndex = index;
renderLightbox();
lightbox.classList.add('open');
}
function closeLightbox() {
if (!lightbox) return;
lightbox.classList.remove('open');
// Delay DOM cleanup until after close transition
setTimeout(() => { lightboxMedia.innerHTML = ''; }, 300);
}
function renderLightbox() {
const item = currentMedia[currentMediaIndex];
lightboxMedia.innerHTML = '';
if (item.type === 'video') {
const vid = document.createElement('video');
vid.src = item.src;
vid.controls = true;
vid.autoplay = true;
lightboxMedia.appendChild(vid);
} else {
const img = document.createElement('img');
img.src = item.src;
img.alt = 'Project screenshot';
lightboxMedia.appendChild(img);
}
lightboxCounter.textContent = (currentMediaIndex + 1) + ' / ' + currentMedia.length;
lightboxPrev.style.display = currentMedia.length > 1 ? '' : 'none';
lightboxNext.style.display = currentMedia.length > 1 ? '' : 'none';
}
function lightboxNavigate(dir) {
currentMediaIndex = (currentMediaIndex + dir + currentMedia.length) % currentMedia.length;
renderLightbox();
}
// --- Background Media Preloader (Pre-fetches gallery images after site loads) ---
const preloadedUrls = new Set();
function preloadCardMedia(card) {
if (!card) return;
const mediaList = parseMedia(card);
mediaList.forEach(item => {
if (item.type === 'image' && item.src && !preloadedUrls.has(item.src)) {
preloadedUrls.add(item.src);
const img = new Image();
img.src = item.src;
}
});
}
function preloadAllProjectMedia() {
cards.forEach(card => preloadCardMedia(card));
}
// Start background fetching after main page load finishes (1.5s delay or browser idle)
if ('requestIdleCallback' in window) {
requestIdleCallback(() => setTimeout(preloadAllProjectMedia, 1500));
} else {
window.addEventListener('load', () => setTimeout(preloadAllProjectMedia, 1500));
}
// --- Event Listeners ---
cards.forEach(card => {
// Hover preloading: Pre-fetch images instantly when user hovers card
card.addEventListener('mouseenter', () => preloadCardMedia(card), { once: true });
card.addEventListener('click', () => {
openModal(card);
});
});
if (modalBackdrop) modalBackdrop.addEventListener('click', closeModal);
if (modalClose) modalClose.addEventListener('click', closeModal);
if (lightboxClose) lightboxClose.addEventListener('click', closeLightbox);
if (lightboxPrev) lightboxPrev.addEventListener('click', () => lightboxNavigate(-1));
if (lightboxNext) lightboxNext.addEventListener('click', () => lightboxNavigate(1));