-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1422 lines (1183 loc) · 45.2 KB
/
script.js
File metadata and controls
1422 lines (1183 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ========================================
// Portfolio: The Architect of Systems
// Main JavaScript - Animations & Interactivity
// ========================================
// ---- Initialize GSAP ----
gsap.registerPlugin(ScrollTrigger);
// ---- ASCII Stars Background Generator ----
function generateHexStream() {
const container = document.getElementById('hex-stream');
if (!container) return;
// Caratteri ASCII casuali - mix di simboli, lettere, numeri
const asciiChars = '!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Colori casuali per le "stelle"
const colors = [
'#00d4ff', // cyan
'#a855f7', // purple
'#ec4899', // pink
'#22c55e', // green
'#f59e0b', // orange
'#3b82f6', // blue
'#ef4444', // red
'#10b981', // emerald
'#8b5cf6', // violet
'#06b6d4' // cyan-500
];
// Calcola quante "stelle" creare in base alla dimensione dello schermo
const starCount = Math.floor((window.innerWidth * window.innerHeight) / 8000);
for (let i = 0; i < starCount; i++) {
const star = document.createElement('div');
star.className = 'ascii-star';
// Posizione casuale
star.style.left = `${Math.random() * 100}%`;
star.style.top = `${Math.random() * 100}%`;
// Carattere casuale
star.textContent = asciiChars[Math.floor(Math.random() * asciiChars.length)];
// Colore casuale
const randomColor = colors[Math.floor(Math.random() * colors.length)];
star.style.color = randomColor;
// Durata animazione casuale (tra 2 e 6 secondi)
star.style.animationDuration = `${2 + Math.random() * 4}s`;
// Delay casuale per non farle partire tutte insieme
star.style.animationDelay = `${Math.random() * 5}s`;
container.appendChild(star);
}
}
// ---- Custom Context Menu ----
const contextMenu = document.getElementById('context-menu');
let menuVisible = false;
function showContextMenu(x, y) {
// Adjust position to stay within viewport
const menuWidth = 180;
const menuHeight = 120;
if (x + menuWidth > window.innerWidth) {
x = window.innerWidth - menuWidth - 10;
}
if (y + menuHeight > window.innerHeight) {
y = window.innerHeight - menuHeight - 10;
}
contextMenu.style.left = `${x}px`;
contextMenu.style.top = `${y}px`;
contextMenu.classList.add('active');
menuVisible = true;
// GSAP animation
gsap.fromTo(contextMenu,
{ scale: 0.8, opacity: 0 },
{ scale: 1, opacity: 1, duration: 0.2, ease: 'back.out(2)' }
);
}
function hideContextMenu() {
if (!menuVisible) return;
gsap.to(contextMenu, {
scale: 0.8,
opacity: 0,
duration: 0.15,
ease: 'power2.in',
onComplete: () => {
contextMenu.classList.remove('active');
menuVisible = false;
}
});
}
// Prevent default context menu and show custom one
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e.clientX, e.clientY);
});
// Block Shift + Right Click (Bypass attempt)
document.addEventListener('mousedown', (e) => {
if (e.button === 2 && e.shiftKey) {
e.preventDefault();
e.stopPropagation();
// Since the browser might surely try to open the menu, we ensure our custom one suppresses it or handles it
// Note: Firefox strongly enforces Shift+RightClick bypassing scripts.
// We can try to force show ours, but blocking the native one fully on Shift+RightClick is difficult in FF.
// However, this capture listener is the best attempt.
showContextMenu(e.clientX, e.clientY);
}
}, { capture: true });
// Disable text selection JS fallback
document.addEventListener('selectstart', (e) => {
e.preventDefault();
});
// Hide menu on click outside
document.addEventListener('click', (e) => {
if (!contextMenu.contains(e.target)) {
hideContextMenu();
}
});
// Hide menu on scroll
document.addEventListener('scroll', hideContextMenu);
// Prevent image dragging (Extra protection)
document.addEventListener('dragstart', (e) => {
if (e.target.tagName === 'IMG') {
e.preventDefault();
}
});
// Language selection from context menu
document.querySelectorAll('.lang-option').forEach(option => {
option.addEventListener('click', (e) => {
const lang = e.currentTarget.dataset.lang;
updateLanguage(lang);
// Update active state
document.querySelectorAll('.lang-option').forEach(opt => {
opt.classList.remove('active');
});
e.currentTarget.classList.add('active');
hideContextMenu();
});
});
// ---- Mobile Language Toggle ----
const mobileToggle = document.getElementById('mobile-lang-toggle');
if (mobileToggle) {
mobileToggle.addEventListener('click', () => {
const newLang = currentLang === 'en' ? 'de' : 'en';
updateLanguage(newLang);
// Update context menu active states
document.querySelectorAll('.lang-option').forEach(opt => {
opt.classList.toggle('active', opt.dataset.lang === newLang);
});
// Animate toggle
gsap.fromTo(mobileToggle,
{ scale: 0.9 },
{ scale: 1, duration: 0.3, ease: 'elastic.out(1, 0.5)' }
);
});
}
// ---- GSAP Scroll Animations ----
function initScrollAnimations() {
// Hero content animations - Optimized for LCP
// Title slides up but stays visible to prevent rendering delay
gsap.from('.hero-content h1', {
y: 40,
duration: 1.2,
ease: 'power3.out'
});
// Subtext fade in
gsap.from('.hero-content p', {
opacity: 0,
y: 30,
duration: 1.2,
ease: 'power3.out',
delay: 0.2
});
// Button fade in - ensure ID selector for specificity
gsap.from('#init-profile-btn', {
opacity: 0,
y: 30,
duration: 1.2,
ease: 'power3.out',
delay: 0.4,
clearProps: "all" // Clean up inline styles to prevent conflict with CSS transitions
});
// Section fade-in animations
gsap.utils.toArray('.section').forEach(section => {
gsap.from(section, {
scrollTrigger: {
trigger: section,
start: 'top 80%',
toggleActions: 'play none none reverse'
},
opacity: 0,
y: 50,
duration: 0.8,
ease: 'power2.out'
});
});
// Staggered card animations
gsap.utils.toArray('.glass-card').forEach((card, i) => {
gsap.from(card, {
scrollTrigger: {
trigger: card,
start: 'top 85%',
toggleActions: 'play none none reverse'
},
opacity: 0,
y: 40,
duration: 0.6,
delay: i * 0.1,
ease: 'power2.out'
});
});
// Parallax effect on hero background
gsap.to('.hex-stream', {
scrollTrigger: {
trigger: '.hero',
start: 'top top',
end: 'bottom top',
scrub: 1
},
y: 200,
ease: 'none'
});
// Floating animation for specific elements
gsap.utils.toArray('.floating').forEach((el, i) => {
gsap.to(el, {
y: -15,
duration: 2 + i * 0.5,
ease: 'sine.inOut',
repeat: -1,
yoyo: true,
delay: i * 0.2
});
});
}
// ---- Smooth Scroll ----
document.querySelectorAll('a[href^="#"]:not(#init-profile-btn)').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
gsap.to(window, {
duration: 1,
scrollTo: { y: target, offsetY: 50 },
ease: 'power2.inOut'
});
}
});
});
// ---- Sticky Nav Scroll Effect ----
const stickyNav = document.querySelector('.sticky-nav');
if (stickyNav) {
window.addEventListener('scroll', () => {
if (window.scrollY > 50) {
stickyNav.classList.add('scrolled');
} else {
stickyNav.classList.remove('scrolled');
}
});
}
// ---- Mobile Menu Toggle ----
const mobileBtn = document.getElementById('mobile-menu-toggle');
const mobileDropdown = document.getElementById('mobile-dropdown');
if (mobileBtn && mobileDropdown) {
const toggleMenu = (e) => {
// Prevent default only for touchstart to avoid ghost clicks,
// but keep propagation stopped for both.
if (e.type === 'touchstart') {
e.preventDefault();
}
e.stopPropagation();
mobileDropdown.classList.toggle('active');
};
mobileBtn.addEventListener('click', toggleMenu);
mobileBtn.addEventListener('touchstart', toggleMenu, { passive: false });
// Close menu when clicking a link
mobileDropdown.querySelectorAll('a').forEach(link => {
link.addEventListener('click', () => {
mobileDropdown.classList.remove('active');
});
});
// Close menu when clicking outside
const closeMenu = (e) => {
if (!mobileDropdown.contains(e.target) && !mobileBtn.contains(e.target)) {
mobileDropdown.classList.remove('active');
}
};
document.addEventListener('click', closeMenu);
document.addEventListener('touchstart', closeMenu, { passive: true });
}
// ---- Glitch Effect Enhancement ----
const crownJewel = document.querySelector('.crown-jewel');
if (crownJewel) {
crownJewel.addEventListener('mouseenter', () => {
gsap.to(crownJewel, {
duration: 0.1,
x: () => Math.random() * 4 - 2,
y: () => Math.random() * 4 - 2,
repeat: 5,
yoyo: true,
ease: 'none',
onComplete: () => {
gsap.set(crownJewel, { x: 0, y: 0 });
}
});
});
}
// ---- Code Background Generator ----
function generateCodeBackground() {
const codeBg = document.querySelector('.code-bg');
if (!codeBg) return;
const codeSnippets = [
'def extract_save(hdd_image, offset):',
' cluster = read_fat_entry(0x00FE)',
' data = bytes()',
' while cluster != 0xFFFF:',
' data += read_cluster(cluster)',
' cluster = get_next_cluster(cluster)',
' return decompress_xsave(data)',
'',
'class FATXParser:',
' SECTOR_SIZE = 512',
' CLUSTER_SHIFT = 5',
' ',
' def parse_header(self):',
' magic = self.read(4)',
' assert magic == b"FATX"',
' self.root_cluster = unpack("<I")',
'',
'# Orphan cluster recovery',
'def scan_orphans(fat_table):',
' orphans = []',
' for i, entry in enumerate(fat_table):',
' if entry == 0x0000:',
' orphans.append(i)',
' return orphans',
];
codeBg.textContent = codeSnippets.join('\n').repeat(8);
}
// ---- Animate Number Counter ----
function animateNumber(element, targetValue, duration = 2000, suffix = '+', prefix = '') {
const startValue = 0;
const startTime = performance.now();
function updateNumber(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// Easing function for smooth animation (easeOutExpo)
const easeProgress = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress);
const currentValue = Math.floor(startValue + (targetValue - startValue) * easeProgress);
// Format with thousands separator
const formattedValue = currentValue.toLocaleString();
element.textContent = `${prefix}${formattedValue}${suffix}`;
if (progress < 1) {
requestAnimationFrame(updateNumber);
} else {
// Ensure final value is exact
element.textContent = `${prefix}${targetValue.toLocaleString()}${suffix}`;
}
}
requestAnimationFrame(updateNumber);
}
// ---- GitHub Stats Fetcher ----
let statsData = null;
let statsAnimationTriggered = false;
async function fetchGitHubStats() {
try {
// Fetch repository data from GitHub API
const response = await fetch('https://api.github.com/repos/Matteo842/SaveState');
if (!response.ok) {
throw new Error('Failed to fetch GitHub data');
}
const data = await response.json();
// Get stars count
const stars = data.stargazers_count;
// Fetch releases for download count
const releasesResponse = await fetch('https://api.github.com/repos/Matteo842/SaveState/releases');
if (releasesResponse.ok) {
const releases = await releasesResponse.json();
// Calculate total downloads from all releases
let totalDownloads = 0;
releases.forEach(release => {
release.assets.forEach(asset => {
totalDownloads += asset.download_count;
});
});
// Store data for later animation
statsData = {
downloads: totalDownloads,
stars: stars
};
// Setup ScrollTrigger to animate when card is visible
setupStatsAnimation();
}
console.log('GitHub stats fetched successfully');
} catch (error) {
console.warn('Could not fetch GitHub stats:', error);
// Keep default values if fetch fails
}
}
function setupStatsAnimation() {
if (!statsData) return;
const saveStateCard = document.getElementById('savestate');
if (!saveStateCard) return;
// Create ScrollTrigger that fires once when card enters viewport
ScrollTrigger.create({
trigger: saveStateCard,
start: 'top 80%',
once: true,
onEnter: () => {
if (statsAnimationTriggered) return;
statsAnimationTriggered = true;
// Animate downloads count in badges
const downloadsElements = document.querySelectorAll('[data-i18n="savestate_downloads"]');
downloadsElements.forEach(el => {
animateNumber(el, statsData.downloads, 2000, '+ Downloads', '');
});
// Animate stars count in badges
const starsElements = document.querySelectorAll('[data-i18n="savestate_stars"]');
starsElements.forEach(el => {
animateNumber(el, statsData.stars, 2000, '+ GitHub Stars', '');
});
// Animate stats in demo section
const statNumbers = document.querySelectorAll('.stat-number');
if (statNumbers.length >= 2) {
animateNumber(statNumbers[0], statsData.downloads, 2000, '+', '');
animateNumber(statNumbers[1], statsData.stars, 2000, '+', '');
}
}
});
}
// ---- Initialize Everything ----
document.addEventListener('DOMContentLoaded', () => {
generateHexStream();
generateCodeBackground();
initScrollAnimations();
// Set initial active language in context menu
document.querySelectorAll('.lang-option').forEach(opt => {
opt.classList.toggle('active', opt.dataset.lang === currentLang);
});
// ---- Chaos Word Handler ----
initChaosWord();
// ---- Fetch GitHub Stats ----
fetchGitHubStats();
});
// ---- Chaos Word Effect (Outer Wilds style) ----
const ChaosEffect = {
letters: [],
flyAwayTargets: [],
isExploded: false,
isReturning: false,
originalPositions: [],
flyAwayAnimations: [],
init() {
const chaosWord = document.getElementById('chaos-word');
const initBtn = document.getElementById('init-profile-btn');
if (!chaosWord || !initBtn) return;
// Set data-content for glitch effect
initBtn.setAttribute('data-content', initBtn.innerText.trim());
this.letters = Array.from(chaosWord.querySelectorAll('.chaos-letter'));
// wrap content in inner spans for nested animation
this.letters.forEach(letter => {
if (!letter.querySelector('.chaos-inner')) {
const content = letter.textContent;
letter.innerHTML = `<span class="chaos-inner">${content}</span>`;
}
});
// Detect mobile to reduce explosion radius
const isMobile = window.innerWidth < 768;
const scale = isMobile ? 0.4 : 1;
// Fixed directions for each letter - scaled for mobile
const directions = [
{ x: -300 * scale, y: -200 * scale, rot: -180 }, // C - top left
{ x: 250 * scale, y: -250 * scale, rot: 120 }, // h - top right
{ x: -280 * scale, y: 180 * scale, rot: 90 }, // a - bottom left
{ x: 320 * scale, y: 150 * scale, rot: -150 }, // o - right
{ x: 80 * scale, y: 280 * scale, rot: 200 } // s - bottom
];
this.flyAwayTargets = this.letters.map((_, i) => directions[i] || directions[0]);
// Start flying away after a short delay to ensure page is loaded
setTimeout(() => this.flyAway(), 500);
// Button click handler - bring letters back (can be called anytime)
initBtn.addEventListener('click', (e) => {
e.preventDefault();
// Allow return even if explosion is still in progress
if (!this.isReturning) {
this.returnLetters();
}
});
},
flyAway() {
this.isExploded = true;
this.flyAwayAnimations = [];
this.letters.forEach((letter, i) => {
const inner = letter.querySelector('.chaos-inner');
const target = this.flyAwayTargets[i];
if (!inner) return;
// 1. Outer Animation: The Endless Drift (Linear)
// Moves much further to cover the entire page height/width over time
const driftTl = gsap.to(letter, {
x: target.x * 20, // Go much further (to infinity...)
y: target.y * 20,
rotation: target.rot * 10,
duration: 200, // Very long duration
ease: 'none',
force3D: true
});
// 2. Inner Animation: The Entropy (Slow, gradual separation)
// Slower duration and softer ease to avoid "explosion" feel
const explodeTl = gsap.to(inner, {
x: target.x,
y: target.y,
rotation: target.rot,
opacity: 0.6,
duration: 7, // Much slower initial movement (was 3)
delay: i * 0.2, // Slightly more staggered
ease: 'power1.out', // Softer deceleration
force3D: true
});
this.flyAwayAnimations.push(driftTl, explodeTl);
});
},
returnLetters() {
const chaosWord = document.getElementById('chaos-word');
const initBtn = document.getElementById('init-profile-btn');
// If already resolved, just scroll immediately
if (chaosWord.classList.contains('resolved')) {
gsap.to(window, {
duration: 1.2,
scrollTo: { y: '#projects', offsetY: -20 },
ease: 'power2.inOut'
});
return;
}
// Prevent multiple simultaneous returns
if (this.isReturning) return;
this.isReturning = true;
// Kill all ongoing fly-away animations
this.flyAwayAnimations.forEach(anim => {
if (anim) anim.kill();
});
this.flyAwayAnimations = [];
this.letters.forEach((letter, i) => {
const inner = letter.querySelector('.chaos-inner');
if (!inner) return;
// Animate both outer and inner back to 0
gsap.to([letter, inner], {
x: 0,
y: 0,
rotation: 0,
opacity: 1,
duration: 0.8,
delay: i * 0.05,
ease: 'back.out(1.7)',
onComplete: () => {
// Restore styles
letter.style.transform = '';
inner.style.transform = '';
inner.style.opacity = '';
}
});
});
const lettersReturnTime = 900;
// Sequence: Resolve -> Glitch Button -> Scroll
setTimeout(() => {
chaosWord.classList.add('resolved');
// Activate glitch on button
if (initBtn) {
initBtn.classList.add('btn-glitch-active');
// Wait while glitch plays, then scroll
setTimeout(() => {
initBtn.classList.remove('btn-glitch-active');
gsap.to(window, {
duration: 1.2,
scrollTo: { y: '#projects', offsetY: -20 },
ease: 'power2.inOut'
});
}, 800);
}
this.isExploded = false;
this.isReturning = false;
}, lettersReturnTime);
}
};
function initChaosWord() {
ChaosEffect.init();
}
// ---- Handle Resize ----
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
// Regenerate hex stream on resize
const hexStream = document.getElementById('hex-stream');
if (hexStream) {
hexStream.innerHTML = '';
generateHexStream();
}
// Refresh ScrollTrigger
ScrollTrigger.refresh();
}, 250);
});
// ========================================
// SAVESTATE INTERACTIVE DEMO
// ========================================
const SaveStateDemo = {
// State: 1 = empty, 2 = popup, 3 = one profile, 4 = final
currentState: 1,
// DOM Elements
elements: {
screenshot: null,
dropZone: null,
gameShortcut: null,
gameWrapper: null,
popupOverlay: null,
popupConfirm: null,
backupOverlay: null,
descriptionPanel: null,
demoHint: null
},
// Asset paths
assets: {
empty: 'assets/savestate-empty.webp',
oneProfile: 'assets/savestate-one-profile.webp',
full: 'assets/SaveState.webp'
},
init() {
// Get DOM elements
this.elements.screenshot = document.getElementById('app-screenshot');
this.elements.dropZone = document.getElementById('drop-zone');
this.elements.gameShortcut = document.getElementById('game-shortcut');
this.elements.gameWrapper = document.getElementById('game-shortcut-wrapper');
this.elements.popupOverlay = document.getElementById('game-popup-overlay');
this.elements.popupConfirm = document.getElementById('popup-confirm');
this.elements.backupOverlay = document.getElementById('backup-overlay');
this.elements.descriptionPanel = document.getElementById('description-panel');
this.elements.demoHint = document.getElementById('demo-hint');
// Check if elements exist
if (!this.elements.screenshot || !this.elements.gameShortcut) {
console.warn('SaveState demo elements not found');
return;
}
this.setupDragAndDrop();
this.setupPopup();
this.setupBackupButton();
// Activate drop zone
this.elements.dropZone.classList.add('active');
},
setupDragAndDrop() {
const { gameShortcut, dropZone, screenshot } = this.elements;
// Mouse drag events
gameShortcut.addEventListener('dragstart', (e) => {
gameShortcut.classList.add('dragging');
e.dataTransfer.setData('text/plain', 'game');
e.dataTransfer.effectAllowed = 'move';
// Fix for Chrome: create a custom drag image
const dragImage = gameShortcut.cloneNode(true);
dragImage.style.position = 'absolute';
dragImage.style.top = '-1000px';
document.body.appendChild(dragImage);
e.dataTransfer.setDragImage(dragImage, 55, 55);
// Clean up the temporary element after drag starts
setTimeout(() => {
document.body.removeChild(dragImage);
}, 0);
});
gameShortcut.addEventListener('dragend', (e) => {
e.preventDefault();
gameShortcut.classList.remove('dragging');
dropZone.classList.remove('drag-over');
});
// Make both dropZone and screenshot accept drops
const dropTargets = [dropZone, screenshot];
dropTargets.forEach(target => {
target.addEventListener('dragenter', (e) => {
if (this.currentState === 1) {
e.preventDefault();
e.stopPropagation();
dropZone.classList.add('drag-over');
}
});
target.addEventListener('dragover', (e) => {
if (this.currentState === 1) {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
}
});
target.addEventListener('dragleave', (e) => {
if (this.currentState === 1) {
// Check if we're really leaving (not just entering a child)
const rect = target.getBoundingClientRect();
if (e.clientX < rect.left || e.clientX >= rect.right ||
e.clientY < rect.top || e.clientY >= rect.bottom) {
dropZone.classList.remove('drag-over');
}
}
});
target.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.remove('drag-over');
if (this.currentState === 1) {
this.showPopup();
}
});
});
// Touch events for mobile
let touchStartX = 0;
let touchStartY = 0;
let isDragging = false;
let clone = null;
gameShortcut.addEventListener('touchstart', (e) => {
if (this.currentState !== 1) return;
isDragging = true;
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
// Create a visual clone for dragging
clone = gameShortcut.cloneNode(true);
clone.style.position = 'fixed';
clone.style.pointerEvents = 'none';
clone.style.zIndex = '10000';
clone.style.opacity = '0.8';
clone.style.transform = 'scale(0.9)';
clone.style.left = `${touchStartX - 55}px`;
clone.style.top = `${touchStartY - 55}px`;
document.body.appendChild(clone);
gameShortcut.classList.add('dragging');
e.preventDefault();
});
gameShortcut.addEventListener('touchmove', (e) => {
if (!isDragging || this.currentState !== 1) return;
const touch = e.touches[0];
const currentX = touch.clientX;
const currentY = touch.clientY;
// Move the clone
if (clone) {
clone.style.left = `${currentX - 55}px`;
clone.style.top = `${currentY - 55}px`;
}
// Check if over drop zone
const dropZoneRect = dropZone.getBoundingClientRect();
const isOverDropZone = (
currentX >= dropZoneRect.left &&
currentX <= dropZoneRect.right &&
currentY >= dropZoneRect.top &&
currentY <= dropZoneRect.bottom
);
if (isOverDropZone) {
dropZone.classList.add('drag-over');
} else {
dropZone.classList.remove('drag-over');
}
e.preventDefault();
});
const touchEnd = (e) => {
if (!isDragging || this.currentState !== 1) return;
const touch = e.changedTouches[0];
const endX = touch.clientX;
const endY = touch.clientY;
// Remove clone
if (clone) {
clone.remove();
clone = null;
}
gameShortcut.classList.remove('dragging');
// Check if dropped on drop zone
const dropZoneRect = dropZone.getBoundingClientRect();
const isOverDropZone = (
endX >= dropZoneRect.left &&
endX <= dropZoneRect.right &&
endY >= dropZoneRect.top &&
endY <= dropZoneRect.bottom
);
dropZone.classList.remove('drag-over');
if (isOverDropZone) {
this.showPopup();
}
isDragging = false;
};
gameShortcut.addEventListener('touchend', touchEnd);
gameShortcut.addEventListener('touchcancel', touchEnd);
},
setupPopup() {
const { popupConfirm } = this.elements;
popupConfirm.addEventListener('click', () => {
this.hidePopup();
this.transitionToState3();
});
},
setupBackupButton() {
const { backupOverlay } = this.elements;
backupOverlay.addEventListener('click', () => {
if (this.currentState === 3) {
this.transitionToState4();
}
});
},
showPopup() {
this.currentState = 2;
const { popupOverlay, gameWrapper, demoHint } = this.elements;
// Hide game shortcut
gsap.to(gameWrapper, {
opacity: 0,
scale: 0.8,
duration: 0.3,
onComplete: () => {
gameWrapper.classList.add('hidden');
}
});
// Show popup
popupOverlay.classList.remove('hidden');
gsap.fromTo(popupOverlay.querySelector('.game-popup'),
{ scale: 0.8, opacity: 0 },
{ scale: 1, opacity: 1, duration: 0.3, ease: 'back.out(1.5)' }
);
// Update hint
demoHint.innerHTML = '<span class="hint-icon">✓</span> <span>Click OK to continue</span>';
},
hidePopup() {
const { popupOverlay } = this.elements;
gsap.to(popupOverlay.querySelector('.game-popup'), {
scale: 0.9,
opacity: 0,
duration: 0.2,
onComplete: () => {
popupOverlay.classList.add('hidden');
}
});
},
transitionToState3() {
this.currentState = 3;
const { screenshot, backupOverlay, dropZone, demoHint } = this.elements;
// Hide drop zone
dropZone.classList.remove('active');
// Change screenshot with animation
gsap.to(screenshot, {
opacity: 0,
duration: 0.3,
onComplete: () => {
screenshot.src = this.assets.oneProfile;
gsap.to(screenshot, {
opacity: 1,
duration: 0.3
});
}
});