diff --git a/src/components/playing/NowPlaying.astro b/src/components/playing/NowPlaying.astro index dbf068e..5872acc 100644 --- a/src/components/playing/NowPlaying.astro +++ b/src/components/playing/NowPlaying.astro @@ -552,4 +552,48 @@ const dataTrack = ( nowPlaying: querySelector("now-playing", HTMLNowPlayingElement), }; + /************ + * LISTENER * + ************/ + + let prev: nowPlaying = null; + + const ev = new EventSource("/now-playing-sse"); + + let i = -1; + ev.addEventListener("playing", (event) => { + i++; + const data = (() => { + try { + return JSON.parse(event.data); + } catch (e) { + return e; + } + })(); + if (!isNowPlaying(data)) + return console.warn("Unexpected package from server:", data, event.data); + + // data is valid nowPlayingData + // first call so assume prev is in an invalid state (which it is) + if (i === 0) console.log("SKIP: i = 0"); + // if both are null, quit since re-rendering is pointless + else if (data == prev) console.log("MATCH: null = null"); + // now if both are valid play items, so check the ID for equality + else if (data !== null && prev !== null && data.id === prev.id) + console.log("MATCH: nowPlaying = nowPlaying"); + else { + console.log("DIFFERENT"); + // there is now a difference between the previous setting and the new setting + // so it is worth updating the UI + + elements.recordArt.src = data + ? data?.album.images[0].url + : "https://undefined"; + + if (data) elements.nowPlaying.updateMetadata(data); + else elements.nowPlaying.nothingPlaying(); + } + + prev = data; + });