-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathdefault-dynamic.js
More file actions
398 lines (355 loc) · 14.5 KB
/
Copy pathdefault-dynamic.js
File metadata and controls
398 lines (355 loc) · 14.5 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
let current = "5.7";
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, 300, els, func, --timeout);
}
}
function getAlbumInfo(uri) {
const Authorization = `Bearer ${Spicetify.Platform.AuthorizationAPI.getState().token.accessToken}`;
const Headers = {
Authorization,
"Spotify-App-Version": Spicetify.Platform.version,
"App-Platform": Spicetify.Platform.PlatformData.app_platform,
"Content-Type": "application/json"
};
const Body = JSON.stringify({
operationName: "getAlbum",
variables: {
uri: uri,
locale: "",
offset: 0,
limit: 50
},
extensions: {
persistedQuery: {
version: 1,
sha256Hash: "b9bfabef66ed756e5e13f68a942deb60bd4125ec1f1be8cc42769dc0259b4b10"
}
}
});
return fetch(`https://api-partner.spotify.com/pathfinder/v2/query`, { headers: Headers, method: "POST", body: Body })
.then((res) => res.json())
.then((d) => d.data.albumUnion);
}
function isLight(hex) {
var [r, g, b] = hexToRgb(hex).map(Number);
const brightness = (r * 299 + g * 587 + b * 114) / 1000;
return brightness > 128;
}
function hexToRgb(hex) {
var bigint = parseInt(hex.replace("#", ""), 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return [r, g, b];
}
function rgbToHex([r, g, b]) {
const rgb = (r << 16) | (g << 8) | (b << 0);
return "#" + (0x1000000 + rgb).toString(16).slice(1);
}
function lightenDarkenColor(h, p) {
return (
"#" +
[1, 3, 5]
.map((s) => parseInt(h.substr(s, 2), 16))
.map((c) => parseInt((c * (100 + p)) / 100))
.map((c) => (c < 255 ? c : 255))
.map((c) => c.toString(16).padStart(2, "0"))
.join("")
);
}
function rgbToHsl([r, g, b]) {
((r /= 255), (g /= 255), (b /= 255));
var max = Math.max(r, g, b),
min = Math.min(r, g, b);
var h,
s,
l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l];
}
function hslToRgb([h, s, l]) {
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return [r * 255, g * 255, b * 255];
}
function setLightness(hex, lightness) {
hsl = rgbToHsl(hexToRgb(hex));
hsl[2] = lightness;
return rgbToHex(hslToRgb(hsl));
}
let textColor = "#1db954";
let textColorBg = getComputedStyle(document.documentElement).getPropertyValue("--spice-main");
let settingsDark = getComputedStyle(document.documentElement).getPropertyValue("--spice-dark") == "#010101";
function setRootColor(name, colHex) {
let root = document.documentElement;
if (root === null) return;
root.style.setProperty("--spice-" + name, colHex);
root.style.setProperty("--spice-rgb-" + name, hexToRgb(colHex).join(","));
}
function toggleDark(setDark) {
if (setDark === undefined) setDark = isLight(textColorBg);
document.documentElement.style.setProperty("--is_light", setDark ? 0 : 1);
textColorBg = setDark ? "#0A0A0A" : "#FAFAFA";
setRootColor("main", textColorBg);
setRootColor("sidebar", textColorBg);
setRootColor("player", textColorBg);
setRootColor("shadow", textColorBg);
setRootColor("card", setDark ? "#040404" : "#ECECEC");
setRootColor("subtext", setDark ? "#EAEAEA" : "#3D3D3D");
setRootColor("selected-row", setDark ? "#EAEAEA" : "#3D3D3D");
setRootColor("main-elevated", setDark ? "#303030" : "#DDDDDD");
setRootColor("notification", setDark ? "#303030" : "#DDDDDD");
setRootColor("highlight-elevated", setDark ? "#303030" : "#DDDDDD");
updateColors(textColor);
}
/* Init with light/dark mode from settings */
toggleDark(settingsDark);
/* Hook user changes to toggle using a proxy for Spicetify.Config */
Spicetify.Config = new Proxy(Spicetify.Config, {
set(target, property, value) {
if (property === "color_scheme") {
// Wait 100ms for CSS variables to update
setTimeout(() => {
let dark = getComputedStyle(document.documentElement).getPropertyValue("--spice-dark").trim() === "#010101";
toggleDark(dark);
}, 100);
}
target[property] = value;
return true;
}
});
waitForElement([".main-actionButtons"], (queries) => {
// Add activator on top bar
const buttonContainer = queries[0];
const button = document.createElement("button");
Array.from(buttonContainer.firstChild.attributes).forEach((attr) => {
button.setAttribute(attr.name, attr.value);
});
button.id = "main-topBar-moon-button";
button.className = buttonContainer.firstChild.className;
button.onclick = () => {
toggleDark();
};
button.innerHTML = `<svg role="img" viewBox="0 0 16 16" height="16" width="16"><path fill="currentColor" d="M9.598 1.591a.75.75 0 01.785-.175 7 7 0 11-8.967 8.967.75.75 0 01.961-.96 5.5 5.5 0 007.046-7.046.75.75 0 01.175-.786zm1.616 1.945a7 7 0 01-7.678 7.678 5.5 5.5 0 107.678-7.678z"></path></svg>`;
const tooltip = Spicetify.Tippy(button, {
...Spicetify.TippyProps,
content: "Light/Dark"
});
buttonContainer.insertBefore(button, buttonContainer.firstChild);
});
function updateColors(textColHex) {
if (textColHex == undefined) return registerCoverListener();
let isLightBg = isLight(textColorBg);
if (isLightBg)
textColHex = lightenDarkenColor(textColHex, -15); // vibrant color is always too bright for white bg mode
else textColHex = setLightness(textColHex, 0.45);
let darkColHex = lightenDarkenColor(textColHex, isLightBg ? 12 : -20);
let darkerColHex = lightenDarkenColor(textColHex, isLightBg ? 30 : -40);
let softHighlightHex = setLightness(textColHex, isLightBg ? 0.9 : 0.14);
setRootColor("text", textColHex);
setRootColor("button", darkerColHex);
setRootColor("button-active", darkColHex);
setRootColor("tab-active", softHighlightHex);
setRootColor("button-disabled", softHighlightHex);
let softerHighlightHex = setLightness(textColHex, isLightBg ? 0.9 : 0.1);
setRootColor("highlight", softerHighlightHex);
// compute hue rotation to change spotify green to main color
let rgb = hexToRgb(textColHex);
let m = `url('data:image/svg+xml;utf8,
<svg xmlns="http://www.w3.org/2000/svg">
<filter id="recolor" color-interpolation-filters="sRGB">
<feColorMatrix type="matrix" values="
0 0 0 0 ${rgb[0] / 255}
0 0 0 0 ${rgb[1] / 255}
0 0 0 0 ${rgb[2] / 255}
0 0 0 1 0
"/>
</filter>
</svg>
#recolor')`;
document.documentElement.style.setProperty("--colormatrix", encodeURI(m));
}
let nearArtistSpanText = "";
async function songchange() {
if (!document.querySelector(".main-trackInfo-container")) return setTimeout(songchange, 300);
try {
// warning popup
if (Spicetify.Platform.PlatformData.client_version_triple < "1.1.68") Spicetify.showNotification(`Your version of Spotify ${Spicetify.Platform.PlatformData.client_version_triple}) is un-supported`);
} catch (err) {
console.error(err);
}
const album_uri = Spicetify.Player.data.item.metadata.album_uri;
let bgImage = Spicetify.Player.data.item.metadata.image_url;
if (!bgImage) {
bgImage = "https://cdn.jsdelivr.net/gh/JulienMaille/spicetify-dynamic-theme@main/images/tracklist-row-song-fallback.svg";
textColor = "#1db954";
updateColors(textColor);
}
if (album_uri && !album_uri.includes("spotify:show")) {
const albumInfo = await getAlbumInfo(album_uri);
let album_date = new Date(albumInfo.date.isoString);
let recent_date = new Date();
recent_date.setMonth(recent_date.getMonth() - 6);
album_date = album_date.toLocaleString("default", album_date > recent_date ? { year: "numeric", month: "short" } : { year: "numeric" });
nearArtistSpanText = `
<span>
<span draggable="true">
<a draggable="false" dir="auto" href="${album_uri}">${Spicetify.Player.data.item.metadata.album_title}</a>
</span>
</span>
<span> • ${album_date}</span>
`;
} else if (Spicetify.Player.data.item.type === "episode") {
// podcast
let added_at = Number(Spicetify.Player.data.item.metadata.added_at); // Sometimes added_at is in seconds, sometimes in milliseconds
if (added_at < 1e10) added_at *= 1000;
let podcast_date = new Date(added_at);
podcast_date = podcast_date.toLocaleString("default", { year: "numeric", month: "short" });
bgImage = bgImage.replace("spotify:image:", "https://i.scdn.co/image/");
nearArtistSpanText = `
<span>
<span draggable="true">
<a draggable="false" dir="auto" href="${album_uri}">${Spicetify.Player.data.item.metadata["show.publisher"]}</a>
</span>
</span>
<span> • ${podcast_date}</span>
`;
} else if (Spicetify.Player.data.item.isLocal) {
// local file
nearArtistSpanText = Spicetify.Player.data.item.metadata.album_title;
} else if (Spicetify.Player.data.item.provider == "ad") {
// ad
nearArtistSpanText.innerHTML = "Advertisement";
return;
} else {
// When clicking a song from the homepage, songChange is fired with half empty metadata
// todo: retry only once?
setTimeout(songchange, 200);
}
if (!document.querySelector("#main-trackInfo-year")) {
waitForElement([".main-trackInfo-container:not(#upcomingSongDiv)"], (queries) => {
nearArtistSpan = document.createElement("div");
nearArtistSpan.id = "main-trackInfo-year";
nearArtistSpan.classList.add("main-trackInfo-release", "standalone-ellipsis-one-line", "main-type-finale");
nearArtistSpan.innerHTML = nearArtistSpanText;
queries[0].append(nearArtistSpan);
});
} else {
nearArtistSpan.innerHTML = nearArtistSpanText;
}
document.documentElement.style.setProperty("--image_url", `url("${bgImage}")`);
pickCoverColor();
}
function getVibrant(image) {
try {
var swatches = new Vibrant(image, 12).swatches();
cols = isLight(textColorBg) ? ["Vibrant", "DarkVibrant", "Muted", "LightVibrant"] : ["Vibrant", "LightVibrant", "Muted", "DarkVibrant"];
for (var col in cols)
if (swatches[cols[col]]) {
textColor = swatches[cols[col]].getHex();
break;
}
} catch (err) {
console.error(err);
}
}
function pickCoverColor() {
const img = document.querySelector(".main-image-image.cover-art-image");
if (!img) return setTimeout(pickCoverColor, 250);
if (Spicetify.Player.data.item.isLocal) img.src = Spicetify.Player.data.item.metadata.image_url;
if (!img.complete) return setTimeout(pickCoverColor, 250);
textColor = "#1db954";
let imageUrl = Spicetify.Player.data.item.metadata.image_url;
if (!imageUrl) {
updateColors(textColor);
return;
}
if (imageUrl.startsWith("spotify:image:")) {
imageUrl = imageUrl.replace("spotify:image:", "https://i.scdn.co/image/");
}
var imgCORS = new Image();
imgCORS.crossOrigin = "anonymous";
imgCORS.src = imageUrl;
imgCORS.onload = function () {
getVibrant(imgCORS);
imgCORS = null;
updateColors(textColor);
};
imgCORS.onerror = function () {
imgCORS = null;
if (img.src && !img.src.startsWith("spotify:")) {
getVibrant(img);
}
updateColors(textColor);
};
}
Spicetify.Player.addEventListener("songchange", songchange);
songchange();
(function Startup() {
if (!Spicetify.showNotification) {
setTimeout(Startup, 300);
return;
}
// Check latest release
fetch("https://api.github.com/repos/JulienMaille/spicetify-dynamic-theme/releases/latest")
.then((response) => {
return response.json();
})
.then((data) => {
if (data.tag_name > current) {
const button = document.querySelector("#main-topBar-moon-button");
button.classList.remove("main-topBar-buddyFeed");
button.classList.add("main-actionButtons-button", "main-noConnection-isNotice");
let updateLink = document.createElement("a");
updateLink.setAttribute("href", "https://github.com/JulienMaille/spicetify-dynamic-theme/releases/latest");
updateLink.innerHTML = `v${data.tag_name} available`;
button.append(updateLink);
button._tippy.setProps({
allowHTML: true,
content: `Changes: ${data.name}`
});
}
})
.catch((err) => {
// Do something for an error here
});
Spicetify.showNotification("Applied " + (settingsDark ? "dark" : "light") + " theme.");
})();
document.documentElement.style.setProperty("--warning_message", " ");