-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
473 lines (440 loc) · 15 KB
/
script.js
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
const searchInput =document.getElementById('search-input');
const container=document.getElementById('container');
const searchButton =document.getElementById('search-button');
const pokemonName =document.getElementById('pokemon-name');
const pokemonId =document.getElementById('pokemon-id');
const pokemonWeight =document.getElementById('weight');
const pokemonHeight =document.getElementById('height');
const imgView =document.getElementById('sprite');
const pokemonType =document.getElementById('types');
const hp =document.getElementById('hp');
const attack =document.getElementById('attack');
const defense =document.getElementById('defense');
const specialAttack =document.getElementById('special-attack');
const specialDefense =document.getElementById('special-defense');
const speed =document.getElementById('speed');
const spinner =document.getElementById('loader');
const bulb=document.getElementById('bulb');
const info=document.getElementById('info');
const animationBtn=document.getElementById('gif-btn');
const normalBtn=document.getElementById('normal-btn');
const dropDownCont =document.getElementById('drop-down-cont');
const maxBtn=document.getElementById('maximize');
const minBtn=document.getElementById('manimize');
const t_loader=document.getElementById('t-loader');
const noAnimationMsg=document.getElementById('no-anim');
const audioSvgCont=document.getElementById('audio-svg-cont');
const toolTip=document.getElementById('tooltip');
const dialogElement=document.getElementById('dialog-ele');
const acceptDialogBtn=document.getElementById('dialog-ele').children[1].children[0];
const rejectDialogBtn=document.getElementById('dialog-ele').children[1].children[1];
let isLoading = false;
let isGlowing=false;
let globalInput;
let globalPokemonName;
let input;
let animatedGifLink;
let normalImgLink;
let globalPokemonId;
const evolExitBtn=document.getElementById('exit-btn-cont').children[1];
const evolCont =document.getElementById('evolution-cont');
const evolChainCont=document.getElementById('evolution-chain-cont');
const errImageContainer=document.getElementById('err');
let isNewImageLoaded=false;
const fetchApi ='https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/';
const fetchApi2='https://pokeapi.co/api/v2/pokemon/';
const fetchApi3='https://pokeapi.co/api/v2/pokemon/?offset=0&limit=1302';
const fetchCrySoundApi= "https://raw.githubusercontent.com/PokeAPI/cries/main/cries/pokemon/latest/"
let data=[];
let idData=[];
const cacheEvolData={};
const fetchData=async()=>{
try{
t_loader.hidden=false;
const response =await fetch(fetchApi3);
const result =await response.json();
data=result.results;
idData=data.map(pokemon=>pokemon.url.slice(34).replace('/',''));
t_loader.hidden=true;
container.hidden=false;
showToolTip();
}catch(e){
t_loader.hidden=true;
container.hidden=true;
errImageContainer.classList.replace('evol-hide','evol-show');
return;
}
}
const showToolTip=()=>{
setTimeout(()=>{
toolTip.style.visibility='hidden';
toolTip.style.opacity='0';
setTimeout(()=>{
toolTip.style.visibility='visible';
toolTip.style.opacity='1';
setTimeout(()=>{
toolTip.style.visibility='hidden';
toolTip.style.opacity='0';
},1800)
},1800)
},1800)
}
window.onload=()=>{
fetchData();
}
const spinnerOnandOff=()=>{
if(isLoading){
spinner.style.animation='spin 1s ease-in-out infinite';
spinner.style.display='block';
}else{
spinner.style.animation='stop-spin 1s ease-in-out infinite';
spinner.style.display='none';
}
}
bulb.addEventListener('click',()=>{
isGlowing=!isGlowing;
isGlowing ? info.style.display='block' : info.style.display='none';
})
const updateStats=(stats)=>{
const stat_array =[];
for(let st of stats){
stat_array.push(st.base_stat)
}
const avail_stats=[hp,attack,defense,specialAttack,specialDefense,speed];
avail_stats.forEach((stat,index)=>{
stat.textContent=stat_array[index];
})
isNewImageLoaded=true;
spinnerOnandOff();
}
const updateNameAndId=(name,id)=>{
pokemonName.textContent=name.toUpperCase();
pokemonId.textContent=`#${id}`;
}
const heightAndWeight=(height,weight)=>{
pokemonWeight.textContent=`Weight: ${weight}`;
pokemonHeight.textContent=`Height: ${height}`;
}
const updateImageAndTypes=(types,sprites,pokemon)=>{
normalImgLink=sprites.front_default;
imgView.src=sprites.front_default;
imgView.alt=pokemon;
for(let num of types){
const {name}=num.type;
pokemonType.innerHTML+=`<div class='${name.toLowerCase()} cent'>${name.toUpperCase()}</div>`
}
}
const filterInput=(input)=>input.replace(/[^a-zA-Z0-9-]/ig,'').toLowerCase();
const updateUI=async()=>{
animationBtn.hidden=true;
noAnimationMsg.hidden=true;
audioSvgCont.classList.replace('evol-show','evol-hide');
normalize();
if(searchInput.value===''){
return;
}
if(Number(searchInput.value)>10277){
alert('provided id is greater than pokemon count try less than 10277')
return;
}
pokemonType.innerHTML=''
isLoading =true;
spinnerOnandOff();
input = filterInput(searchInput.value);
globalInput=input;
dropDownCont.classList.replace('show','dd-hide');
if(input===''){
spinner.style.animation='stop-spin 1s ease-in-out infinite';
spinner.style.display='none';
return;
}
try{
const response = await fetch(fetchApi+input);
const result = await response.json();
isLoading=false;
const {height,id,name,sprites,stats,types,weight}=result;
globalPokemonName=name;
globalPokemonId=id;
updateNameAndId(name,id);
heightAndWeight(height,weight);
updateImageAndTypes(types,sprites,name);
updateStats(stats);
normalBtn.hidden=true;
animationBtn.hidden=false;
audioSvgCont.classList.replace('evol-hide','evol-show');
}catch(e){
spinner.style.animation='stop-spin 1s ease-in-out infinite';
spinner.style.display='none';
alert('error occured or undetermined id')
}
}
animationBtn.addEventListener('click',async ()=>{
isLoading=true;
spinnerOnandOff();
try{
const response2 =await fetch(fetchApi2+globalInput);
const result2=await response2.json();
const link=result2.sprites.versions['generation-v']['black-white'].animated.front_default;
animatedGifLink=link;
}catch(e){
isLoading=false;
spinnerOnandOff();
alert('error with animation try after some time');
return;
}
if(!animatedGifLink){
isLoading=false;
spinnerOnandOff();
noAnimationMsg.hidden=false;
return;
}
imgView.style.width='107px';
imgView.src='';
imgView.src=animatedGifLink;
btnAdjusterWithImageLoad();
isLoading=false;
spinnerOnandOff();
animationBtn.hidden=true;
normalBtn.hidden=false;
})
const normalize=()=>{
imgView.style.width='170px';
}
const btnAdjusterWithImageLoad=()=>{
imgView.onload = () => {
const currentWidth = parseInt(window.getComputedStyle(imgView).width);
currentWidth >= 200 ? maxBtn.disabled=true : maxBtn.disabled=false;
currentWidth <=50 ? minBtn.disabled=true : minBtn.disabled=false;
};
}
normalBtn.addEventListener('click',()=>{
noAnimationMsg.hidden=true;
imgView.style.width='170px';
isLoading=true;
spinnerOnandOff();
imgView.src='';
imgView.src=normalImgLink;
btnAdjusterWithImageLoad();
normalBtn.hidden=true;
animationBtn.hidden=false;
isLoading=false;
spinnerOnandOff();
})
searchButton.addEventListener('click',()=>{
updateUI();
})
searchInput.addEventListener('input',(e)=>{
const query = searchInput.value.toLowerCase();
if (!data.length) {
console.log('Data not loaded yet');
return;
}
if(searchInput.value===''){
dropDownCont.classList.replace('show','dd-hide');
}else{
dropDownCont.classList.replace('dd-hide','show');
if(/^[a-zA-Z]/.test(query)){
showSuggestions(query)
}else{
showSuggestionsForId(query);
}
}
})
searchInput.addEventListener('keyup',(e)=>{
if(e.key==='Enter'){
updateUI();
}
})
const showSuggestions=(query)=>{
const filterData = data.filter(pokemon => pokemon.name.toLowerCase().startsWith(query));
handleSuggestions(filterData,true);
}
const showSuggestionsForId=(query)=>{
const filteredId=idData.filter(pokemonId=>pokemonId.startsWith(query.toString()));
handleSuggestions(filteredId,false);
}
const handleSuggestions=(filteredArray,isName)=>{
dropDownCont.innerHTML='';
if(filteredArray.length===0){
isName ? dropDownCont.innerHTML=`<p id='no-match'>NO MATCHES</p>` : dropDownCont.innerHTML=`<p id='no-match-num'>NO MATCHES</p>`;
}
filteredArray.forEach(pokemon=>{
const div=document.createElement('div');
div.classList.add('dd-btns');
const regex=new RegExp(`^(${searchInput.value})`,'i');
if(isName){
div.innerHTML=pokemon.name.replace(regex,`<span class='high'>${searchInput.value}</span>`);
}else{
div.innerHTML=pokemon.replace(regex,`<span class='high'>${searchInput.value}</span>`);
}
div.addEventListener('click',()=>{
searchInput.value = isName ? pokemon.name : pokemon;
searchInput.focus();
});
dropDownCont.appendChild(div);
})
}
maxBtn.addEventListener('click',()=>{
const currentWidth =parseInt(window.getComputedStyle(imgView).width);
imgView.style.width=(currentWidth+20)+'px';
currentWidth>=180 ? maxBtn.disabled=true : maxBtn.disabled=false;
if(currentWidth>50){
minBtn.disabled=false;
}
})
minBtn.addEventListener('click',()=>{
const currentWidth =parseInt(window.getComputedStyle(imgView).width);
imgView.style.width=(currentWidth-20)+'px';
currentWidth<=75 ? minBtn.disabled=true : minBtn.disabled=false;
if(currentWidth<200){
maxBtn.disabled=false;
}
})
evolExitBtn.addEventListener('click',()=>{
evolCont.classList.remove('evol-show');
evolCont.classList.add('evol-hide');
container.style.opacity='1'
})
imgView.addEventListener('click',()=>{
if(isNewImageLoaded){
dialogElement.show();
}
})
acceptDialogBtn.addEventListener('click',()=>{
dialogElement.close();
evolCont.classList.remove('evol-hide');
evolCont.classList.add('evol-show');
updateEvolContUI();
container.style.opacity='0.8';
})
rejectDialogBtn.addEventListener('click',()=>[
dialogElement.close()
])
const findPokemonEvolArr=(id)=>{
for(let arr of Object.values(pokemonEvolMap)){
if(arr.includes(id)){
return arr;
}
}
}
const evolImgFetcher=async(evolutionArrElement)=>{
const cacheKey=evolutionArrElement;
if(cacheEvolData[cacheKey]){
// console.log(roughSizeOfCacheObject(cacheEvolData)/1000+'kb');
return cacheEvolData[cacheKey];
}
try{
const response=await fetch(fetchApi+evolutionArrElement.toString());
const result=await response.json();
cacheEvolData[cacheKey]=result;
return result;
}catch(e){
console.log(e);
const h2=document.createElement('h2');
h2.textContent='No Evolution Data Available at this Moment.';
h2.className='no-form-data';
evolChainCont.appendChild(h2);
return;
}
}
const evolContUiUpdateHandler=(result)=>{
const img=document.createElement('img');
const p=document.createElement('p');
const loader=document.createElement('div');
img.src=result.sprites.front_default;
img.alt=result.name;
img.className='scaler';
p.textContent=result.name;
p.style.fontFamily=' "Orbitron", sans-serif';
loader.className='img-loader';
const div=document.createElement('div');
div.className='evol-img-cont';
div.appendChild(loader);
div.appendChild(img);
div.appendChild(p);
evolChainCont.appendChild(div);
img.onload=()=>{
loader.remove();
}
img.onerror=()=>{
loader.remove();
p.textContent='Image Not available';
}
img.classList.add('animate__animated');
img.classList.add('animate__flip');
}
const updateEvolContUI=async()=>{
evolChainCont.innerHTML='';
let evolutionArr=findPokemonEvolArr(globalPokemonId);
if(evolutionArr){
for(let i=0;i<evolutionArr.length;i++){
let result;
result= await evolImgFetcher(evolutionArr[i]);
evolContUiUpdateHandler(result);
}
}else{
const h2=document.createElement('h2');
h2.textContent='No Evolution Data Available For This Pokemon';
h2.className='no-form-data';
evolChainCont.appendChild(h2);
}
}
const playPokemonCry=async()=>{
const id = globalPokemonId;
audioSvgCont.classList.add('disabled');
try{
const response = await fetch(fetchCrySoundApi+`${id}.ogg`);
if(!response.ok){
throw new Error(`HTTP error! status: ${response.status}`);
}
if(!response.headers.get('Content-Type').startsWith('audio/')){
console.error('Not a Supported audio format');
return;
}
const blob = await response.blob();
const audioCtx = new AudioContext();
const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = () =>{
const audioBuffer = reader.result;
audioCtx.decodeAudioData(audioBuffer)
.then(decodedBuffer=>{
const source = audioCtx.createBufferSource();
source.buffer = decodedBuffer;
source.connect(audioCtx.destination);
source.start(0);
})
.catch(err=>console.error('error decoding audio data:',err));
}
reader.onerror=(err)=>console.error('Error reading audio data: ',err);
audioSvgCont.classList.remove('disabled');
}catch(e){
console.error('Error fetching audio:',error);
alert('an error occured try again after some time');
audioSvgCont.classList.remove('disabled');
}
}
audioSvgCont.addEventListener('click',playPokemonCry)
// function roughSizeOfCacheObject(object) {
// const objectList = [];
// const stack = [object];
// let bytes = 0;
// while (stack.length) {
// const value = stack.pop();
// if (typeof value === 'boolean') {
// bytes += 4;
// } else if (typeof value === 'string') {
// bytes += value.length * 2;
// } else if (typeof value === 'number') {
// bytes += 8;
// } else if (typeof value === 'object' && value !== null && !objectList.includes(value)) {
// objectList.push(value);
// for (const i in value) {
// if (value.hasOwnProperty(i)) {
// stack.push(value[i]);
// }
// }
// }
// }
// return bytes;
// }