-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2470 lines (2194 loc) · 98 KB
/
script.js
File metadata and controls
2470 lines (2194 loc) · 98 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
// ========== CONSTANTS ==========
const STAR_DENSITY_DIVISOR = 10000;
const STAR_FRAME_MS = 50; // ~20fps starfield
const PARTICLE_FRAME_MS = 33; // ~30fps particles
const MOUSE_THROTTLE_MS = 16; // ~60fps mouse tracking
const SHOOTING_STAR_INTERVAL = 5000;
const METEOR_SHOWER_INTERVAL = 45000;
const METEOR_SHOWER_COUNT = 8;
const TYPEWRITER_TYPE_SPEED = 80;
const TYPEWRITER_DELETE_SPEED = 40;
const TYPEWRITER_PAUSE = 2000;
const TYPEWRITER_SWITCH_DELAY = 500;
const GREETING_SCRAMBLE_SPEED = 40;
const HERO_GLITCH_INTERVAL = 6000;
const HERO_GLITCH_CHANCE = 0.85;
const TITLE_CHAR_DELAY_MS = 50;
const WARP_INITIAL_STRENGTH = 1.5;
const SCROLL_WARP_THRESHOLD = 30;
const SCROLL_DECAY_INTERVAL = 250;
const CODE_RAIN_FRAME_MS = 33;
const CODE_RAIN_ACTIVE_CHANCE = 0.08; // ~8% of columns active
const GLITCH_BURST_INTERVAL = 8000;
const GLITCH_BURST_CHANCE = 0.92;
const HUD_FLICKER_INTERVAL = 4000;
const TERMINAL_IDLE_TIMEOUT = 10000;
const TERMINAL_DEMO_STEP_DELAY = 3000;
const TERMINAL_DEMO_TYPE_SPEED = 80;
const GITHUB_CACHE_TTL = 600000; // 10 minutes
const GHOST_SPAWN_DELAY = 60000; // 60 seconds
const PACKET_SNIFFER_DELAY = 15000; // 15 seconds
const PACKET_MAX_LINES = 8;
const LENS_RADIUS_DEFAULT = 200;
const LENS_RADIUS_HOLD = 300;
const TILT_MAX_DEG = 12;
const CARD_TILT_PERSPECTIVE = 600;
// ========== GLOBAL PERFORMANCE: pause when tab hidden ==========
let _tabVisible = true;
document.addEventListener('visibilitychange', () => { _tabVisible = !document.hidden; });
// ========== THREE-LAYER PARALLAX STARFIELD ==========
const canvas = document.getElementById('starfield');
const ctx = canvas.getContext('2d');
let stars = [];
let shootingStars = [];
let mouseX = 0, mouseY = 0;
let constellationLines = [];
// Ambient drift — scene is never static
let driftTime = 0;
let driftX = 0, driftY = 0;
// Warp state
let warpActive = false;
let warpStrength = 0;
// Feature forward declarations (used in drawStars before their full init)
let lensActive = false;
let lensHolding = false;
let lensHoldTime = 0;
let vizActive = false;
let vizBass = 0, vizMids = 0, vizTreble = 0;
function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }
function createStars() {
stars = [];
const count = Math.floor((canvas.width * canvas.height) / STAR_DENSITY_DIVISOR);
for (let i = 0; i < count; i++) {
// Three layers: background (0-0.33), mid (0.33-0.66), foreground (0.66-1)
const depth = Math.random();
let layer, parallaxSpeed, baseSize;
if (depth < 0.4) {
layer = 0; parallaxSpeed = 0.008; baseSize = depth * 1.2 + 0.3; // background: tiny, barely moves
} else if (depth < 0.75) {
layer = 1; parallaxSpeed = 0.03; baseSize = depth * 1.8 + 0.5; // mid: medium, moderate movement
} else {
layer = 2; parallaxSpeed = 0.07; baseSize = depth * 2.5 + 0.8; // foreground: bright, fast movement
}
// Crimson-infected starfield: ~15% deep red, rest white/warm
const colorType = Math.random();
let r, g, b;
if (colorType < 0.15) { r = 255; g = 40 + Math.random() * 40; b = 40 + Math.random() * 30; } // CRIMSON infected
else if (colorType < 0.55) { r = 220; g = 215; b = 230; } // cool white
else if (colorType < 0.75) { r = 255; g = 235; b = 200; } // warm white
else if (colorType < 0.88) { r = 200; g = 200; b = 220; } // dim white
else { r = 255; g = 160; b = 160; } // soft red tint
stars.push({
x: Math.random() * canvas.width, y: Math.random() * canvas.height,
size: baseSize, speed: depth * 0.5 + 0.1,
opacity: depth * 0.5 + 0.25, pulse: Math.random() * Math.PI * 2,
depth, layer, parallaxSpeed, r, g, b,
twinkleSpeed: Math.random() * 0.04 + 0.005,
// Store original position for warp effect
ox: 0, oy: 0,
});
stars[stars.length - 1].ox = stars[stars.length - 1].x;
stars[stars.length - 1].oy = stars[stars.length - 1].y;
}
constellationLines = [];
}
function spawnShootingStar() {
// Red/white split — some crimson traces, some white
const isCrimson = Math.random() > 0.5;
shootingStars.push({
x: Math.random() * canvas.width * 0.8, y: Math.random() * canvas.height * 0.4,
len: Math.random() * 120 + 60, speed: Math.random() * 10 + 8,
angle: (Math.PI / 4) + (Math.random() * 0.5 - 0.25), opacity: 1, life: 1,
crimson: isCrimson,
});
}
// Shooting stars — rare, surprising
setInterval(() => { if (Math.random() > 0.6) spawnShootingStar(); }, SHOOTING_STAR_INTERVAL);
// Meteor shower
setInterval(() => { for (let i = 0; i < METEOR_SHOWER_COUNT; i++) setTimeout(() => spawnShootingStar(), i * 200); }, METEOR_SHOWER_INTERVAL);
// Pulsar beacon
let pulsarPhase = 0;
let lastStarTime = 0;
function drawStars(timestamp) {
requestAnimationFrame(drawStars);
// Skip when tab hidden or throttle to ~20fps
if (!_tabVisible || timestamp - lastStarTime < STAR_FRAME_MS) return;
lastStarTime = timestamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Ambient drift (sine wave, never static)
driftTime += 0.003;
driftX = Math.sin(driftTime * 0.7) * 8;
driftY = Math.cos(driftTime * 0.5) * 5;
// Warp decay
if (warpStrength > 0.01) {
warpStrength *= 0.96;
} else {
warpStrength = 0;
}
const cx = canvas.width / 2, cy = canvas.height / 2;
// Draw stars with three-layer parallax
stars.forEach(star => {
star.pulse += star.twinkleSpeed;
const flicker = Math.sin(star.pulse) * 0.3 + 0.7;
// Three-layer parallax: each layer moves at different speed
const px = star.parallaxSpeed;
const dx = (mouseX - cx) * px + driftX * (star.layer * 0.5 + 0.5);
const dy = (mouseY - cy) * px + driftY * (star.layer * 0.5 + 0.5);
let sx = star.x + dx, sy = star.y + dy;
// Gravitational lensing effect (Feature 5)
if (lensActive && mouseX && mouseY) {
const ldx = sx - mouseX, ldy = sy - mouseY;
const ldist = Math.sqrt(ldx * ldx + ldy * ldy);
const lensRadius = lensHolding ? LENS_RADIUS_HOLD : LENS_RADIUS_DEFAULT;
if (ldist < lensRadius && ldist > 1) {
const lnx = ldx / ldist, lny = ldy / ldist;
if (lensHolding && lensHoldTime > 1.5) {
// Attraction mode — spiral inward
const pull = Math.min(80 / (ldist * 0.5 + 1), 6);
sx -= lnx * pull; sy -= lny * pull;
// Spiral tangent
sx += lny * pull * 0.3; sy -= lnx * pull * 0.3;
if (ldist < 15) star.opacity *= 0.9; // fade at center
} else {
// Repulsion mode — push outward
const push = Math.min(2000 / (ldist * ldist + 100), 4);
sx += lnx * push; sy += lny * push;
}
}
}
// Warp effect — stars streak away from center
let drawSize = star.size;
let streakLen = 0;
if (warpStrength > 0.01) {
const fromCX = star.x - cx, fromCY = star.y - cy;
const dist = Math.sqrt(fromCX * fromCX + fromCY * fromCY) || 1;
const nx = fromCX / dist, ny = fromCY / dist;
const warpPush = warpStrength * (star.layer + 1) * 40;
sx += nx * warpPush;
sy += ny * warpPush;
streakLen = warpStrength * (star.layer + 1) * 30;
}
// Draw star
if (streakLen > 2) {
// Warp streak — elongated toward vanishing point
const fromCX = star.x - cx, fromCY = star.y - cy;
const dist = Math.sqrt(fromCX * fromCX + fromCY * fromCY) || 1;
const nx = fromCX / dist, ny = fromCY / dist;
const tailX = sx - nx * streakLen, tailY = sy - ny * streakLen;
// Warp streaks — mix of red and white
const isRedStreak = star.r > 200 && star.g < 100;
const sr = isRedStreak ? '255, 45, 45' : `${star.r}, ${star.g}, ${star.b}`;
ctx.beginPath(); ctx.moveTo(tailX, tailY); ctx.lineTo(sx, sy);
ctx.strokeStyle = `rgba(${sr}, ${star.opacity * flicker})`;
ctx.lineWidth = Math.min(star.size * 1.5, 3); ctx.stroke();
ctx.beginPath(); ctx.arc(sx, sy, star.size * 0.8, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${isRedStreak ? '255, 80, 80' : '255, 255, 255'}, ${star.opacity * flicker})`; ctx.fill();
} else {
// Apply threat red-shift and audio visualizer modulation
let dr = star.r, dg = star.g, db = star.b, dOp = star.opacity * flicker, dSize = drawSize;
if (vizActive) {
dSize *= (1 + vizBass * 0.5);
dOp *= (0.7 + vizMids * 0.5);
// Color shift: bass=purple, treble=white
dr = Math.min(255, dr + vizBass * 60);
db = Math.min(255, db + vizBass * 80);
}
ctx.beginPath();
ctx.arc(sx, sy, dSize, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${dr|0}, ${dg|0}, ${db|0}, ${dOp})`;
ctx.fill();
}
});
// Shooting stars
shootingStars.forEach((s, i) => {
s.x += Math.cos(s.angle) * s.speed;
s.y += Math.sin(s.angle) * s.speed;
s.life -= 0.012; s.opacity = s.life;
if (s.life <= 0) { shootingStars.splice(i, 1); return; }
const tailX = s.x - Math.cos(s.angle) * s.len;
const tailY = s.y - Math.sin(s.angle) * s.len;
const cr = s.crimson;
ctx.beginPath(); ctx.moveTo(tailX, tailY); ctx.lineTo(s.x, s.y);
ctx.strokeStyle = `rgba(${cr ? '255, 60, 60' : '220, 220, 240'}, ${s.opacity})`;
ctx.lineWidth = cr ? 2 : 1.5; ctx.stroke();
});
// Pulsar beacon
pulsarPhase += 0.03;
const pulsarBright = (Math.sin(pulsarPhase) * 0.5 + 0.5) * 0.6;
ctx.beginPath(); ctx.arc(canvas.width - 60, 80, 2, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 45, 45, ${pulsarBright})`; ctx.fill();
ctx.beginPath(); ctx.arc(canvas.width - 60, 80, 8, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 45, 45, ${pulsarBright * 0.2})`; ctx.fill();
}
resizeCanvas(); createStars(); requestAnimationFrame(drawStars);
window.addEventListener('resize', () => { resizeCanvas(); createStars(); });
// ========== CURSOR PARTICLE TRAIL ==========
const particleCanvas = document.getElementById('cursorParticles');
const pCtx = particleCanvas.getContext('2d');
let particles = [];
let prevMouseX = -1, prevMouseY = -1, mouseHasMoved = false;
function resizeParticleCanvas() { particleCanvas.width = window.innerWidth; particleCanvas.height = window.innerHeight; }
resizeParticleCanvas();
window.addEventListener('resize', resizeParticleCanvas);
function spawnParticles(x, y, speed) {
const count = Math.min(Math.floor(speed / 3), 4);
for (let i = 0; i < count; i++) {
particles.push({
x: x + (Math.random() - 0.5) * 10, y: y + (Math.random() - 0.5) * 10,
vx: (Math.random() - 0.5) * 2, vy: (Math.random() - 0.5) * 2,
size: Math.random() * 3 + 1, life: 1, decay: Math.random() * 0.03 + 0.02,
color: Math.random() > 0.5 ? '255, 45, 45' : '255, 107, 107',
});
}
}
let lastParticleTime = 0;
function drawParticles(timestamp) {
requestAnimationFrame(drawParticles);
// Skip when tab hidden, throttle to ~30fps, or skip if empty
if (!_tabVisible || timestamp - lastParticleTime < PARTICLE_FRAME_MS) return;
lastParticleTime = timestamp;
if (particles.length === 0) { pCtx.clearRect(0, 0, particleCanvas.width, particleCanvas.height); return; }
pCtx.clearRect(0, 0, particleCanvas.width, particleCanvas.height);
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.x += p.vx; p.y += p.vy; p.life -= p.decay; p.size *= 0.98;
if (p.life <= 0) { particles.splice(i, 1); continue; }
pCtx.beginPath(); pCtx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
pCtx.fillStyle = `rgba(${p.color}, ${p.life * 0.6})`; pCtx.fill();
if (p.size > 1.2) {
pCtx.beginPath(); pCtx.arc(p.x, p.y, p.size * 2.5, 0, Math.PI * 2);
pCtx.fillStyle = `rgba(${p.color}, ${p.life * 0.15})`; pCtx.fill();
}
}
}
requestAnimationFrame(drawParticles);
// ========== ROTATING RETICLE CURSOR ==========
const reticle = document.getElementById('reticle');
let reticleVisible = false;
// ========== MOUSE TRACKING (throttled) ==========
let _lastMouseMove = 0;
document.addEventListener('mousemove', e => {
mouseX = e.clientX; mouseY = e.clientY;
// Reticle follows immediately (GPU-composited via transform)
if (reticle) {
reticle.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
if (!reticleVisible) {
reticleVisible = true;
reticle.classList.add('visible');
document.body.classList.add('reticle-active');
}
}
// Throttle particle spawning to ~60fps
const now = performance.now();
if (now - _lastMouseMove < MOUSE_THROTTLE_MS) return;
_lastMouseMove = now;
if (!mouseHasMoved) { mouseHasMoved = true; prevMouseX = e.clientX; prevMouseY = e.clientY; return; }
const dx = e.clientX - prevMouseX, dy = e.clientY - prevMouseY;
const speed = Math.sqrt(dx * dx + dy * dy);
// Cursor particle trail disabled for performance
prevMouseX = e.clientX; prevMouseY = e.clientY;
}, { passive: true });
document.addEventListener('mouseleave', () => {
if (reticle) { reticle.classList.remove('visible'); reticleVisible = false; }
});
// ========== CLICK SPARKLE BURST ==========
document.addEventListener('click', e => {
if (e.target.closest('a, button, input, .nav, .terminal')) return;
for (let i = 0; i < 4; i++) {
const sparkle = document.createElement('div');
sparkle.className = 'click-sparkle';
const angle = (Math.PI * 2 / 4) * i;
const dist = 20 + Math.random() * 20;
sparkle.style.left = (e.clientX + Math.cos(angle) * dist) + 'px';
sparkle.style.top = (e.clientY + Math.sin(angle) * dist) + 'px';
sparkle.style.background = Math.random() > 0.5 ? 'var(--accent)' : 'var(--accent2)';
sparkle.style.width = sparkle.style.height = (Math.random() * 4 + 2) + 'px';
document.body.appendChild(sparkle);
setTimeout(() => sparkle.remove(), 600);
}
});
// ========== BUTTON RIPPLE EFFECT ==========
document.querySelectorAll('.btn').forEach(btn => {
btn.addEventListener('click', function(e) {
const ripple = document.createElement('span');
ripple.className = 'btn-ripple';
const rect = this.getBoundingClientRect();
ripple.style.left = (e.clientX - rect.left) + 'px';
ripple.style.top = (e.clientY - rect.top) + 'px';
ripple.style.width = ripple.style.height = Math.max(rect.width, rect.height) + 'px';
this.appendChild(ripple);
setTimeout(() => ripple.remove(), 600);
});
});
// ========== TYPEWRITER ==========
const phrases = ['Developer & Creator', 'Building cool things', 'Always learning', 'Open source enthusiast', 'Turning ideas into code'];
let phraseIndex = 0, charIndex = 0, isDeleting = false;
const typewriterEl = document.getElementById('typewriter');
function typewrite() {
const currentPhrase = phrases[phraseIndex];
if (isDeleting) { typewriterEl.textContent = currentPhrase.substring(0, charIndex - 1); charIndex--; }
else { typewriterEl.textContent = currentPhrase.substring(0, charIndex + 1); charIndex++; }
let speed = isDeleting ? TYPEWRITER_DELETE_SPEED : TYPEWRITER_TYPE_SPEED;
if (!isDeleting && charIndex === currentPhrase.length) { speed = TYPEWRITER_PAUSE; isDeleting = true; }
else if (isDeleting && charIndex === 0) { isDeleting = false; phraseIndex = (phraseIndex + 1) % phrases.length; speed = TYPEWRITER_SWITCH_DELAY; }
setTimeout(typewrite, speed);
}
typewrite();
// ========== GREETING TEXT SCRAMBLE ==========
const greetingEl = document.querySelector('.greeting-text');
if (greetingEl) {
const original = greetingEl.textContent;
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
let iterations = 0;
const scrambleInterval = setInterval(() => {
greetingEl.textContent = original.split('').map((char, i) => {
if (i < iterations) return original[i];
return chars[Math.floor(Math.random() * chars.length)];
}).join('');
iterations += 0.5;
if (iterations >= original.length) clearInterval(scrambleInterval);
}, GREETING_SCRAMBLE_SPEED);
}
// ========== HERO NAME GLITCH ==========
const heroName = document.getElementById('heroName');
setInterval(() => {
if (Math.random() > HERO_GLITCH_CHANCE) {
heroName.classList.add('glitch');
setTimeout(() => heroName.classList.remove('glitch'), 300);
}
}, HERO_GLITCH_INTERVAL);
// ========== SECTION TITLE LETTER-BY-LETTER ASSEMBLY ==========
function assembleTitle(titleEl) {
const textSpan = titleEl.querySelector('.title-text');
if (!textSpan || textSpan.dataset.assembled) return;
textSpan.dataset.assembled = '1';
const text = textSpan.textContent;
textSpan.textContent = '';
const chars = [];
for (let i = 0; i < text.length; i++) {
const span = document.createElement('span');
span.className = 'title-char';
span.textContent = text[i] === ' ' ? '\u00A0' : text[i];
textSpan.appendChild(span);
chars.push(span);
}
// Reveal letters one by one like a signal being received
chars.forEach((charEl, i) => {
setTimeout(() => {
charEl.classList.add('revealed');
}, i * TITLE_CHAR_DELAY_MS + 100);
});
// After all letters, slide out the divider line
setTimeout(() => {
titleEl.classList.add('title-assembled');
}, chars.length * TITLE_CHAR_DELAY_MS + 200);
}
// ========== SCROLL REVEAL (with title assembly) ==========
const revealElements = document.querySelectorAll('.reveal');
const revealObserver = new IntersectionObserver((entries) => {
entries.forEach((entry, i) => {
if (entry.isIntersecting) {
setTimeout(() => {
entry.target.classList.add('visible');
// If this is a section title, trigger letter assembly
if (entry.target.classList.contains('section-title')) {
assembleTitle(entry.target);
}
}, i * 100);
revealObserver.unobserve(entry.target);
}
});
}, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });
revealElements.forEach(el => revealObserver.observe(el));
// ========== ARRIVAL PULSE ==========
const arrivalPulse = document.getElementById('arrivalPulse');
const sectionColors = {
home: '#ff2d2d',
about: '#ff2d2d',
projects: '#ff6b6b',
skills: '#ff2d2d',
terminal: '#00ff66',
contact: '#ff6b6b',
};
function fireArrivalPulse(sectionId) {
if (!arrivalPulse) return;
arrivalPulse.classList.remove('active');
arrivalPulse.style.borderColor = sectionColors[sectionId] || 'var(--accent)';
// Force reflow
void arrivalPulse.offsetWidth;
arrivalPulse.classList.add('active');
setTimeout(() => arrivalPulse.classList.remove('active'), 900);
}
// ========== WARP TUNNEL ON NAV JUMP ==========
const warpOverlay = document.getElementById('warpOverlay');
function triggerWarp(targetSectionId) {
// Phase 1: Stars elongate into streaks (warp in)
warpStrength = WARP_INITIAL_STRENGTH;
if (warpOverlay) warpOverlay.classList.add('active');
// Fire glitch burst + HUD breach on every jump
fireGlitch();
if (typeof hudBreach === 'function') hudBreach();
// Flare the nebulas
document.querySelectorAll('.nebula').forEach(n => {
n.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
n.style.opacity = '0.35';
n.style.transform = 'scale(1.15)';
});
// Phase 2: Flash and collapse (0.5s later)
setTimeout(() => {
if (warpOverlay) {
warpOverlay.classList.remove('active');
warpOverlay.classList.add('flash');
warpOverlay.style.background = `radial-gradient(circle at center, ${sectionColors[targetSectionId] || 'rgba(255,255,255,0.3)'}33 0%, transparent 60%)`;
}
// Spawn burst of shooting stars
for (let i = 0; i < 6; i++) setTimeout(() => spawnShootingStar(), i * 50);
}, 500);
// Phase 3: Clear flash, fire arrival pulse
setTimeout(() => {
if (warpOverlay) {
warpOverlay.classList.remove('flash');
warpOverlay.style.background = '';
}
fireArrivalPulse(targetSectionId);
// Settle nebulas
document.querySelectorAll('.nebula').forEach(n => {
n.style.transition = 'opacity 1.5s ease, transform 1.5s ease';
n.style.opacity = '';
n.style.transform = '';
});
}, 900);
}
// ========== NEBULA BREATHING (sine wave) ==========
let nebulaBreathTime = 0;
const nebulas = document.querySelectorAll('.nebula');
// Nebula breathing handled by CSS animation (removed JS rAF loop for performance)
// ========== SPACE DUST PARTICLES ==========
const spaceDust = document.getElementById('spaceDust');
if (spaceDust) {
for (let i = 0; i < 15; i++) {
const p = document.createElement('div'); p.className = 'dust-particle';
p.style.left = Math.random() * 100 + '%'; p.style.top = Math.random() * 100 + '%';
p.style.width = (Math.random() * 2 + 1) + 'px'; p.style.height = p.style.width;
p.style.animationDuration = (Math.random() * 20 + 15) + 's';
p.style.animationDelay = (Math.random() * 20) + 's';
p.style.opacity = Math.random() * 0.4 + 0.1;
spaceDust.appendChild(p);
}
}
// ========== FLOATING CODE FRAGMENTS ==========
const codeSnippets = ['const life = "code";', 'fn main() {}', 'import * as future', '// TODO: conquer', 'let x = 42;', 'async fn build()', 'git push origin', '<Component />', 'pip install', 'npm run dev'];
const heroSection = document.getElementById('home');
if (heroSection) {
for (let i = 0; i < 3; i++) {
const frag = document.createElement('div'); frag.className = 'code-fragment';
frag.textContent = codeSnippets[Math.floor(Math.random() * codeSnippets.length)];
frag.style.left = (Math.random() * 80 + 10) + '%';
frag.style.top = (Math.random() * 60 + 20) + '%';
frag.style.animationDuration = (Math.random() * 15 + 20) + 's';
frag.style.animationDelay = (Math.random() * 15) + 's';
heroSection.appendChild(frag);
}
}
// ========== WARP SPEED ON FAST SCROLL ==========
let lastScrollY = 0, scrollSpeed = 0;
const starfieldCanvas = document.getElementById('starfield');
// ========== UNIFIED SCROLL HANDLER (single listener, throttled via rAF) ==========
const nav = document.getElementById('nav');
const sections = document.querySelectorAll('.section');
const navLinks = document.querySelectorAll('.nav-link');
const rocketBtn = document.getElementById('rocketBtn');
const scrollIndicator = document.getElementById('scrollIndicator');
let _scrollTicking = false;
window.addEventListener('scroll', () => {
const currentY = window.scrollY;
scrollSpeed = Math.abs(currentY - lastScrollY);
lastScrollY = currentY;
if (!_scrollTicking) {
_scrollTicking = true;
requestAnimationFrame(() => {
const sy = window.scrollY;
// Warp speed on fast scroll
if (scrollSpeed > SCROLL_WARP_THRESHOLD) {
const stretch = Math.min(1 + scrollSpeed * 0.002, 1.1);
starfieldCanvas.style.transition = 'none';
starfieldCanvas.style.transform = `scaleY(${stretch})`;
starfieldCanvas.style.filter = `blur(${Math.min(scrollSpeed * 0.03, 2)}px) brightness(1.15)`;
if (scrollSpeed > 60 && Math.random() > 0.6) spawnShootingStar();
}
// Nav scroll effect
nav.classList.toggle('scrolled', sy > 50);
if (scrollIndicator) scrollIndicator.style.opacity = sy > 100 ? '0' : '1';
// Current section detection (single loop for nav + HUD)
let current = 'home';
sections.forEach(section => { if (sy >= section.offsetTop - 200) current = section.getAttribute('id'); });
navLinks.forEach(link => link.classList.toggle('active', link.dataset.section === current));
updateHudSector(current);
// Rocket button
rocketBtn.classList.toggle('visible', sy > 500);
_scrollTicking = false;
});
}
}, { passive: true });
// Scroll speed decay (reduced from 10x/sec to 4x/sec)
setInterval(() => {
if (scrollSpeed < 5) {
starfieldCanvas.style.transition = 'transform 0.6s ease, filter 0.6s ease';
starfieldCanvas.style.transform = 'scaleY(1)';
starfieldCanvas.style.filter = 'none';
}
scrollSpeed *= 0.8;
}, SCROLL_DECAY_INTERVAL);
rocketBtn.addEventListener('click', () => {
rocketBtn.classList.add('launching');
triggerWarp('home');
for (let i = 0; i < 20; i++) {
setTimeout(() => {
particles.push({
x: window.innerWidth - 56 + (Math.random() - 0.5) * 10,
y: window.innerHeight - 56 + (Math.random() - 0.5) * 10,
vx: (Math.random() - 0.5) * 3, vy: Math.random() * 3 + 1,
size: Math.random() * 4 + 1, life: 1, decay: 0.02,
color: Math.random() > 0.5 ? '255, 165, 0' : '255, 215, 0',
});
}, i * 30);
}
window.scrollTo({ top: 0, behavior: 'smooth' });
setTimeout(() => rocketBtn.classList.remove('launching'), 800);
});
// ========== MOBILE MENU ==========
const hamburger = document.getElementById('hamburger');
const mobileMenu = document.getElementById('mobileMenu');
hamburger.addEventListener('click', () => mobileMenu.classList.toggle('open'));
document.querySelectorAll('.mobile-link').forEach(link => { link.addEventListener('click', () => mobileMenu.classList.remove('open')); });
// ========== PROJECT COUNT + STATS ==========
function animateCount(el, target) {
let current = 0;
const step = Math.ceil(target / 30);
const timer = setInterval(() => {
current += step;
if (current >= target) { current = target; clearInterval(timer); el.classList.add('counted'); }
el.textContent = current;
}, 50);
}
// ========== 3D TILT ON PROJECT CARDS (rAF throttled) ==========
let _tiltRAF = null;
function tiltCard(e, card) {
if (_tiltRAF) return;
_tiltRAF = requestAnimationFrame(() => {
const rect = card.getBoundingClientRect();
const x = (e.clientX - rect.left) / rect.width - 0.5;
const y = (e.clientY - rect.top) / rect.height - 0.5;
card.style.transform = `perspective(${CARD_TILT_PERSPECTIVE}px) rotateY(${x * TILT_MAX_DEG}deg) rotateX(${-y * TILT_MAX_DEG}deg) translateY(-4px)`;
_tiltRAF = null;
});
}
function resetCard(card) { card.style.transform = ''; }
// Event delegation for project card tilt (replaces inline handlers)
const projectsContainer = document.getElementById('projects');
if (projectsContainer) {
projectsContainer.addEventListener('mousemove', function(e) {
// Disable tilt on touch devices
if (window.matchMedia('(pointer: coarse)').matches) return;
const card = e.target.closest('.project-card');
if (card) tiltCard(e, card);
}, { passive: true });
projectsContainer.addEventListener('mouseleave', function(e) {
const card = e.target.closest('.project-card');
if (card) resetCard(card);
}, { passive: true });
// Also reset when moving between cards
projectsContainer.addEventListener('mouseout', function(e) {
const card = e.target.closest('.project-card');
if (card && !card.contains(e.relatedTarget)) resetCard(card);
}, { passive: true });
}
// ========== FETCH GITHUB STATS (repos + commits, cached with stale fallback) ==========
async function fetchGitHubStats() {
const projectEl = document.getElementById('statProjects');
const commitEl = document.getElementById('statCommits');
// Helper: load stale cache (any age)
function loadCache() {
try { return JSON.parse(localStorage.getItem('ghStats') || '{}'); } catch { return {}; }
}
// Use cached data if fresh
const cached = loadCache();
if (cached.ts && Date.now() - cached.ts < GITHUB_CACHE_TTL) {
if (projectEl) animateCount(projectEl, cached.repos);
if (commitEl) animateCount(commitEl, cached.commits);
return;
}
try {
const reposRes = await fetch('https://api.github.com/users/ArsenalRX/repos?per_page=100&type=owner');
// Check rate limit headers
const remaining = reposRes.headers.get('X-RateLimit-Remaining');
if (remaining !== null && parseInt(remaining, 10) < 5) {
// Nearly rate-limited — use stale cache if available
if (cached.repos) {
if (projectEl) animateCount(projectEl, cached.repos);
if (commitEl) animateCount(commitEl, cached.commits);
return;
}
}
if (!reposRes.ok) throw new Error('HTTP ' + reposRes.status);
const repos = await reposRes.json();
if (!Array.isArray(repos)) throw new Error('bad response');
if (projectEl) animateCount(projectEl, repos.length);
const counts = await Promise.all(repos.map(async repo => {
try {
const r = await fetch(`https://api.github.com/repos/ArsenalRX/${repo.name}/commits?per_page=1`);
if (!r.ok) return 0;
const link = r.headers.get('Link');
if (link) {
const match = link.match(/page=(\d+)>; rel="last"/);
if (match) return parseInt(match[1], 10);
}
const data = await r.json();
return Array.isArray(data) ? data.length : 0;
} catch { return 0; }
}));
const total = counts.reduce((s, n) => s + n, 0);
if (commitEl) animateCount(commitEl, total || 0);
// Cache results
try { localStorage.setItem('ghStats', JSON.stringify({ repos: repos.length, commits: total || 0, ts: Date.now() })); } catch {}
} catch {
// Fallback: use stale cache, or show "?" with tooltip
const stale = loadCache();
if (stale.repos) {
if (projectEl) animateCount(projectEl, stale.repos);
if (commitEl) animateCount(commitEl, stale.commits);
} else {
if (projectEl) { projectEl.textContent = '?'; projectEl.title = 'GitHub API unavailable'; }
if (commitEl) { commitEl.textContent = '?'; commitEl.title = 'GitHub API unavailable'; }
}
}
}
fetchGitHubStats();
// ========== SKILLS HOVER ==========
const skillDescriptions = {
'Python': 'Versatile powerhouse for AI, automation, scripting, and backend development.',
'JavaScript': 'The language of the web — powers interactivity, animations, and full-stack apps.',
'TypeScript': 'Type-safe JavaScript — catches bugs early and scales to large codebases.',
'C#': 'Object-oriented language for .NET, desktop apps, game dev, and enterprise software.',
'C++': 'High-performance systems language — game engines, drivers, and low-level programming.',
'Rust': 'Memory-safe systems language — fast, reliable, and perfect for native apps.',
'.NET': 'Microsoft framework for building desktop, web, and enterprise applications.',
'Node.js': 'JavaScript runtime for building scalable server-side applications.',
'React': 'Component-based UI library for building fast, dynamic web interfaces.',
'Docker': 'Containerization platform — package and deploy apps anywhere consistently.',
'Git & GitHub': 'Version control and collaboration — track changes, manage code, and work with teams.',
'Linux': 'Open-source OS — servers, development environments, and system administration.',
'AI & ML': 'Machine learning and artificial intelligence — training models and building smart systems.',
'Windows': 'Primary development platform — deep knowledge of Windows internals, drivers, and system APIs.',
'Fedora': 'Red Hat-based Linux distro — development, servers, and containerized workflows.',
};
const centerLabel = document.getElementById('hoveredSkill');
const skillsCenter = document.getElementById('skillsCenter');
const isTouchDevice = window.matchMedia('(pointer: coarse)').matches;
let activeSkillCard = null;
// Update label text for touch devices
if (isTouchDevice && centerLabel) {
centerLabel.innerHTML = 'Tap a skill to learn more';
}
function showSkillInfo(card) {
const name = card.dataset.skill;
const desc = skillDescriptions[name] || '';
centerLabel.innerHTML = `<strong>${name}</strong><br><span style="font-size:0.8rem;font-weight:400;opacity:0.8;">${desc}</span>`;
const icon = document.getElementById('skillInfoIcon');
if (icon) icon.textContent = name.charAt(0);
skillsCenter.classList.add('active');
}
function clearSkillInfo() {
centerLabel.innerHTML = isTouchDevice ? 'Tap a skill to learn more' : 'Hover a skill to learn more';
const icon = document.getElementById('skillInfoIcon');
if (icon) icon.textContent = '?';
skillsCenter.classList.remove('active');
activeSkillCard = null;
}
document.querySelectorAll('.skill-card').forEach(card => {
card.addEventListener('mouseenter', () => showSkillInfo(card));
card.addEventListener('mouseleave', clearSkillInfo);
// Touch/click support
card.addEventListener('click', (e) => {
e.stopPropagation();
if (activeSkillCard === card) {
clearSkillInfo();
} else {
activeSkillCard = card;
showSkillInfo(card);
}
});
});
// Tap outside to dismiss on touch
document.addEventListener('click', () => { if (activeSkillCard) clearSkillInfo(); });
// ========== INTERACTIVE TERMINAL ==========
const terminalInput = document.getElementById('terminalInput');
const terminalBody = document.getElementById('terminalBody');
let commandHistory = [];
let historyIndex = -1;
const terminalCommands = {
help: () => `Available commands:
<span class="cmd-highlight">about</span> - Learn about me
<span class="cmd-highlight">skills</span> - View my skills
<span class="cmd-highlight">projects</span> - See my projects
<span class="cmd-highlight">contact</span> - How to reach me
<span class="cmd-highlight">github</span> - Open my GitHub
<span class="cmd-highlight">neofetch</span> - System info
<span class="cmd-highlight">ls</span> - List project files
<span class="cmd-highlight">whoami</span> - Who are you?
<span class="cmd-highlight">date</span> - Current date
<span class="cmd-highlight">secret</span> - ???
<span class="cmd-highlight">hack</span> - Hack the mainframe
<span class="cmd-highlight">clear</span> - Clear terminal`,
about: () => `Hi! I'm <span class="cmd-highlight">Evan</span>, aka <span class="cmd-highlight">ArsenalRX</span>.
I'm a developer who loves building interactive web experiences,
exploring AI, and turning ideas into reality through code.
When I'm not coding, I play hockey and ride dirtbikes.`,
skills: () => `<span class="cmd-highlight">Languages:</span> Python, JavaScript, TypeScript, C#, C++, Rust
<span class="cmd-highlight">Frameworks:</span> React, .NET, Node.js
<span class="cmd-highlight">Tools:</span> Docker, Git, Linux, Windows, Fedora
<span class="cmd-highlight">Interests:</span> AI/ML, Systems Programming, UI/UX`,
projects: () => { document.querySelector('#projects').scrollIntoView({ behavior: 'smooth' }); return 'Navigating to projects...'; },
contact: () => `Email: <span class="cmd-highlight">faterivalz@gmail.com</span>
GitHub: <span class="cmd-highlight">github.com/ArsenalRX</span>`,
github: () => { window.open('https://github.com/ArsenalRX', '_blank'); return 'Opening GitHub profile...'; },
neofetch: () => `<span class="cmd-highlight">
___ </span> visitor@arsenalrx
<span class="cmd-highlight"> / \\ </span> ─────────────────
<span class="cmd-highlight"> / E. \\ </span> <span class="cmd-highlight">OS:</span> Web Browser
<span class="cmd-highlight"> / ___ \\ </span> <span class="cmd-highlight">Host:</span> arsenalrx.github.io
<span class="cmd-highlight"> / / \\ \\ </span> <span class="cmd-highlight">Resolution:</span> ${window.innerWidth}x${window.innerHeight}
<span class="cmd-highlight"> /__/ \\__\\ </span> <span class="cmd-highlight">Theme:</span> Space Dark
<span class="cmd-highlight">Terminal:</span> ArsenalRX v1.0
<span class="cmd-highlight">Projects:</span> ${document.querySelectorAll('.project-card').length}
<span class="cmd-highlight">Uptime:</span> Always online`,
ls: () => `<span style="color:#58a6ff;">projects/</span> <span style="color:#58a6ff;">skills/</span> <span style="color:#58a6ff;">config/</span>
index.html style.css script.js
README.md .gitignore package.json`,
cat: () => `Usage: cat <filename>
Try: cat README.md`,
'cat readme.md': () => `# ArsenalRX Portfolio
Built with vanilla HTML, CSS, and JavaScript.
Featuring: starfield, particle trails, and space vibes.
<span class="cmd-highlight">*</span> Zero frameworks. Pure code.`,
secret: () => `<span style="color: var(--accent2);">
╔══════════════════════════════════╗
║ You found the secret! ║
║ Try the Konami Code too ;) ║
║ ↑↑↓↓←→←→BA ║
╚══════════════════════════════════╝</span>`,
hack: () => {
document.body.style.transition = 'filter 0.3s';
document.body.style.filter = 'hue-rotate(120deg) saturate(2)';
for (let i = 0; i < 25; i++) setTimeout(() => spawnShootingStar(), i * 80);
setTimeout(() => { document.body.style.filter = ''; }, 3000);
return `<span style="color:#00ff00;">
[*] Accessing mainframe...
[*] Bypassing firewall.......done
[*] Decrypting files..........done
[*] Access granted.
[!] Just kidding. Nice try though ;)</span>`;
},
clear: () => '__CLEAR__',
date: () => `Current date: <span class="cmd-highlight">${new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</span>`,
whoami: () => `You are a <span class="cmd-highlight">visitor</span> exploring Evan's portfolio. Welcome!`,
};
if (terminalInput) {
terminalInput.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (historyIndex < commandHistory.length - 1) { historyIndex++; terminalInput.value = commandHistory[commandHistory.length - 1 - historyIndex]; }
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex > 0) { historyIndex--; terminalInput.value = commandHistory[commandHistory.length - 1 - historyIndex]; }
else { historyIndex = -1; terminalInput.value = ''; }
} else if (e.key === 'Tab') {
e.preventDefault();
const partial = terminalInput.value.trim().toLowerCase();
const match = Object.keys(terminalCommands).find(cmd => cmd.startsWith(partial) && cmd !== partial);
if (match) terminalInput.value = match;
} else if (e.key === 'Enter') {
const cmd = terminalInput.value.trim().toLowerCase();
if (!cmd) return;
commandHistory.push(cmd);
historyIndex = -1;
const cmdLine = document.createElement('div');
cmdLine.className = 'terminal-line';
cmdLine.innerHTML = `<span class="terminal-prompt">visitor@arsenalrx:~$</span> ${cmd}`;
terminalBody.appendChild(cmdLine);
if (terminalCommands[cmd]) {
const result = terminalCommands[cmd]();
if (result === '__CLEAR__') { terminalBody.innerHTML = ''; }
else if (result === null || result === undefined) { /* async command handles own output */ }
else if (result instanceof Promise) {
result.then(r => { if (r) { const ol = document.createElement('div'); ol.className = 'terminal-line'; ol.innerHTML = `<span class="terminal-output">${r}</span>`; terminalBody.appendChild(ol); terminalBody.scrollTop = terminalBody.scrollHeight; } });
}
else {
const outputLine = document.createElement('div');
outputLine.className = 'terminal-line';
outputLine.innerHTML = `<span class="terminal-output">${result}</span>`;
terminalBody.appendChild(outputLine);
}
} else {
const errorLine = document.createElement('div');
errorLine.className = 'terminal-line';
errorLine.innerHTML = `<span class="terminal-output" style="color: #f85149;">Command not found: ${cmd}. Type <span class="cmd-highlight">help</span> for available commands.</span>`;
terminalBody.appendChild(errorLine);
}
terminalInput.value = '';
terminalBody.scrollTop = terminalBody.scrollHeight;
}
});
}
// ========== TERMINAL AUTO-DEMO MODE ==========
let terminalIdleTimer = null;
let autoDemo = false;
const demoCommands = ['help', 'neofetch', 'skills', 'ls', 'about'];
let demoIndex = 0;
function startAutoDemo() {
if (autoDemo) return;
autoDemo = true;
demoIndex = 0;
runDemoStep();
}
function runDemoStep() {
if (!autoDemo || demoIndex >= demoCommands.length) { autoDemo = false; return; }
const cmd = demoCommands[demoIndex];
let i = 0;
terminalInput.value = '';
const typeInterval = setInterval(() => {
terminalInput.value += cmd[i]; i++;
if (i >= cmd.length) {
clearInterval(typeInterval);
setTimeout(() => {
terminalInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
demoIndex++;
setTimeout(() => runDemoStep(), TERMINAL_DEMO_STEP_DELAY);
}, 500);
}
}, TERMINAL_DEMO_TYPE_SPEED);
}
function resetIdleTimer() {
if (autoDemo) { autoDemo = false; }
clearTimeout(terminalIdleTimer);
terminalIdleTimer = setTimeout(startAutoDemo, TERMINAL_IDLE_TIMEOUT);
}
const terminalSection = document.getElementById('terminal');
const terminalObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) resetIdleTimer();
else { clearTimeout(terminalIdleTimer); autoDemo = false; }
});
}, { threshold: 0.3 });
if (terminalSection) terminalObserver.observe(terminalSection);
if (terminalInput) {
terminalInput.addEventListener('focus', () => { autoDemo = false; clearTimeout(terminalIdleTimer); });
terminalInput.addEventListener('blur', resetIdleTimer);
}