-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
737 lines (629 loc) · 20.8 KB
/
script.js
File metadata and controls
737 lines (629 loc) · 20.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
let currentStartIndex = 0;
/**
* Array holding all fetched Pokémon data.
* @type {Object[]}
*/
let allPokemon = [];
/**
* Variable holding wich tab (about or stats) in detail card is open.
*/
let activeLargeCardTab = "about";
let isCompareModeActive = false;
let selectedPokemonForCompare = [];
const generations = {
1: { label: "Kanto", startId: 1, endId: 151 },
2: { label: "Johto", startId: 152, endId: 251 },
3: { label: "Hoenn", startId: 252, endId: 386 },
4: { label: "Sinnoh", startId: 387, endId: 493 },
5: { label: "Unova", startId: 494, endId: 649 },
6: { label: "Kalos", startId: 650, endId: 721 },
7: { label: "Alola", startId: 722, endId: 809 },
8: { label: "Galar", startId: 810, endId: 905 },
9: { label: "Paldea", startId: 906, endId: 1025 },
};
const generationCache = {};
let activeGeneration = 1;
// /**
// * Initializes the application by setting up event listeners, rendering the loading template, and fetching the initial batch of Pokémon.
// */
// function init() {
// hideLoadMoreButton();
// addEventListeners();
// loadingTemplate();
// getPokemon(currentStartIndex);
// loadPokemonByGeneration(1);
// }
function init() {
hideLoadMoreButton();
addEventListeners();
loadPokemonByGeneration(1);
}
/**
* Renders the initial start-question overlay into the DOM.
* This is called on page load to ask the user the Pikachu-color quiz.
*/
function showStartQuestion() {
const overlayRef = document.getElementById("start-overlay");
overlayRef.innerHTML = startTemplate();
}
/**
* Reveals the "wrong answer" message container by removing its hidden CSS class.
*/
function showThatAnswerIsWrong() {
const wrongOverlay = document.getElementById("wrong-answer-container");
document.getElementById("wrong-answer-container").classList.remove("d_none_three");
document.getElementById("start-overlay").classList.add("d_none_three");
wrongOverlay.innerHTML = wrongAnswerTemplate();
}
/**
* Hides the "wrong answer" message container by re-applying its hidden CSS class.
*/
function backToStartQuestion() {
document.getElementById("wrong-answer-container").classList.add("d_none_three");
document.getElementById("start-overlay").classList.remove("d_none_three");
}
/**
* Checks the user's answer to the start question.
* If correct, hides the overlay and starts the app.
*
* @param {string} selectedColor – The color the user clicked (e.g. "yellow", "green", "blue").
*/
function checkAnswer(selectedColor) {
if (selectedColor === "yellow") {
document.getElementById("start-overlay").classList.add("d_none_three");
document.getElementById("nav-right").classList.remove("d_none_three");
document.getElementById("compare-controls").classList.remove("d_none_three");
init();
}
}
/**
* Inserts the loading spinner into the container element.
*/
function showLoadingSpinner() {
document.getElementById("loading-spinner-container").innerHTML = loadingTemplate();
}
/**
* Removes the loading spinner from the container element.
*/
function hideLoadingSpinner() {
document.getElementById("loading-spinner-container").innerHTML = "";
}
/**
* Fetches a batch of Pokémon data from the PokéAPI.
*
* @param {number} startIndex - The index (0-based) of the first Pokémon to fetch.
* @param {number} amount - The number of Pokémon to fetch in this batch.
* @returns {Promise<Object[]>} A promise that resolves to an array of Pokémon data objects.
*/
async function fetchPokemon(startIndex, amount) {
const requests = [];
for (let i = 0; i < amount; i++) {
const url = `https://pokeapi.co/api/v2/pokemon/${startIndex + 1 + i}`;
requests.push(fetch(url).then((response) => response.json()));
}
const result = await Promise.all(requests);
return result;
}
/**
* Loads and displays a batch of Pokémon cards in the main content container.
*
* Hides the "Load More" button and shows a loading spinner while fetching.
* On success, appends the rendered Pokémon cards and re-enables the "Load More" button.
* On failure, displays an error template.
*
* @param {number} startIndex - The index (0-based) from which to start loading Pokémon.
*/
async function getPokemon(startIndex) {
const container = document.getElementById("main-content-container");
hideLoadMoreButton();
showLoadingSpinner();
if (startIndex === 0) {
container.innerHTML = "";
}
try {
const pokemons = await fetchPokemon(startIndex, 151);
let html = "";
for (let i = 0; i < pokemons.length; i++) {
allPokemon.push(pokemons[i]);
const index = allPokemon.length - 1;
html += renderPokemonCard(pokemons[i], index);
}
container.innerHTML += html;
showLoadMoreButton();
} catch (error) {
console.error("Failed to load Pokémon:", error);
container.innerHTML = errorTemplate();
} finally {
hideLoadingSpinner();
}
}
/**
* Capitalizes the first character of a string.
*
* @param {string} text - The string to capitalize.
* @returns {string} The capitalized string.
*/
function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
/**
* Loads the next batch of Pokémon by incrementing the start index and fetching again.
* @returns {Promise<void>} A promise that resolves when the next batch is fetched.
*/
async function loadMorePokemon() {
currentStartIndex += 151;
await getPokemon(currentStartIndex);
}
/**
* Shows a large detailed card for the Pokémon at the given index.
*
* @param {number} index - The index of the Pokémon in the allPokemon array.
*/
function showLargeCard(index) {
const pokemon = allPokemon[index];
const card = document.getElementById("large-card-container");
card.classList.remove("d_none");
card.innerHTML = largeCardTemplate(pokemon, index);
if (activeLargeCardTab === "stats") {
showStats(index);
} else {
showAbout(index);
}
const closeButton = document.getElementById("large-card-close-button");
if (closeButton) {
closeButton.focus();
}
}
/**
* Shows the next Pokémon in the large card view, wrapping to the first if at the end.
*
* @param {number} index - The current index of the displayed Pokémon.
*/
function nextLargeCard(index) {
let newIndex = index + 1;
if (newIndex >= allPokemon.length) {
newIndex = 0;
}
showLargeCard(newIndex);
}
/**
* Shows the previous Pokémon in the large card view, wrapping to the last if at the beginning.
*
* @param {number} index - The current index of the displayed Pokémon.
*/
function prevLargeCard(index) {
let newIndex = index - 1;
if (newIndex < 0) {
newIndex = allPokemon.length - 1;
}
showLargeCard(newIndex);
}
/**
* Closes the large Pokémon detail card.
*/
function closeLargeCardOnX() {
const card = document.getElementById("large-card-container");
card.classList.add("d_none");
card.innerHTML = "";
}
/**
* Displays the "About" tab content for the Pokémon at the given index.
*
* @param {number} index - The index of the Pokémon in the allPokemon array.
*/
function showAbout(index, idPrefix = "large-card") {
activeLargeCardTab = "about";
const pokemon = allPokemon[index];
const aboutTab = document.getElementById(`${idPrefix}-about-tab-content`);
const statsTab = document.getElementById(`${idPrefix}-stats-tab-content`);
aboutTab.classList.remove("d_none_two");
statsTab.classList.add("d_none_two");
highlightAboutTab(idPrefix);
aboutTab.innerHTML = aboutTemplate(pokemon);
}
/**
* Displays the "Stats" tab content for the Pokémon at the given index.
*
* @param {number} index - The index of the Pokémon in the allPokemon array.
*/
function showStats(index, idPrefix = "large-card") {
activeLargeCardTab = "stats";
const pokemon = allPokemon[index];
const aboutTab = document.getElementById(`${idPrefix}-about-tab-content`);
const statsTab = document.getElementById(`${idPrefix}-stats-tab-content`);
aboutTab.classList.add("d_none_two");
statsTab.classList.remove("d_none_two");
highlightStatsTab(idPrefix);
statsTab.innerHTML = statsTemplate(pokemon);
}
/**
* Calculates the percentage width of a base stat relative to a maximum value.
*
* @param {number} baseStat - The base stat value.
* @returns {number} The percentage representation of the base stat.
*/
function calculateBaseStats(baseStat) {
const maxStat = 150;
const percent = (baseStat / maxStat) * 100;
return percent;
}
/**
* Filters the global allPokemon array for entries whose names include the given search value.
*
* @param {string} searchValue - The lowercase string to match against each Pokémon’s name.
* @returns {Object[]} An array of Pokémon objects whose names contain the search value.
*/
function filterPokemonByName(searchValue) {
const result = [];
for (let i = 0; i < allPokemon.length; i++) {
if (allPokemon[i].name.toLowerCase().includes(searchValue)) {
result.push(allPokemon[i]);
}
}
return result;
}
/**
* Renders a list of Pokémon cards into the main content container, then appends
* the "Back to Start" template at the end.
*
* @param {Object[]} pokemonList - Array of Pokémon objects to render.
*/
function renderSearchedPokemon(pokemonList) {
const container = document.getElementById("main-content-container");
container.innerHTML = "";
for (let i = 0; i < pokemonList.length; i++) {
const index = allPokemon.indexOf(pokemonList[i]);
container.innerHTML += renderPokemonCard(pokemonList[i], index);
}
container.innerHTML += searchGetBackToStartTemplate();
}
/**
* Handles the search action triggered by the user. Hides the "Load More" button,
* closes any open detail card, validates the query length, performs the filtering,
* and renders the results or error templates as needed.
*/
function searchPokemon() {
hideLoadMoreButton();
closeLargeCardOnX();
const searchField = document.getElementById("search-field");
const searchValue = searchField.value.toLowerCase();
const container = document.getElementById("main-content-container");
if (searchValue.length < 3) {
container.innerHTML = searchErrorTemplate();
return;
}
const searchedPokemon = filterPokemonByName(searchValue);
if (searchedPokemon.length === 0) {
container.innerHTML = searchNoPokemonFoundTemplate();
return;
}
renderSearchedPokemon(searchedPokemon);
}
/**
* Resets the search field and reloads the initial batch of Pokémon.
*/
function resetPokemonSearchIfWrongInput() {
document.getElementById("search-field").value = "";
loadPokemonByGeneration(activeGeneration);
}
/**
* Shows the "Load More" button if it exists.
*/
function showLoadMoreButton() {
const loadMoreButton = document.getElementById("load-more-button");
if (loadMoreButton) {
loadMoreButton.classList.remove("d_none");
}
}
/**
* Hides the "Load More" button if it exists.
*/
function hideLoadMoreButton() {
const loadMoreButton = document.getElementById("load-more-button");
if (loadMoreButton) {
loadMoreButton.classList.add("d_none");
}
}
/**
* Plays the cry sound of the Pokémon at the given index.
*
* @param {number} index - The index of the Pokémon in the allPokemon array.
*/
function playCrySound(index) {
const pokemon = allPokemon[index];
const cryUrl = pokemon.cries.latest;
const audio = new Audio(cryUrl);
audio.volume = 0.03;
audio.play();
}
/**
* Highlights the "About" tab button.
*/
function highlightAboutTab(idPrefix = "large-card") {
document.getElementById(`${idPrefix}-about-tab`).className = "tab_button active_tab";
document.getElementById(`${idPrefix}-stats-tab`).className = "tab_button";
}
/**
* Highlights the "Stats" tab button.
*/
function highlightStatsTab(idPrefix = "large-card") {
document.getElementById(`${idPrefix}-stats-tab`).classList.add("active_tab");
document.getElementById(`${idPrefix}-about-tab`).classList.remove("active_tab");
}
/**
* Attaches event listeners for loading more Pokémon, closing the large card with Escape key and start searching with Enter key.
*/
function addEventListeners() {
const loadMoreButton = document.getElementById("load-more-button");
if (loadMoreButton) {
loadMoreButton.addEventListener("click", loadMorePokemon);
}
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
closeLargeCardOnX();
}
});
document.getElementById("search-field").addEventListener("keydown", (event) => {
if (event.key === "Enter") {
searchPokemon();
}
});
document.getElementById("search-field").addEventListener("input", () => {
const value = document.getElementById("search-field").value.trim();
if (value === "") {
resetPokemonSearchIfWrongInput();
}
});
document.addEventListener("keydown", handleLargeCardKeyboard);
document.getElementById("main-content-container").addEventListener("click", cancelCompareModeOnMainContentClick);
}
/**
* Checks whether the large Pokémon detail card is currently visible.
*
* @returns {boolean} True if the large card is open, otherwise false.
*/
function isLargeCardOpen() {
const largeCardContainer = document.getElementById("large-card-container");
return largeCardContainer && !largeCardContainer.classList.contains("d_none");
}
/**
* Handles keyboard navigation while the large Pokémon detail card is open.
*
* Pressing Escape closes the detail card.
* Pressing Tab or Shift + Tab keeps the focus inside the detail card.
*
* @param {KeyboardEvent} event - The keyboard event triggered by the user.
*/
function handleLargeCardKeyboard(event) {
if (!isLargeCardOpen()) {
return;
}
if (event.key === "Escape") {
closeLargeCardOnX();
return;
}
if (event.key !== "Tab") {
return;
}
const focusableElements = getFocusableLargeCardElements();
if (focusableElements.length === 0) {
return;
}
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
if (event.shiftKey && document.activeElement === firstElement) {
event.preventDefault();
lastElement.focus();
return;
}
if (!event.shiftKey && document.activeElement === lastElement) {
event.preventDefault();
firstElement.focus();
}
}
/**
* Returns all keyboard-focusable elements inside the large Pokémon detail card.
*
* These elements are used by the focus trap to keep keyboard navigation
* inside the open detail card.
*
* @returns {NodeListOf<HTMLElement>} A list of focusable elements inside the large card.
*/
function getFocusableLargeCardElements() {
const largeCardContainer = document.getElementById("large-card-container");
if (!largeCardContainer) {
return [];
}
return largeCardContainer.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
}
/**
* Handles clicks on Pokémon cards.
*
* Opens the normal detail card unless compare mode is active.
*
* @param {number} index - The index of the clicked Pokémon in the allPokemon array.
*/
function handlePokemonCardClick(index) {
if (isCompareModeActive) {
selectPokemonForCompare(index);
return;
}
showLargeCard(index);
}
/**
* Starts the Pokémon compare mode and asks the user to select two Pokémon.
*/
function startCompareMode() {
isCompareModeActive = true;
selectedPokemonForCompare = [];
const message = document.getElementById("compare-message");
message.textContent = "Please select two Pokémon to compare.";
}
/**
* Adds a Pokémon to the current compare selection.
*
* Once two different Pokémon are selected, the compare overlay can be opened.
*
* @param {number} index - The index of the selected Pokémon in the allPokemon array.
*/
function selectPokemonForCompare(index) {
if (selectedPokemonForCompare.includes(index)) {
return;
}
selectedPokemonForCompare.push(index);
const message = document.getElementById("compare-message");
message.textContent = `${selectedPokemonForCompare.length} of 2 Pokémon selected.`;
if (selectedPokemonForCompare.length === 2) {
isCompareModeActive = false;
message.textContent = "";
showCompareOverlay();
}
}
/**
* Opens the compare overlay for the two selected Pokémon.
*/
function showCompareOverlay() {
const compareOverlayContainer = document.getElementById("compare-overlay-container");
const firstPokemon = allPokemon[selectedPokemonForCompare[0]];
const secondPokemon = allPokemon[selectedPokemonForCompare[1]];
compareOverlayContainer.innerHTML = compareOverlayTemplate(firstPokemon, secondPokemon);
compareOverlayContainer.classList.remove("d_none");
showStats(selectedPokemonForCompare[0], "compare-first");
showStats(selectedPokemonForCompare[1], "compare-second");
const closeButton = document.getElementById("compare-close-button");
if (closeButton) {
closeButton.focus();
}
}
/**
* Closes the compare overlay and resets the selected Pokémon.
*/
function closeCompareOverlay() {
const compareOverlayContainer = document.getElementById("compare-overlay-container");
compareOverlayContainer.classList.add("d_none");
compareOverlayContainer.innerHTML = "";
selectedPokemonForCompare = [];
}
/**
* Cancels the compare mode when the user clicks outside a Pokémon card.
*
* @param {MouseEvent} event - The click event inside the main content container.
*/
function cancelCompareModeOnMainContentClick(event) {
if (!isCompareModeActive) {
return;
}
if (event.target.closest(".pokemon_card")) {
return;
}
isCompareModeActive = false;
selectedPokemonForCompare = [];
const message = document.getElementById("compare-message");
message.textContent = "";
}
/**
* Closes the compare overlay when the user clicks on the overlay background.
*
* @param {MouseEvent} event - The click event inside the compare overlay.
*/
function closeCompareOverlayOnBackgroundClick(event) {
if (event.target.classList.contains("compare_overlay")) {
closeCompareOverlay();
}
}
/**
* Opens the generation selection overlay.
*/
function openGenerationOverlay() {
const container = document.getElementById("generation-overlay-container");
container.innerHTML = generationOverlayTemplate();
container.classList.remove("d_none");
}
/**
* Closes the generation selection overlay and removes its content from the DOM.
*/
function closeGenerationOverlay() {
const container = document.getElementById("generation-overlay-container");
container.classList.add("d_none");
container.innerHTML = "";
}
/**
* Closes the generation overlay when the user clicks on the overlay background.
*
* @param {MouseEvent} event - The click event inside the generation overlay.
*/
function closeGenerationOverlayOnBackgroundClick(event) {
if (event.target.classList.contains("generation_overlay")) {
closeGenerationOverlay();
}
}
/**
* Selects a Pokémon generation, closes the overlay and loads the selected generation.
*
* @param {number} generation - The selected generation number.
* @returns {Promise<void>} A promise that resolves when the generation has been loaded.
*/
async function selectGeneration(generation) {
closeGenerationOverlay();
await loadPokemonByGeneration(generation);
}
/**
* Calculates how many Pokémon belong to a generation.
*
* @param {number} generation - The generation number.
* @returns {number} The amount of Pokémon in the selected generation.
*/
function getGenerationAmount(generation) {
const generationData = generations[generation];
return generationData.endId - generationData.startId + 1;
}
/**
* Renders a list of Pokémon cards and stores it as the currently active Pokémon list.
*
* @param {Object[]} pokemonList - The Pokémon data objects to render.
*/
function renderPokemonList(pokemonList) {
const container = document.getElementById("main-content-container");
let html = "";
container.innerHTML = "";
allPokemon = pokemonList;
for (let i = 0; i < pokemonList.length; i++) {
html += renderPokemonCard(pokemonList[i], i);
}
container.innerHTML = html;
}
/**
* Loads and renders all Pokémon of a selected generation.
*
* If the generation was loaded before, the cached data is rendered.
* Otherwise the Pokémon are fetched from the PokéAPI, cached and then rendered.
*
* @param {number} generation - The generation number to load.
* @returns {Promise<void>} A promise that resolves when the generation has been loaded.
*/
async function loadPokemonByGeneration(generation) {
const generationData = generations[generation];
if (!generationData) {
return;
}
activeGeneration = generation;
hideLoadMoreButton();
showLoadingSpinner();
closeLargeCardOnX();
try {
if (generationCache[generation]) {
renderPokemonList(generationCache[generation]);
return;
}
const startIndex = generationData.startId - 1;
const amount = getGenerationAmount(generation);
const pokemons = await fetchPokemon(startIndex, amount);
generationCache[generation] = pokemons;
renderPokemonList(pokemons);
} catch (error) {
console.error("Failed to load generation:", error);
document.getElementById("main-content-container").innerHTML = errorTemplate();
} finally {
hideLoadingSpinner();
}
}