forked from JulienMaille/spicetify-dynamic-theme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default-dynamic.js
342 lines (307 loc) · 12.9 KB
/
default-dynamic.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
let current = "4.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(id) {
return Spicetify.CosmosAsync.get(`https://api.spotify.com/v1/albums/${id}`);
}
function getEpisodeInfo(id) {
return Spicetify.CosmosAsync.get(`https://api.spotify.com/v1/episodes/${id}`);
}
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 = getComputedStyle(document.documentElement).getPropertyValue("--spice-text");
let textColorBg = getComputedStyle(document.documentElement).getPropertyValue("--spice-main");
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("main-elevated", setDark ? "#303030" : "#DDDDDD");
setRootColor("notification", setDark ? "#303030" : "#DDDDDD");
setRootColor("highlight-elevated", setDark ? "#303030" : "#DDDDDD");
updateColors(textColor);
}
/* Init with current system light/dark mode */
let systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
toggleDark(systemDark);
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
toggleDark(e.matches);
});
waitForElement([".main-topBar-container"], (queries) => {
// Add activator on top bar
const div = document.createElement("div");
div.id = "main-topBar-moon-div";
queries[0].insertBefore(div, queries[0].querySelector(".main-userWidget-box"));
const button = document.createElement("button");
button.id = "main-topBar-moon-button";
button.classList.add("main-topBar-buddyFeed");
button.setAttribute("title", "Light/Dark");
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>`;
div.append(button);
});
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
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("selected-row", darkerColHex);
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);
}
let album_uri = Spicetify.Player.data.item.metadata.album_uri;
let bgImage = Spicetify.Player.data.item.metadata.image_url;
if (!bgImage) {
bgImage = "/images/tracklist-row-song-fallback.svg";
textColor = "#1db954";
updateColors(textColor);
}
if (album_uri && !album_uri.includes("spotify:show")) {
const albumInfo = await getAlbumInfo(album_uri.replace("spotify:album:", ""));
let album_date = new Date(albumInfo.release_date);
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
const episodeInfo = await getEpisodeInfo(Spicetify.Player.data.item.uri.replace("spotify:episode:", ""));
let podcast_date = new Date(episodeInfo.release_date);
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}")`);
registerCoverListener();
}
Spicetify.Player.addEventListener("songchange", songchange);
function pickCoverColor(img) {
if (!img.currentSrc.startsWith("spotify:")) return;
if (img.complete) {
textColor = "#1db954";
try {
var swatches = new Vibrant(img, 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);
}
}
updateColors(textColor);
}
var coverListener;
function registerCoverListener() {
const img = document.querySelector(".main-image-image.cover-art-image");
if (!img) return setTimeout(registerCoverListener, 250); // Check if image exists
if (!img.complete) return img.addEventListener("load", registerCoverListener); // Check if image is loaded
pickCoverColor(img);
if (coverListener != null) {
coverListener.disconnect();
coverListener = null;
}
coverListener = new MutationObserver((muts) => {
const img = document.querySelector(".main-image-image.cover-art-image");
if (!img) return registerCoverListener();
pickCoverColor(img);
});
coverListener.observe(img, {
attributes: true,
attributeFilter: ["src"]
});
}
registerCoverListener();
(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) {
document.querySelector("#main-topBar-moon-button").classList.remove("main-topBar-buddyFeed");
document.querySelector("#main-topBar-moon-button").classList.add("main-noConnection-button", "main-noConnection-isNotice");
let updateLink = document.createElement("a");
updateLink.setAttribute("title", `Changes: ${data.name}`);
updateLink.setAttribute("href", "https://github.com/JulienMaille/spicetify-dynamic-theme/releases/latest");
updateLink.innerHTML = `v${data.tag_name} available`;
document.querySelector("#main-topBar-moon-button").append(updateLink);
}
})
.catch((err) => {
// Do something for an error here
});
Spicetify.showNotification("Applied system " + (systemDark ? "dark" : "light") + " theme.");
})();
document.documentElement.style.setProperty("--warning_message", " ");