-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscript.js
More file actions
1002 lines (856 loc) · 31.8 KB
/
Copy pathscript.js
File metadata and controls
1002 lines (856 loc) · 31.8 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
// Board state
let allQuotes = [];
const profileCache = {};
let cards = [];
let searchTerm = '';
// Camera/View state
let offsetX = 0;
let offsetY = 0;
// Auto-scroll state
let autoScrollInterval = null;
let currentCardIndex = 0;
let isAutoScrolling = false;
let restartTimeout = null;
let canAutoScroll = false;
// Card dimensions (responsive)
function getCardDimensions() {
const width = window.innerWidth;
if (width <= 480) {
return { width: 240, height: 280, spacing: 350 };
} else if (width <= 768) {
return { width: 280, height: 320, spacing: 400 };
}
return { width: 450, height: 380, spacing: 500 };
}
let CARD_WIDTH = getCardDimensions().width;
let CARD_HEIGHT = getCardDimensions().height;
let GRID_SPACING = getCardDimensions().spacing;
// Mouse/Touch state
let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;
let dragStartOffsetX = 0;
let dragStartOffsetY = 0;
let lastTouchDistance = 0;
let rafPending = false;
// DOM elements
const board = document.getElementById('board');
const cardsContainer = document.getElementById('cards-container');
const loading = document.getElementById('loading');
const searchInput = document.getElementById('search-input');
const themeToggle = document.getElementById('theme-toggle');
// Fetch quotes from JSON
async function loadQuotes() {
try {
const response = await fetch('quotes.json');
allQuotes = await response.json();
// Generate cards
generateCards();
loading.classList.add('hide');
} catch (error) {
console.error('Error loading quotes:', error);
loading.textContent = 'Error loading quotes';
}
}
// Filter quotes based on search term
function getFilteredQuotes() {
if (!searchTerm) return allQuotes;
const term = searchTerm.toLowerCase();
return allQuotes.filter(q =>
q.quote.toLowerCase().includes(term) ||
q.githubUsername.toLowerCase().includes(term) ||
(q.date && q.date.includes(term))
);
}
// Generate card positions in a grid
function generateCards() {
cards = [];
const filteredQuotes = getFilteredQuotes();
// Responsive column count based on screen width
const width = window.innerWidth;
let cols;
if (width <= 480) {
cols = 2; // Two columns on mobile
} else if (width <= 768) {
cols = 2; // Two columns on tablet
} else {
cols = 4; // Four columns on desktop
}
const rows = Math.ceil(filteredQuotes.length / cols);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const cardIndex = row * cols + col;
if (cardIndex >= filteredQuotes.length) {
continue;
}
const quote = filteredQuotes[cardIndex];
const x = col * GRID_SPACING;
const y = row * GRID_SPACING;
const rotation = (Math.sin(col * 1.5) * Math.cos(row * 2) * 0.05);
cards.push({
x,
y,
quote,
rotation,
width: CARD_WIDTH,
height: CARD_HEIGHT,
element: null
});
}
}
createCardElements();
centerAllCards();
updateCardPositions();
// Start auto-scroll if cards fit on screen
checkAndStartAutoScroll();
}
// Create card DOM elements
function createCardElements() {
cardsContainer.innerHTML = '';
cards.forEach((card, cardIndex) => {
const cardEl = document.createElement('div');
cardEl.className = 'quote-card';
cardEl.innerHTML = `
<div class="card-inner">
<div class="card-front">
<button class="copy-btn" title="Copy quote">📋</button>
<div class="quote-text">"${card.quote.quote}"</div>
<div class="quote-author">— @${card.quote.githubUsername}</div>
<div class="flip-hint">Click to flip</div>
</div>
<div class="card-back">
<div class="profile">
<a href="https://github.com/${card.quote.githubUsername}" target="_blank" class="profile-avatar-link">
<img class="profile-avatar" src="https://github.com/${card.quote.githubUsername}.png" alt="${card.quote.githubUsername}" onerror="this.src='img/pull-requotes.png'; this.classList.add('placeholder');">
</a>
<div class="profile-info">
<a href="https://github.com/${card.quote.githubUsername}" target="_blank" class="profile-name-link">
<div class="profile-name">Loading...</div>
</a>
</div>
</div>
${card.quote.date ? `<div class="quote-date">${card.quote.date}</div>` : ''}
</div>
</div>
`;
// Copy button functionality
const copyBtn = cardEl.querySelector('.copy-btn');
copyBtn.addEventListener('click', (e) => {
e.stopPropagation();
navigator.clipboard.writeText(card.quote.quote);
copyBtn.textContent = '✓';
setTimeout(() => copyBtn.textContent = '📋', 1500);
});
// Card flip functionality
cardEl.addEventListener('click', (e) => {
if (!e.target.closest('.copy-btn, .profile-avatar-link, .profile-name-link')) {
cardEl.classList.toggle('flipped');
}
});
// Add staggered animation delay
cardEl.style.animationDelay = `${cardIndex * 0.1}s`;
card.element = cardEl;
cardsContainer.appendChild(cardEl);
});
// Fetch GitHub profiles
fetchProfiles();
}
// Focus on a random card on load
function focusRandomCard() {
const randomIndex = Math.floor(Math.random() * cards.length);
const randomCard = cards[randomIndex];
// Center the board view on the random card
const windowCenterX = window.innerWidth / 2;
const windowCenterY = window.innerHeight / 2;
// Calculate offset to center the card
offsetX = windowCenterX - (randomCard.x + CARD_WIDTH / 2);
offsetY = windowCenterY - (randomCard.y + CARD_HEIGHT / 2);
}
// Center view to show all cards
function centerAllCards() {
if (cards.length === 0) return;
let minX = Infinity, maxX = -Infinity;
let minY = Infinity, maxY = -Infinity;
cards.forEach(card => {
minX = Math.min(minX, card.x);
maxX = Math.max(maxX, card.x + card.width);
minY = Math.min(minY, card.y);
maxY = Math.max(maxY, card.y + card.height);
});
const centerX = (minX + maxX) / 2;
const centerY = (minY + maxY) / 2;
const windowCenterX = window.innerWidth / 2;
const windowCenterY = window.innerHeight / 2;
offsetX = windowCenterX - centerX;
offsetY = windowCenterY - centerY;
}
// Fetch GitHub profiles and repos
async function fetchProfiles() {
for (const card of cards) {
const username = card.quote.githubUsername;
const profileNameEl = card.element.querySelector('.profile-name');
// If profile is cached, display it immediately
if (profileCache[username]) {
const profile = profileCache[username];
if (profileNameEl) {
const stats = [];
stats.push(`⭐ ${profile.totalStars}`);
stats.push(`📦 ${profile.publicRepos}`);
if (profile.topLanguages.length > 0) {
stats.push(`🗿 ${profile.topLanguages.join(', ')}`);
}
profileNameEl.innerHTML = `<div class="profile-display-name">${profile.name || username}</div><div class="profile-stats">${stats.join(' • ')}</div>`;
}
} else {
// Only fetch if not cached
try {
// Fetch user profile
const userResponse = await fetch(`https://api.github.com/users/${username}`);
const profile = await userResponse.json();
// Fetch user repos for stars and languages
const reposResponse = await fetch(`https://api.github.com/users/${username}/repos?sort=stars&per_page=100`);
const repos = await reposResponse.json();
// Calculate total stars and collect languages
let totalStars = 0;
const languages = new Set();
if (Array.isArray(repos)) {
repos.forEach(repo => {
if (repo.stargazers_count) {
totalStars += repo.stargazers_count;
}
if (repo.language) {
languages.add(repo.language);
}
});
}
profile.totalStars = totalStars;
profile.topLanguages = Array.from(languages).slice(0, 3);
profile.publicRepos = profile.public_repos || 0;
profileCache[username] = profile;
// Update card with profile info
if (profileNameEl) {
const stats = [];
stats.push(`⭐ ${profile.totalStars}`);
stats.push(`📦 ${profile.publicRepos}`);
if (profile.topLanguages.length > 0) {
stats.push(`🗿 ${profile.topLanguages.join(', ')}`);
}
profileNameEl.innerHTML = `<div class="profile-display-name">${profile.name || username}</div><div class="profile-stats">${stats.join(' • ')}</div>`;
}
} catch (error) {
console.error(`Error fetching profile for ${username}:`, error);
// Update with fallback if API fails
if (profileNameEl) {
profileNameEl.innerHTML = `<div class="profile-display-name">${username}</div>`;
}
}
}
}
}
// Update card positions based on offset using transform (no layout reflow)
function updateCardPositions() {
for (const card of cards) {
if (card.element) {
const x = card.x + offsetX;
const y = card.y + offsetY;
card.element.style.transform = `translate(${x}px, ${y}px) rotate(${card.rotation}rad)`;
card.element.style.setProperty('--rotation', `${(card.rotation * 180) / Math.PI}deg`);
}
}
}
// Throttled version for drag events
function schedulePositionUpdate() {
if (!rafPending) {
rafPending = true;
requestAnimationFrame(() => {
rafPending = false;
updateCardPositions();
});
}
}
// Mouse events
board.addEventListener('mousedown', (e) => {
stopAutoScroll(); // Stop auto-scroll when user interacts
isDragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
dragStartOffsetX = offsetX;
dragStartOffsetY = offsetY;
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
const deltaX = e.clientX - dragStartX;
const deltaY = e.clientY - dragStartY;
offsetX = dragStartOffsetX + deltaX;
offsetY = dragStartOffsetY + deltaY;
schedulePositionUpdate();
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
checkAndReturnToCards();
});
// Touch events
board.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
stopAutoScroll(); // Stop auto-scroll when user interacts
isDragging = true;
dragStartX = e.touches[0].clientX;
dragStartY = e.touches[0].clientY;
dragStartOffsetX = offsetX;
dragStartOffsetY = offsetY;
}
}, { passive: true });
board.addEventListener('touchmove', (e) => {
if (isDragging && e.touches.length === 1) {
const deltaX = e.touches[0].clientX - dragStartX;
const deltaY = e.touches[0].clientY - dragStartY;
offsetX = dragStartOffsetX + deltaX;
offsetY = dragStartOffsetY + deltaY;
schedulePositionUpdate();
}
}, { passive: true });
board.addEventListener('touchend', () => {
isDragging = false;
checkAndReturnToCards();
}, { passive: true });
// Handle window resize
window.addEventListener('resize', () => {
const dimensions = getCardDimensions();
CARD_WIDTH = dimensions.width;
CARD_HEIGHT = dimensions.height;
GRID_SPACING = dimensions.spacing;
// Regenerate cards with new dimensions
generateCards();
});
// Create seasonal emoji background pattern
function createEmojiPattern() {
const emojiPattern = document.createElement('div');
emojiPattern.id = 'emoji-pattern';
emojiPattern.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
z-index: 0;
overflow: hidden;
opacity: 0.05;
`;
const season = detectSeason();
let emojis;
switch (season) {
case 'autumn':
emojis = ['🍂', '🍁'];
break;
case 'winter':
emojis = ['❄️', '⛄'];
break;
case 'spring':
emojis = ['🌸', '🌺'];
break;
case 'summer':
emojis = ['🌻', '☀️'];
break;
case 'songkran':
emojis = ['💧', '🔫'];
break;
case 'lunar':
emojis = ['🏮', '🎆'];
break;
default:
emojis = ['💻', '⭐'];
}
const spacing = 60;
const cols = Math.ceil(window.innerWidth / spacing) + 1;
const rows = Math.ceil(window.innerHeight / spacing) + 1;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const emoji = document.createElement('span');
emoji.textContent = emojis[Math.floor(Math.random() * emojis.length)];
const rotation = (Math.random() - 0.5) * 60;
const ox = (i % 2) * 30;
emoji.style.cssText = `
position: absolute;
left: ${j * spacing + ox}px;
top: ${i * spacing}px;
font-size: 20px;
user-select: none;
transform: rotate(${rotation}deg);
`;
emojiPattern.appendChild(emoji);
}
}
document.body.insertBefore(emojiPattern, document.body.firstChild);
}
function detectSeason() {
const now = new Date();
const month = now.getMonth() + 1;
const day = now.getDate();
if ((month === 1 && day >= 21) || (month === 2 && day <= 20)) return 'lunar';
if (month === 4 && day >= 13 && day <= 17) return 'songkran';
if (month >= 3 && month <= 5) return 'spring';
if (month >= 6 && month <= 8) return 'summer';
if (month >= 9 && month <= 11) return 'autumn';
return 'winter';
}
// Theme toggle
function initTheme() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'light') {
document.body.classList.add('light-mode');
}
}
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('light-mode');
const isLight = document.body.classList.contains('light-mode');
localStorage.setItem('theme', isLight ? 'light' : 'dark');
});
// Keyboard navigation
document.addEventListener('keydown', (e) => {
if (e.target === searchInput) return;
const step = 100;
switch(e.key) {
case 'ArrowUp':
e.preventDefault();
stopAutoScroll(); // Stop auto-scroll when user navigates
offsetY += step;
updateCardPositions();
break;
case 'ArrowDown':
e.preventDefault();
stopAutoScroll();
offsetY -= step;
updateCardPositions();
break;
case 'ArrowLeft':
e.preventDefault();
stopAutoScroll();
offsetX += step;
updateCardPositions();
break;
case 'ArrowRight':
e.preventDefault();
stopAutoScroll();
offsetX -= step;
updateCardPositions();
break;
case ' ':
e.preventDefault();
stopAutoScroll();
focusRandomCard();
updateCardPositions();
break;
case 'Escape':
searchInput.value = '';
searchTerm = '';
generateCards();
break;
case '/':
e.preventDefault();
searchInput.focus();
break;
}
});
// Search functionality
searchInput.addEventListener('input', (e) => {
searchTerm = e.target.value;
generateCards();
});
// Seasonal particle burst on click
function createSeasonalBurst(x, y) {
const season = particles.season;
for (let i = 0; i < 15; i++) {
const particle = document.createElement('div');
particle.style.cssText = `
position: fixed;
left: ${x}px;
top: ${y}px;
width: 8px;
height: 8px;
pointer-events: none;
z-index: 100;
animation: burst-fall 2s linear forwards;
`;
switch (season) {
case 'autumn':
particle.textContent = ['🍂', '🍁'][Math.floor(Math.random() * 2)];
break;
case 'winter':
particle.textContent = ['❄️', '⛄'][Math.floor(Math.random() * 2)];
break;
case 'spring':
particle.textContent = ['🌸', '🌺'][Math.floor(Math.random() * 2)];
break;
case 'summer':
particle.textContent = ['🌻', '☀️'][Math.floor(Math.random() * 2)];
break;
case 'songkran':
particle.textContent = ['💧', '🔫'][Math.floor(Math.random() * 2)];
break;
case 'lunar':
particle.textContent = ['🏮', '🎆'][Math.floor(Math.random() * 2)];
break;
}
particle.style.fontSize = '16px';
particle.style.animationDelay = Math.random() * 0.5 + 's';
particle.style.setProperty('--dx', (Math.random() - 0.5) * 200 + 'px');
document.body.appendChild(particle);
setTimeout(() => particle.remove(), 2500);
}
}
// Background single-click for seasonal particles
board.addEventListener('click', (e) => {
if (e.target === board || e.target === cardsContainer) {
particles.addParticles();
}
});
// Auto-scroll functionality
function checkAndStartAutoScroll() {
stopAutoScroll();
if (cards.length === 0) return;
// Check if all cards can fit on screen
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
let minX = Infinity, maxX = -Infinity;
let minY = Infinity, maxY = -Infinity;
cards.forEach(card => {
minX = Math.min(minX, card.x);
maxX = Math.max(maxX, card.x + card.width);
minY = Math.min(minY, card.y);
maxY = Math.max(maxY, card.y + card.height);
});
const totalWidth = maxX - minX;
const totalHeight = maxY - minY;
// Enable auto-scroll for all screen sizes if there are more than 2 cards
if (cards.length > 2) {
canAutoScroll = true;
startAutoScroll();
} else {
canAutoScroll = false;
}
}
function startAutoScroll() {
if (isAutoScrolling || cards.length <= 1) return;
isAutoScrolling = true;
currentCardIndex = 0;
autoScrollInterval = setInterval(() => {
// Check if all cards are already visible
if (areAllCardsVisible()) {
stopAutoScroll();
return;
}
focusOnCard(currentCardIndex);
currentCardIndex = (currentCardIndex + 1) % cards.length;
}, 4000); // Change card every 4 seconds
}
function stopAutoScroll() {
if (autoScrollInterval) {
clearInterval(autoScrollInterval);
autoScrollInterval = null;
}
isAutoScrolling = false;
// Clear any existing restart timeout
if (restartTimeout) {
clearTimeout(restartTimeout);
}
// Set timeout to restart auto-scroll after 5 seconds of inactivity
if (canAutoScroll) {
restartTimeout = setTimeout(() => {
startAutoScroll();
}, 5000);
}
}
function focusOnCard(index) {
if (index >= cards.length) return;
const card = cards[index];
const windowCenterX = window.innerWidth / 2;
const windowCenterY = window.innerHeight / 2;
// Calculate offset to center the card with smooth transition
const targetOffsetX = windowCenterX - (card.x + CARD_WIDTH / 2);
const targetOffsetY = windowCenterY - (card.y + CARD_HEIGHT / 2);
// Smooth transition
const startOffsetX = offsetX;
const startOffsetY = offsetY;
const duration = 2000; // 2 second transition
const startTime = Date.now();
function animate() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
// Smoother easing function (ease-in-out)
const easeProgress = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
offsetX = startOffsetX + (targetOffsetX - startOffsetX) * easeProgress;
offsetY = startOffsetY + (targetOffsetY - startOffsetY) * easeProgress;
updateCardPositions();
if (progress < 1) {
requestAnimationFrame(animate);
}
}
animate();
}
// Check if user is in empty space and return to cards
function checkAndReturnToCards() {
if (cards.length === 0) return;
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// Check if any card is visible in viewport
let hasVisibleCard = false;
for (const card of cards) {
const cardLeft = card.x + offsetX;
const cardRight = cardLeft + card.width;
const cardTop = card.y + offsetY;
const cardBottom = cardTop + card.height;
// Check if card overlaps with viewport
if (cardRight > 0 && cardLeft < viewportWidth &&
cardBottom > 0 && cardTop < viewportHeight) {
hasVisibleCard = true;
break;
}
}
// If no cards are visible, smoothly return to center immediately
if (!hasVisibleCard) {
const startOffsetX = offsetX;
const startOffsetY = offsetY;
// Calculate target position to center all cards
let minX = Infinity, maxX = -Infinity;
let minY = Infinity, maxY = -Infinity;
cards.forEach(card => {
minX = Math.min(minX, card.x);
maxX = Math.max(maxX, card.x + card.width);
minY = Math.min(minY, card.y);
maxY = Math.max(maxY, card.y + card.height);
});
const centerX = (minX + maxX) / 2;
const centerY = (minY + maxY) / 2;
const windowCenterX = window.innerWidth / 2;
const windowCenterY = window.innerHeight / 2;
const targetOffsetX = windowCenterX - centerX;
const targetOffsetY = windowCenterY - centerY;
const duration = 1000;
const startTime = Date.now();
function animate() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeProgress = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
offsetX = startOffsetX + (targetOffsetX - startOffsetX) * easeProgress;
offsetY = startOffsetY + (targetOffsetY - startOffsetY) * easeProgress;
updateCardPositions();
if (progress < 1) {
requestAnimationFrame(animate);
}
}
animate();
}
}
// Check if all cards are visible in viewport
function areAllCardsVisible() {
if (cards.length === 0) return true;
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
for (const card of cards) {
const cardLeft = card.x + offsetX;
const cardRight = cardLeft + card.width;
const cardTop = card.y + offsetY;
const cardBottom = cardTop + card.height;
// If any card is not fully visible, return false
if (cardLeft < 0 || cardRight > viewportWidth ||
cardTop < 0 || cardBottom > viewportHeight) {
return false;
}
}
return true;
}
// Particle System
class ParticleSystem {
constructor() {
this.canvas = document.getElementById('particles');
this.ctx = this.canvas.getContext('2d');
this.particles = [];
this.season = this.detectSeason();
this.resize();
this.init();
window.addEventListener('resize', () => this.resize());
}
detectSeason() {
const now = new Date();
const month = now.getMonth() + 1;
const day = now.getDate();
// Lunar New Year (approx Jan 21 - Feb 20)
if ((month === 1 && day >= 21) || (month === 2 && day <= 20)) {
return 'lunar';
}
// Songkran/Pi Mai Lao (Apr 13-17)
if (month === 4 && day >= 13 && day <= 17) {
return 'songkran';
}
// Seasons
if (month >= 3 && month <= 5) return 'spring';
if (month >= 6 && month <= 8) return 'summer';
if (month >= 9 && month <= 11) return 'autumn';
return 'winter';
}
resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
init() {
this.particles = [];
this.animate();
}
addParticles() {
// Limit total particles to prevent performance issues
if (this.particles.length > 60) {
this.particles.splice(0, 12); // Remove oldest particles
}
for (let i = 0; i < 12; i++) {
this.particles.push(this.createParticle());
}
}
createParticle() {
const particle = {
x: Math.random() * this.canvas.width,
y: -20,
vx: (Math.random() - 0.5) * 2,
vy: Math.random() * 2 + 1,
rotation: Math.random() * Math.PI * 2,
rotationSpeed: (Math.random() - 0.5) * 0.1,
size: Math.random() * 8 + 4,
opacity: Math.random() * 0.8 + 0.2
};
switch (this.season) {
case 'autumn':
particle.color = ['#ff6b35', '#f7931e', '#ffb347', '#d2691e'][Math.floor(Math.random() * 4)];
particle.shape = 'leaf';
break;
case 'winter':
particle.color = '#ffffff';
particle.shape = 'snowflake';
particle.vy *= 0.5;
break;
case 'spring':
particle.color = ['#ffb6c1', '#ffc0cb', '#ffffff'][Math.floor(Math.random() * 3)];
particle.shape = 'petal';
break;
case 'summer':
particle.color = ['#ffd700', '#ffb347', '#ff8c00'][Math.floor(Math.random() * 3)];
particle.shape = 'sunflower';
particle.vy *= 0.8;
break;
case 'songkran':
particle.color = ['#00bfff', '#1e90ff', '#87ceeb'][Math.floor(Math.random() * 3)];
particle.shape = 'water';
particle.vy *= 3;
particle.size *= 1.5;
break;
case 'lunar':
particle.color = ['#ff0000', '#ffd700', '#ff4500'][Math.floor(Math.random() * 3)];
particle.shape = 'lantern';
particle.vy *= 0.3;
particle.vx = (Math.random() - 0.5) * 0.5;
break;
}
return particle;
}
drawParticle(particle) {
this.ctx.save();
this.ctx.globalAlpha = particle.opacity;
this.ctx.translate(particle.x, particle.y);
this.ctx.rotate(particle.rotation);
this.ctx.fillStyle = particle.color;
switch (particle.shape) {
case 'leaf':
this.ctx.beginPath();
this.ctx.ellipse(0, 0, particle.size/3, particle.size/2, 0, 0, Math.PI * 2);
this.ctx.fill();
break;
case 'snowflake':
this.ctx.strokeStyle = particle.color;
this.ctx.lineWidth = 1;
for (let i = 0; i < 6; i++) {
this.ctx.beginPath();
this.ctx.moveTo(0, 0);
this.ctx.lineTo(0, -particle.size/2);
this.ctx.stroke();
this.ctx.rotate(Math.PI / 3);
}
break;
case 'petal':
this.ctx.beginPath();
this.ctx.ellipse(0, -particle.size/4, particle.size/4, particle.size/2, 0, 0, Math.PI * 2);
this.ctx.fill();
break;
case 'sunflower':
this.ctx.beginPath();
this.ctx.arc(0, 0, particle.size/3, 0, Math.PI * 2);
this.ctx.fill();
for (let i = 0; i < 8; i++) {
this.ctx.beginPath();
this.ctx.ellipse(0, -particle.size/2, particle.size/6, particle.size/3, 0, 0, Math.PI * 2);
this.ctx.fill();
this.ctx.rotate(Math.PI / 4);
}
break;
case 'water':
this.ctx.beginPath();
this.ctx.moveTo(0, -particle.size/2);
this.ctx.quadraticCurveTo(-particle.size/3, 0, 0, particle.size/2);
this.ctx.quadraticCurveTo(particle.size/3, 0, 0, -particle.size/2);
this.ctx.fill();
break;
case 'lantern':
this.ctx.fillRect(-particle.size/3, -particle.size/2, particle.size*2/3, particle.size);
this.ctx.fillRect(-particle.size/4, -particle.size/2-2, particle.size/2, 2);
break;
}
this.ctx.restore();
}
animate() {
this.frameCount = (this.frameCount || 0) + 1;
// Only update every other frame for better performance
if (this.frameCount % 2 === 0) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (let i = this.particles.length - 1; i >= 0; i--) {
const particle = this.particles[i];
particle.x += particle.vx;
particle.y += particle.vy;
particle.rotation += particle.rotationSpeed;
if (particle.y > this.canvas.height + 20 ||
particle.x < -20 || particle.x > this.canvas.width + 20) {
this.particles.splice(i, 1);
} else {
this.drawParticle(particle);
}
}
}
requestAnimationFrame(() => this.animate());
}
}
// Initialize
initTheme();
createEmojiPattern();
loadQuotes();
const particles = new ParticleSystem();
// Test function for all seasons
window.testSeason = (season) => {
particles.season = season;
particles.init();
// Update emoji background too
document.getElementById('emoji-pattern').remove();
window.detectSeason = () => season;
createEmojiPattern();
};
// Auto-cycle through all seasons for testing
window.testAllSeasons = () => {
const seasons = ['autumn', 'winter', 'spring', 'summer', 'songkran', 'lunar'];
let i = 0;
setInterval(() => {
console.log('Testing:', seasons[i]);
testSeason(seasons[i]);
i = (i + 1) % seasons.length;