-
Notifications
You must be signed in to change notification settings - Fork 20
/
theme.js
466 lines (405 loc) · 19.2 KB
/
theme.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
(function galaxy() {
if (!(Spicetify.Player.data && Spicetify.Platform)) {
setTimeout(galaxy, 100);
return;
}
console.log("galaxy running");
Object.keys(localStorage).forEach(item => {
if (item.includes("galaxy:temp")) localStorage.removeItem(item);
});
const config = {}
function parseOptions() {
config.blurHomeBackground = JSON.parse(localStorage.getItem("blurHomeBackground"));
config.useCurrSongAsHome = JSON.parse(localStorage.getItem("useCurrentSongAsHome"));
config.useHomeEverywhere = JSON.parse(localStorage.getItem("useHomeEverywhere"));
config.blurAllBackgrounds = JSON.parse(localStorage.getItem("blurAllBackgrounds"));
config.showHeaderImage = JSON.parse(localStorage.getItem("showHeaderImage"));
}
parseOptions()
let isDim = false;
function loopOptions(page) {
if (page === "/") {
if (config.blurHomeBackground) {
document.querySelector(".bg-main-shadow").classList.toggle("blur-enabled", true);
} else {
document.querySelector(".bg-main-shadow").classList.toggle("blur-enabled", false);
}
if (config.useCurrSongAsHome) {
fetchCurrTrackAlbumImage();
} else {
setBg(startImage);
}
} else {
if (config.blurAllBackgrounds) {
document.querySelector(".bg-main-shadow").classList.toggle("blur-enabled", true);
} else {
document.querySelector(".bg-main-shadow").classList.toggle("blur-enabled", false);
}
if (config.useHomeEverywhere) {
config.useCurrSongAsHome ? fetchCurrTrackAlbumImage() : setBg(startImage);
}
}
if (config.showHeaderImage && !document.querySelector("style[galaxy-showHeaderImage]")) {
const style = document.createElement("style");
style.setAttribute("galaxy-showHeaderImage", "");
style.innerHTML = `
.playlist-playlist-playlistImageContainer,
.main-entityHeader-imageContainer { display: block; }
.main-entityHeader-headerText { align-items: start; }
.main-entityHeader-title { text-align: left; }
.main-entityHeader-shadow { box-shadow: none;}`;
document.body.append(style);
} else if (!config.showHeaderImage && document.querySelector("style[galaxy-showHeaderImage]")) {
document.querySelector("style[galaxy-showHeaderImage]").remove();
}
}
const defImage = `https://github.com/harbassan/spicetify-galaxy/blob/main/assets/default_bg.jpg?raw=true`;
let startImage = localStorage.getItem("galaxy:startupBg") || defImage;
async function fetchCurrTrackAlbumImage() {
console.log("galaxy: fetching current track album image...");
const data = Spicetify.Player.data.item.metadata;
if (localStorage.getItem(`galaxy:tempAlbumImage:${data.album_uri.split(":")[2]}`)) {
setBg(localStorage.getItem(`galaxy:tempAlbumImage:${data.album_uri.split(":")[2]}`))
return
}
setBg(data.image_xlarge_url);
const dataHigh = await Spicetify.CosmosAsync.get(`https://api.deezer.com/search/album?q=artist:"${data.album_artist_name}" album:"${data.album_title}"`);
let album = dataHigh.data.find(e => e.title == data.album_title)
const uid = Spicetify.URI.fromString(data.album_uri).id
try {
setBg(album.cover_xl);
localStorage.setItem(`galaxy:tempAlbumImage:${uid}`, album.cover_xl)
} catch {
console.log("galaxy: unable to fetch image from deezer api");
}
}
async function fetchAlbumImage(uid) {
console.log("galaxy: fetching album image...");
if (localStorage.getItem(`galaxy:tempAlbumImage:${uid}`)) {
setBg(localStorage.getItem(`galaxy:tempAlbumImage:${uid}`))
return
}
const data = await Spicetify.CosmosAsync.get(`https://api.spotify.com/v1/albums/${uid}`);
setBg(data.images[0].url);
const dataHigh = await Spicetify.CosmosAsync.get(`https://api.deezer.com/search/album?q=artist:"${data.artists[0].name}" album:"${data.name}"`);
let album = dataHigh.data.find(e => e.title == data.name)
try {
setBg(album.cover_xl);
localStorage.setItem(`galaxy:tempAlbumImage:${uid}`, album.cover_xl)
} catch {
console.log("galaxy: unable to fetch image from deezer api");
}
}
async function fetchArtistImage(uid) {
console.log("galaxy: fetching artist image...");
const bannerSect = document.querySelector(".under-main-view");
const observer = new MutationObserver(mutation_list => {
for (mutation of mutation_list) {
if (mutation.addedNodes.length) {
const bannerImg = mutation.addedNodes[0].querySelector("div").style.backgroundImage;
setBg(bannerImg.slice(5, bannerImg.length - 2));
}
}
});
observer.observe(bannerSect, { childList: true });
const data = await Spicetify.CosmosAsync.get(`https://api.spotify.com/v1/artists/${uid}`);
setTimeout(() => {
if (!document.querySelector(".under-main-view .main-entityHeader-background")) setBg(data.images[0].url);
}, 600);
}
async function fetchPlaylistImage(uid) {
console.log("galaxy: fetching default playlist image...");
const uri = `spotify:playlist:${uid}`;
Spicetify.CosmosAsync.get(`sp://core-playlist/v1/playlist/${uri}/metadata`, {
policy: { picture: true },
}).then(data => {
setBg(data.metadata.picture);
});
const dataHigh = await Spicetify.CosmosAsync.get(`https://api.spotify.com/v1/playlists/${uid}`);
setBg(dataHigh.images[0].url);
localStorage.setItem("galaxy:tempPlaylistBg:" + uid, dataHigh.images[0].url);
}
function getPlaylistImage(uid) {
if (localStorage.getItem("galaxy:playlistBg:" + uid)) {
console.log("galaxy: fetching stored playlist image...");
setBg(localStorage.getItem("galaxy:playlistBg:" + uid));
return;
}
if (localStorage.getItem("galaxy:tempPlaylistBg:" + uid)) {
console.log("galaxy: fetching temporarily stored playlist image...");
setBg(localStorage.getItem("galaxy:tempPlaylistBg:" + uid));
return;
}
fetchPlaylistImage(uid);
}
function setBg(imageData) {
bgImage.src = imageData;
}
function waitForElement(els, func, timeout = 100) {
const queries = els.map(el => document.querySelector(el));
if (queries.every(a => a)) {
func(queries);
} else if (timeout > 0) {
setTimeout(waitForElement, 50, els, func, --timeout);
}
}
// input for custom background images
const bannerInput = document.createElement("input");
bannerInput.type = "file";
bannerInput.className = "banner-input";
bannerInput.accept = ["image/jpeg", "image/apng", "image/avif", "image/gif", "image/png", "image/svg+xml", "image/webp"].join(",");
// listen for edit playlist popup
const editObserver = new MutationObserver(mutation_list => {
for (let mutation of mutation_list) {
if (mutation.addedNodes.length) {
const popupContent = mutation.addedNodes[0].querySelector(".main-playlistEditDetailsModal-content");
if (!popupContent) continue;
const coverSelect = popupContent.querySelector(".main-playlistEditDetailsModal-albumCover");
const bannerSelect = coverSelect.cloneNode(true);
bannerSelect.id = "banner-select";
const [, , uid] = Spicetify.Platform.History.location.pathname.split("/");
const base64 = localStorage.getItem("galaxy:playlistBg:" + uid);
if (base64) {
bannerSelect.querySelector("img").src = base64;
bannerSelect.querySelector("img").removeAttribute("srcset");
}
const srcInput = document.createElement("input");
srcInput.type = "text";
srcInput.classList.add("main-playlistEditDetailsModal-textElement", "main-playlistEditDetailsModal-titleInput");
srcInput.id = "src-input";
srcInput.placeholder = "Banner image URL (recommended)";
const optButton = bannerSelect.querySelector(".main-playlistEditDetailsModal-imageDropDownButton");
optButton.querySelector("svg").children[0].remove();
optButton.querySelector("svg").append(document.querySelector(".main-playlistEditDetailsModal-closeBtn path").cloneNode());
optButton.onclick = () => {
localStorage.removeItem("galaxy:playlistBg:" + uid);
bannerSelect.querySelector("img").src = coverSelect.querySelector("img").src;
};
popupContent.append(bannerSelect);
popupContent.append(bannerInput);
popupContent.append(srcInput);
const editButton = bannerSelect.querySelector(".main-editImageButton-image.main-editImageButton-overlay");
editButton.onclick = () => {
bannerInput.click();
};
const save = popupContent.querySelector(".main-playlistEditDetailsModal-save button");
save.addEventListener("click", () => {
if (srcInput.value) {
localStorage.setItem("galaxy:playlistBg:" + uid, srcInput.value);
}
getPlaylistImage(uid);
});
}
}
});
editObserver.observe(document.body, { childList: true });
// when user selects a custom background image
bannerInput.onchange = () => {
if (!bannerInput.files.length) return;
const file = bannerInput.files[0];
const reader = new FileReader();
reader.onload = event => {
const result = event.target.result;
const [, , uid] = Spicetify.Platform.History.location.pathname.split("/");
if (!uid) {
try {
localStorage.setItem("galaxy:startupBg", result);
} catch {
Spicetify.Snackbar.enqueueSnackbar("File too large");
return;
}
document.querySelector("#home-select img").src = result;
} else {
try {
localStorage.setItem("galaxy:playlistBg:" + uid, result);
} catch {
Spicetify.Snackbar.enqueueSnackbar("File too large");
return;
}
loadBg_playlist(uid);
document.querySelector("#banner-select img").src = result;
document.querySelector("#banner-select img").removeAttribute("srcset");
}
};
reader.readAsDataURL(file);
};
// create the background elements
const bgContainer = document.createElement("div");
bgContainer.className = "bg-main-container";
bgContainer.innerHTML = `</div><div class="bg-image-container"><img class="bg-main-image"></div><div class="bg-main-shadow">`;
const bgImage = bgContainer.children[0].children[0];
document.body.prepend(bgContainer);
// add fade and dimness effects to mainview scroll node
waitForElement([".Root__main-view .main-view-container__scroll-node > div:nth-child(2)"], ([scrollNode]) => {
scrollNode.addEventListener("scroll", () => {
// dim
if (!isDim) {
bgContainer.children[0].style.webkitMaskImage = `linear-gradient(rgba(0, 0, 0, ${
0.75 - scrollNode.scrollTop / 1000 < 0.3 ? 0.3 : 0.75 - scrollNode.scrollTop / 1000
}) 0px, rgba(0, 0, 0, 0.1) 90%)`;
}
// fade
if (!scrollNode.scrollTop) {
scrollNode.setAttribute("fade", "bottom");
} else if (!(scrollNode.scrollHeight - scrollNode.scrollTop - scrollNode.clientHeight)) {
scrollNode.setAttribute("fade", "top");
} else {
scrollNode.setAttribute("fade", "full");
}
});
});
waitForElement([".Root__nav-bar .main-yourLibraryX-libraryItemContainer > div:nth-child(2)"], ([scrollNode]) => {
scrollNode.setAttribute("fade", "bottom");
scrollNode.addEventListener("scroll", () => {
// fade
if (scrollNode.scrollTop == 0) {
scrollNode.setAttribute("fade", "bottom");
} else if (scrollNode.scrollHeight - scrollNode.scrollTop - scrollNode.clientHeight == 0) {
scrollNode.setAttribute("fade", "top");
} else {
scrollNode.setAttribute("fade", "full");
}
});
});
waitForElement([".Root__right-sidebar .main-buddyFeed-scrollBarContainer > div:nth-child(2)"], ([scrollNode]) => {
scrollNode.setAttribute("fade", "bottom");
scrollNode.addEventListener("scroll", () => {
// fade
if (scrollNode.scrollTop == 0) {
scrollNode.setAttribute("fade", "bottom");
} else if (scrollNode.scrollHeight - scrollNode.scrollTop - scrollNode.clientHeight == 0) {
scrollNode.setAttribute("fade", "top");
} else {
scrollNode.setAttribute("fade", "full");
}
});
});
// create edit playlist topbar button
const playlistEdit = new Spicetify.Topbar.Button("edit-playlist", "edit", () => {
const button = document.querySelector(".main-entityHeader-titleButton");
button.click();
});
playlistEdit.element.classList.toggle("hidden", true);
// create edit home topbar button
const homeEdit = new Spicetify.Topbar.Button("edit-home", "edit", () => {
const content = document.createElement("div");
content.innerHTML = `
<div class="main-playlistEditDetailsModal-albumCover" id="home-select">
<div class="main-entityHeader-image" draggable="false">
<img aria-hidden="false" draggable="false" loading="eager" class="main-image-image main-entityHeader-image main-entityHeader-shadow"></div>
<div class="main-playlistEditDetailsModal-imageChangeButton">
<div class="main-editImage-buttonContainer">
<button class="main-editImageButton-image main-editImageButton-overlay" aria-haspopup="true" type="button">
<div class="main-editImageButton-icon icon">
<svg role="img" height="48" width="48" aria-hidden="true" viewBox="0 0 24 24" class="Svg-sc-1bi12j5-0 EQkJl"><path d="M17.318 1.975a3.329 3.329 0 114.707 4.707L8.451 20.256c-.49.49-1.082.867-1.735 1.103L2.34 22.94a1 1 0 01-1.28-1.28l1.581-4.376a4.726 4.726 0 011.103-1.735L17.318 1.975zm3.293 1.414a1.329 1.329 0 00-1.88 0L5.159 16.963c-.283.283-.5.624-.636 1l-.857 2.372 2.371-.857a2.726 2.726 0 001.001-.636L20.611 5.268a1.329 1.329 0 000-1.879z"></path></svg><span class="Type__TypeElement-goli3j-0 gAmaez main-editImageButton-copy">Choose photo</span></div></button></div></div><div class="main-playlistEditDetailsModal-imageDropDownContainer"><button class="main-playlistEditDetailsModal-imageDropDownButton" type="button"><svg role="img" height="16" width="16" viewBox="0 0 16 16" class="Svg-sc-1bi12j5-0 EQkJl"><path d="M1.47 1.47a.75.75 0 011.06 0L8 6.94l5.47-5.47a.75.75 0 111.06 1.06L9.06 8l5.47 5.47a.75.75 0 11-1.06 1.06L8 9.06l-5.47 5.47a.75.75 0 01-1.06-1.06L6.94 8 1.47 2.53a.75.75 0 010-1.06z"></path></svg><span class="hidden-visually">Edit photo</span></button></div></div>`;
const optionList = document.createElement("div");
function createOption(name, desc, defVal) {
const optionRow = document.createElement("div");
optionRow.classList.add("galaxyOptionRow");
optionRow.innerHTML = `
<span class="galaxyOptionDesc">${desc}</span>
<button class="galaxyOptionToggle">
<span class="toggleWrapper">
<span class="toggle"></span>
</span>
</button>`;
optionRow.setAttribute("name", name);
optionRow.querySelector("button").addEventListener("click", () => {
optionRow.querySelector(".toggle").classList.toggle("enabled");
});
const isEnabled = JSON.parse(localStorage.getItem(name)) ?? defVal;
optionRow.querySelector(".toggle").classList.toggle("enabled", isEnabled);
optionList.append(optionRow);
}
const srcInput = document.createElement("input");
srcInput.type = "text";
srcInput.classList.add("main-playlistEditDetailsModal-textElement", "main-playlistEditDetailsModal-titleInput");
srcInput.id = "src-input";
srcInput.placeholder = "Banner image URL (recommended)";
content.append(srcInput);
createOption("useCurrentSongAsHome", "Use currently playing song as home bg", false);
createOption("useHomeEverywhere", "Use the home bg everywhere", false);
createOption("blurHomeBackground", "Blur the home bg", false);
createOption("blurAllBackgrounds", "Blur the bg on other pages", false);
createOption("showHeaderImage", "Show the playlist/album img in header", false);
content.append(optionList);
img = content.querySelector("img");
img.src = localStorage.getItem("galaxy:startupBg") || defImage;
const editButton = content.querySelector(".main-editImageButton-image.main-editImageButton-overlay");
editButton.onclick = () => {
bannerInput.click();
};
const removeButton = content.querySelector(".main-playlistEditDetailsModal-imageDropDownButton");
removeButton.onclick = () => {
content.querySelector("img").src = defImage;
};
const saveButton = document.createElement("button");
saveButton.id = "home-save";
saveButton.innerHTML = "Save";
saveButton.addEventListener("click", () => {
// update changed bg image
startImage = srcInput.value || content.querySelector("img").src;
localStorage.setItem("galaxy:startupBg", startImage);
// save options to local storage
[...optionList.children].forEach(option => {
localStorage.setItem(option.getAttribute("name"), option.querySelector(".toggle").classList.contains("enabled"));
console.log(`galaxy: ${option.getAttribute("name")} set to ${option.querySelector(".toggle").classList.contains("enabled")}`);
});
parseOptions();
loopOptions("/")
});
content.append(saveButton);
const issueButton = document.createElement("a");
issueButton.classList.add("issue-button");
issueButton.innerHTML = "Report Issue";
issueButton.href = "https://github.com/harbassan/spicetify-galaxy";
content.append(issueButton);
Spicetify.PopupModal.display({ title: "Galaxy Settings", content: content });
});
homeEdit.element.classList.toggle("hidden", false);
// startup parse
loopOptions("/");
// pages on which to not dim background
const notDimPages = ["/playlist/", "/artist/", "/album/", "/folder/", "/collection/tracks"];
const bgImageWrapper = bgContainer.children[0];
// on page change
Spicetify.Platform.History.listen(({ pathname }) => {
const [, type, uid] = pathname.split("/");
// change background images for certain pages
if (!config.useHomeEverywhere) {
switch (type) {
case "playlist":
getPlaylistImage(uid);
break;
case "album":
fetchAlbumImage(uid);
break;
case "artist":
fetchArtistImage(uid);
break;
case "lyrics":
fetchCurrTrackAlbumImage();
}
if (pathname === "/collection/tracks") fetchCurrTrackAlbumImage();
}
isDim = !(notDimPages.some(page => pathname.includes(page)) || pathname == "/");
// dim pages without art
bgImageWrapper.style.webkitMaskImage = `linear-gradient(rgba(0, 0, 0, ${isDim ? 0.3 : 0.75}) 0px, rgba(0, 0, 0, 0.1) 90%)`;
// center topbar elements on dim pages
waitForElement([".main-topBar-topbarContentWrapper"], ([topbarWrapper]) => {
isDim ? topbarWrapper.classList.add("center") : topbarWrapper.classList.remove("center");
});
// add or remove topbar edit buttons
playlistEdit.element.classList.toggle("hidden", type !== "playlist");
homeEdit.element.classList.toggle("hidden", pathname !== "/");
loopOptions(pathname);
});
// change home and lyrics page background on songchange
Spicetify.Player.addEventListener("songchange", () => {
const pathname = Spicetify.Platform.History.location.pathname;
if ((pathname === "/lyrics" || pathname === "/collection/tracks") && !config.useHomeEverywhere) {
fetchCurrTrackAlbumImage();
}
loopOptions(pathname);
});
})();