-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.js
82 lines (72 loc) · 2.4 KB
/
main.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
//create an empty array on startup
let animeHistory = []
const API_BASE = "https://api.jikan.me/"
const API_ANIME = API_BASE + "anime/"
const HISTORY_STORAGE_KEY = 'HISTORY_KEY'
/**
* generate anime tag
*/
function buildAnimeMarkup(anime) {
return `<div class="anime_item"><img class='anime_image' src=${anime.image_url} />
<h2 class='anime_name'>${anime.title}</h2>
<p class='anime_description'>${anime.aired_string}</p></div>`
}
/**
* add an anime to the history and updates display
*/
function updateHistory(anime) {
animeHistory.push(anime)
//Save the array in the local storage. JSON.stringify allows to serialize the array to a string
localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(animeHistory))
//update display
addAnimeToHistoryTag(anime)
}
/**
* Update the DOM
*/
function addAnimeToHistoryTag(anime) {
document.querySelector('#history').innerHTML = buildAnimeMarkup(anime) + document.querySelector('#history').innerHTML
}
/**
* loadAnAnime from the internet and place it on a target element
*/
async function onOkButtonClickAsync() {
let targetElementId = '#main_anime'
let animeId = document.querySelector("#anime_id_input").value
try {
const response = await fetch(API_ANIME + animeId)
if (!response.ok) {
return
}
const anime = await response.json()
console.log("anime", anime)
document.querySelector(targetElementId).innerHTML = buildAnimeMarkup(anime)
updateHistory(anime)
} catch (err) {
console.error(`error ${err}`)
}
}
/**
* The history is serrialized as a JSON array. We use JSON.parse to convert is to a Javascript array
*/
function getLocalHistory() {
return JSON.parse(localStorage.getItem(HISTORY_STORAGE_KEY))
}
async function onLoadAsync() {
//load the history from cache
let history = getLocalHistory()
if (history !== null) {
//set the animeHistory array and update the display
animeHistory = history
animeHistory.forEach(anime => addAnimeToHistoryTag(anime))
}
//Install the service worker
if ('serviceWorker' in navigator) {
try {
let serviceWorker = await navigator.serviceWorker.register('/sw.js')
console.log(`Service worker registered ${serviceWorker}`)
} catch (err) {
console.error(`Failed to register service worker: ${err}`)
}
}
}