Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
335 lines (282 loc) · 11.7 KB
/
Copy pathscript.js
File metadata and controls
335 lines (282 loc) · 11.7 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
// name file script.js
import { songList } from './spotify_top_hits_clean_json.js';
//>curl -X POST "https://accounts.spotify.com/api/token" -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=8f38be140a0e4f3a86ae61282fc2f875&client_secret=1ae6bbe5cc81426186efc77a28db6365"
//^^the request for API to function
const API_KEY = "BQCarPTpKBqIujujsDWNOQQSm8EFUZdAR1HGEgINW1Xnq21Nk9y-8xCW16UbmxZxAnymVhTR8vOYwLSA3L0qwrnAdXs5aPuGBuMlPu2SDAvsgUNjleV6zyKDxnbeRk-5cEPD3Mi4kZA";
function showForm() { //displays the search entry bar
const resultCard = document.getElementById('result-card')
resultCard.innerHTML = ''
const artistSearch = document.createElement('div')
artistSearch.innerHTML =
`
<form id="artist-search-form">
<label for="artist-input">Search for an artist</label>
<input type="text" name="artist" id="artist-input" placeholder="Taylor Swift">
<button type="submit" id="submit-button">Search</button>
</form>
`
resultCard.prepend(artistSearch)
const form = document.getElementById('artist-search-form')
form.addEventListener('submit', handleSubmit)
}
const handleSubmit = async (event) => {
event.preventDefault()
const inputForm = document.getElementById('artist-input')
console.log(inputForm)
const artistRequested = inputForm.value
console.log(artistRequested)
const artists = await searchArtists(artistRequested)
displayArtistCards(artists)
}
async function searchArtists(artist) { //search for an artist using spotify's API
const requestURL = `https://api.spotify.com/v1/search?q=${artist}&type=artist&limit=5&offset=0`
const details = {
method: "GET",
headers: {
Authorization: `Bearer ${API_KEY}`
}
}
const result = await fetch(requestURL, details)
const json = await result.json()
console.log(json)
const retrievedArtists = json.artists.items
console.log(retrievedArtists)
const cleanedArtistData = retrievedArtists.map((artist) => (
{
id: artist.id,
name: artist.name,
link: artist.external_urls.spotify,
followers: artist.followers.total,
popular: artist.popularity,
genre: artist.genres,
image: (artist.images.length > 0 ? artist.images[0].url : '')
}
))
return cleanedArtistData
}
function displayArtistCards(artistDetails) {//displays the artists found to the screen
const resultCard = document.getElementById('result-card')
resultCard.innerHTML = ''
showForm()
console.log("Artist details : ", artistDetails)
const cardsContainer = document.createElement('div')
artistDetails.forEach((artist) => {
const card = document.createElement('div')
card.innerHTML =
`
<div class="card-container">
<div class="detail-container">
<div class="img-container">
<img src=${artist.image ? artist.image : 'https://storage.googleapis.com/pr-newsroom-wp/1/2023/05/Spotify_Primary_Logo_RGB_Green.png'} alt=${artist.name}/>
</div>
<div class="info-container">
<h4>
${artist.name}
</h4>
<div>
<span>${artist.genre} ◆ </span>
<span>${artist.followers} Followers ◆ </span>
<span>Popularity ${artist.popularity}</span>
</div>
</div>
</div>
<h6 class="visit-link"><a href=${artist.link}>Visit Artist</a></h6>
</div>
`
//card.addEventListener('click', () => {handleArtistClick(artist.id)})
cardsContainer.appendChild(card)
})
resultCard.append(cardsContainer)
}
function displayAlbums(albumDetails) { //displays the found albums to the screen
const resultCard = document.getElementById('result-card')
resultCard.innerHTML = ''
showForm()
console.log("Album details : ", albumDetails)
const cardsContainer = document.createElement('div')
albumDetails.forEach((album) => {
const card = document.createElement('div')
card.innerHTML =
`
<div class="card-container">
<div class="detail-container">
<div class="img-container">
<img src=${album.image ? album.image : 'https://storage.googleapis.com/pr-newsroom-wp/1/2023/05/Spotify_Primary_Logo_RGB_Green.png'} alt=${album.name}/>
</div>
<div class="info-container">
<h4>
${album.name}
</h4>
<div>
<span>${album.numTracks} Tracks ◆ </span>
<span> Released ${album.released} ◆ </span>
<span>${album.type}</span>
</div>
</div>
</div>
<h6 class="visit-link"><a href=${album.link}>Visit Album</a></h6>
</div>
`
card.addEventListener('click', () => {handleAlbumClick(album)})
cardsContainer.appendChild(card)
})
resultCard.append(cardsContainer)
}
function displayTracks(trackDetails, image) { //displays the tracks of a selected album
const resultCard = document.getElementById('result-card')
resultCard.innerHTML = ''
showForm()
console.log("Track details : ", trackDetails)
const cardsContainer = document.createElement('div')
trackDetails.forEach((track) => {
const card = document.createElement('div')
card.innerHTML =
`
<div class="card-container">
<div class="detail-container">
<div class="img-container">
<img src=${image ? image : 'https://storage.googleapis.com/pr-newsroom-wp/1/2023/05/Spotify_Primary_Logo_RGB_Green.png'} alt=${track.name}/>
</div>
<div class="info-container">
<h4>
${track.name}
</h4>
<div>
<span>${Math.floor(track.duration / 60000)} minutes ◆ </span>
<span>${track.artists.map((artist) => (" " + artist.name))}</span>
</div>
</div>
</div>
<div class="button-container">
<h6 class="visit-link" style="text-align:center"><a href=${track.link}>Visit Song</a></h6>
<button class="visit-link add-btn" id="add-button">Add Song to Dataset</button>
</div>
</div>
`
const addButton = card.getElementsByClassName('add-btn').item(0)
addButton.addEventListener('click', () => {addTrackToData(track.id)})
cardsContainer.appendChild(card)
})
resultCard.append(cardsContainer)
}
document.addEventListener('DOMContentLoaded', () => {
const buttons = document.querySelectorAll('.result-button');
const resultCard = document.getElementById('result-card');
buttons.forEach(button => {
button.addEventListener('click', () => {
const buttonText = button.textContent;
if (buttonText === 'Most Common Genre') {
createGenreChart();
} else if (buttonText === 'Year Song Released') {
createYearChart();
} else if (buttonText === 'Loudest Song') {
createLoudestSongChart();
} else if (buttonText == 'Search') {
showForm()
}
});
});
function createGenreChart() {
const genreCounts = {};
// Outer loop to iterate over the songList array
for (const song of songList) {
const genres = song.genre.split(',').map(g => g.trim());
// Inner loop to iterate over each genre
for (const genre of genres) {
genreCounts[genre] = (genreCounts[genre] || 0) + 1;
}
}
const labels = Object.keys(genreCounts);
const data = Object.values(genreCounts);
const canvas = document.createElement('canvas');
canvas.id = 'genreChart';
resultCard.innerHTML = ''; // Clear previous content
resultCard.appendChild(canvas);
const ctx = canvas.getContext('2d'); // Get the context of the canvas element
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Number of Songs',
data: data,
backgroundColor: 'rgba(35, 255, 64, 0.8)',
borderColor: 'rgb(0, 0, 0)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function createYearChart() {
const yearCounts = {};
songList.forEach(song => {
const year = song.year;
yearCounts[year] = (yearCounts[year] || 0) + 1;
});
const labels = Object.keys(yearCounts);
const data = Object.values(yearCounts);
const canvas = document.createElement('canvas');
canvas.id = 'yearChart';
resultCard.innerHTML = ''; // Clear previous content
resultCard.appendChild(canvas);
const ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
label: 'Number of Songs by Year',
data: data,
backgroundColor: [
'rgb(23, 255, 23)',
'rgb(4, 83, 8)',
'rgb(12, 207, 29)'
],
hoverOffset: 100
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
}
}
});
}
function createLoudestSongChart() {
// Sort the songList by loudness in descending order
const sortedSongs = [...songList].sort((a, b) => b.loudness - a.loudness);
// Take the top 10 loudest songs
const top10Loudest = sortedSongs.slice(0, 10);
// Extract song names and loudness values
const labels = top10Loudest.map(song => song.song);
const data = top10Loudest.map(song => song.loudness);
const canvas = document.createElement('canvas');
canvas.id = 'loudestSongChart';
resultCard.innerHTML = ''; // Clear previous content
resultCard.appendChild(canvas);
const ctx = canvas.getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Loudest Song',
data: data,
fill: false,
borderColor: 'rgb(5, 255, 5)',
tension: 0.1
}]
},
});
}
});