Files
rootandClaude Opus 5.5 536de29e4d Web: keep real playlist art in downloads, hide quota on HTTPS
The group art fetch now falls back to the raw composite when the Plex
transcode fails, and the Downloads card uses any stored group art.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:32:38 -08:00

1590 lines
99 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Stemify web player: views, the player bar, drawers (mixer, lyrics, queue), the context
// menu and settings. Playback lives in player.js, Plex in plex.js, stemserve in stems.js.
import { $, $$, esc, fmtTime, fmtBytes, plural, on, emit, toast, ICON, store, uuid } from "./util.js";
import { S, save, songMixes, saveSongMix, forgetSongMix, playlists, savePlaylists, newPlaylist, addToPlaylist, Offline } from "./store.js";
import { px, img, rawImg, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything, pxSend, plexUri } from "./plex.js";
import { Stems, Live, stemNow, stemTrack, stemBase, api } from "./stems.js";
import { E, Q, setting, stemGain, presets, allPresets, presetLabel, applyPreset, currentPreset, nextPreset, savePreset, deletePreset, movePreset, restorePresets, deleteAllCustom, toggleLock,
mixChanged, setKaraoke, setKaraokeMode, sameMix, setSpeed, saveQueue, saveOffline, Radio } from "./player.js";
import { lyricsFor, lineAt } from "./lyrics.js";
const SPEEDS = [0.5, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 2];
const view = $("#view");
// ---- appearance -------------------------------------------------------------------------------
// Same palettes as the iOS app: three appearances and the system accent colors (light / dark variants).
const THEMES = {
black: { label: "Black", bg: "#000000", panel: "#000000", raised: "#1c1c1e", line: "#2c2c2e", text: "#ffffff", muted: "#8d8d93", fill: "#3a3a3c" },
dark: { label: "Dark", bg: "#1c1c1e", panel: "#161618", raised: "#2c2c2e", line: "#3d3d40", text: "#ffffff", muted: "#98989d", fill: "#48484a" },
white: { label: "White", bg: "#ffffff", panel: "#f2f2f7", raised: "#efeff0", line: "#d8d8dc", text: "#000000", muted: "#8a8a8e", fill: "#e3e3e8", light: true },
};
const ACCENTS = {
music: ["Music", "#fa2d48", "#fc3c44"], pink: ["Pink", "#ff2d55", "#ff375f"], orange: ["Orange", "#ff9500", "#ff9f0a"],
yellow: ["Yellow", "#ffcc00", "#ffd60a"], green: ["Green", "#34c759", "#30d158"], teal: ["Teal", "#30b0c7", "#40c8e0"],
blue: ["Blue", "#007aff", "#0a84ff"], indigo: ["Indigo", "#5856d6", "#5e5ce6"], purple: ["Purple", "#af52de", "#bf5af2"],
};
const accentOf = (base, key = S.accent) => (ACCENTS[key] || ACCENTS.music)[base.light ? 1 : 2];
const inkFor = hex => {
const n = parseInt(hex.slice(1), 16), l = (0.299 * (n >> 16) + 0.587 * (n >> 8 & 255) + 0.114 * (n & 255)) / 255;
return l > 0.6 ? "#141414" : "#ffffff";
};
// Theme from the playing track's art: one hue taken from the art, laid over the chosen theme's lightness.
const hex = (h, s, l) => {
const f = n => { const k = (n + h * 12) % 12, c = l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1)); return Math.round(c * 255).toString(16).padStart(2, "0"); };
return "#" + f(0) + f(8) + f(4);
};
function artPalette([h, s0, v], base) {
const s = Math.min(s0, 0.9), tint = Math.min(s * 0.55, 0.32), clamp = (x, a, b) => Math.max(a, Math.min(b, x));
if (base.light) return { bg: hex(h, tint, .955), panel: hex(h, tint, .985), raised: hex(h, tint, .9), line: hex(h, tint, .85),
text: hex(h, .2, .1), muted: hex(h, .08, .42), accent: hex(h, Math.max(s, .55), clamp(v * .45, .32, .42)), light: true };
const black = base.bg === "#000000";
return { bg: black ? "#000000" : hex(h, tint, .09), panel: black ? "#000000" : hex(h, tint, .06), raised: hex(h, tint, black ? .085 : .145), line: hex(h, tint, black ? .12 : .18),
text: hex(h, .15, .93), muted: hex(h, .1, .66), accent: hex(h, Math.max(s, .55), clamp(v * .7, .58, .7)) };
}
// Roughly a vibrant swatch: the circular mean hue of the most colorful mid-bright pixels.
function vibrant(bm) {
const n = 24, cv = new OffscreenCanvas(n, n), cx = cv.getContext("2d", { willReadFrequently: true });
cx.drawImage(bm, 0, 0, n, n);
const d = cx.getImageData(0, 0, n, n).data, px = [];
for (let i = 0; i < d.length; i += 4) {
const r = d[i] / 255, g = d[i + 1] / 255, b = d[i + 2] / 255, mx = Math.max(r, g, b), mn = Math.min(r, g, b), c = mx - mn;
const h = !c ? 0 : mx === r ? ((g - b) / c + 6) % 6 / 6 : mx === g ? ((b - r) / c + 2) / 6 : ((r - g) / c + 4) / 6, s = mx ? c / mx : 0;
px.push([h, s, mx, s * (1 - Math.abs(mx - 0.55) * 1.4)]);
}
const top = px.sort((a, b) => b[3] - a[3]).slice(0, px.length / 6);
let x = 0, y = 0, s = 0, v = 0;
for (const p of top) { x += Math.cos(p[0] * 2 * Math.PI); y += Math.sin(p[0] * 2 * Math.PI); s += p[1]; v += p[2]; }
return s / top.length < 0.12 ? null : [(Math.atan2(y, x) / (2 * Math.PI) + 1) % 1, s / top.length, v / top.length];
}
const ArtTheme = {
url: "", hsv: null, seq: 0, cache: new Map(),
async set(url) {
if (!S.artTheme) url = "";
if (url === this.url) return;
this.url = url;
const n = ++this.seq;
let hsv = url ? this.cache.get(url) : null;
if (url && !this.cache.has(url)) {
try {
const r = await fetch(url, { signal: AbortSignal.timeout(8000) });
hsv = vibrant(await createImageBitmap(await r.blob()));
this.cache.set(url, hsv);
} catch { hsv = null; }
if (n !== this.seq) return;
}
this.hsv = hsv; applyTheme();
},
};
function applyTheme() {
const base = THEMES[S.theme] || THEMES.dark, t = ArtTheme.hsv ? artPalette(ArtTheme.hsv, base) : base, a = ArtTheme.hsv ? t.accent : accentOf(base);
$("#theme").textContent = `:root{--bg:${t.bg};--panel:${t.panel};--raised:${t.raised};--line:${t.line};--text:${t.text};--muted:${t.muted};` +
`--accent:${a};--accent-ink:${inkFor(a)};--glass:${t.panel}ee;--hover:${t.text}0d;--shadow:${t.light ? "#0003" : "#0009"};` +
`--wave:${t.text}44;--wave-ghost:${t.text}14;color-scheme:${t.light ? "light" : "dark"}}`;
$("#custom-css").textContent = S.css || "";
$('meta[name="theme-color"]').content = t.bg;
Wave.colors();
}
// ---- stem filter (Stems Only / No Stems) ---------------------------------------------------------------------
// Tracks know whether they have stems. Album and artist cards are matched by folder name
// (stems are stored as Artist/Album/Track), which is close enough for a filter.
const nameKey = s => (s || "").toLowerCase().replace(/\s*[([][^)\]]*[)\]]/g, "").replace(/[^\p{L}\p{N}]+/gu, "");
let stemSetCache = null;
function stemSets() {
if (!stemSetCache) {
stemSetCache = { album: new Set(), artist: new Set() };
for (const e of Stems.entries) {
const p = e.key.split("/");
stemSetCache.album.add(nameKey(p.at(-2)));
stemSetCache.artist.add(nameKey(p.at(-3)));
}
}
return stemSetCache;
}
const cardHasStems = (kind, title) => stemSets()[kind]?.has(nameKey(title)) ?? true;
function applyStemFilter() {
document.body.classList.toggle("stems-only", S.stemFilter === "stems");
document.body.classList.toggle("no-stems", S.stemFilter === "nostems");
$$("[data-stemfilter]").forEach(b => b.classList.toggle("on", S.stemFilter === b.dataset.stemfilter));
kick?.();
}
// ---- waveform ---------------------------------------------------------------------------------
const Wave = {
peaks: null, key: null, canvas: $("#wave"), c: {},
colors() {
const cs = getComputedStyle(document.documentElement), v = n => cs.getPropertyValue(n).trim();
this.c = { accent: v("--accent"), bar: v("--wave"), ghost: v("--wave-ghost") };
this.draw();
},
async load(t) {
const e = t && Stems.find(t);
this.peaks = null; this.key = t?.id || null;
this.draw();
if (!t) return;
const key = this.key;
let peaks = null;
if (Offline.has(t.id)) peaks = (await Offline.get(t.id).catch(() => null))?.peaks;
else if (e) peaks = (await fetch(api("/api/peaks", { key: e.key, n: 300 })).then(r => r.ok ? r.json() : null).catch(() => null))?.stems;
if (this.key === key && peaks) { this.peaks = peaks; this.draw(); }
},
draw() {
const c = this.canvas, dpr = devicePixelRatio || 1, w = c.clientWidth, h = c.clientHeight;
if (!w) return;
if (c.width !== w * dpr) { c.width = w * dpr; c.height = h * dpr; }
const x = c.getContext("2d");
x.setTransform(dpr, 0, 0, dpr, 0, 0);
x.clearRect(0, 0, w, h);
const dur = E.duration(), frac = dur ? Math.min(1, E.position() / dur) : 0;
if (E.loading) {
x.fillStyle = this.c.ghost; x.fillRect(0, h / 2 - 2, w, 4);
x.fillStyle = this.c.bar; x.fillRect(0, h / 2 - 2, w * E.loadFrac, 4);
return;
}
if (!this.peaks) {
x.fillStyle = this.c.ghost; x.fillRect(0, h / 2 - 2, w, 4);
x.fillStyle = this.c.accent; x.fillRect(0, h / 2 - 2, w * frac, 4);
return;
}
const names = Object.keys(this.peaks), n = this.peaks[names[0]].length;
// The envelope only changes with the song or the mix, not every redraw.
const gains = names.map(nm => stemGain(nm, names)), gk = gains.join();
if (this.env?.peaks !== this.peaks || this.env.gk !== gk) {
const full = new Float32Array(n), mixed = new Float32Array(n);
names.forEach((nm, k) => {
const g = gains[k];
this.peaks[nm].forEach((p, i) => { const v = p / 1000; full[i] += v * v; mixed[i] += v * v * g * g; });
});
this.env = { peaks: this.peaks, gk, full, mixed, max: Math.sqrt(Math.max(...full)) || 1 };
}
const { full, mixed, max } = this.env;
const bars = Math.max(20, Math.floor(w / 3)), bw = w / bars;
for (let b = 0; b < bars; b++) {
const i = Math.floor(b / bars * n);
const v = Math.sqrt(mixed[i]) / max, ghost = Math.sqrt(full[i]) / max;
const gh = Math.max(2, ghost * h), bh = Math.max(2, v * h);
x.fillStyle = this.c.ghost; x.fillRect(b * bw, (h - gh) / 2, bw - 1, gh);
x.fillStyle = b / bars < frac ? this.c.accent : this.c.bar; x.fillRect(b * bw, (h - bh) / 2, bw - 1, bh);
}
},
// Redraws during playback only when the played part has grown by a bar (or a pixel without peaks).
follow() {
const w = this.canvas.clientWidth, dur = E.duration();
const steps = this.peaks ? Math.max(20, Math.floor(w / 3)) : w;
const at = dur ? Math.floor(Math.min(1, E.position() / dur) * steps) : 0;
if (at === this.at) return;
this.at = at;
this.draw();
},
};
{
let drag = false;
const at = ev => { const r = Wave.canvas.getBoundingClientRect(); return Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)) * E.duration(); };
Wave.canvas.addEventListener("pointerdown", ev => { drag = true; Wave.canvas.setPointerCapture(ev.pointerId); E.seek(at(ev)); });
Wave.canvas.addEventListener("pointermove", ev => { if (drag) E.seek(at(ev)); });
Wave.canvas.addEventListener("pointerup", () => { drag = false; saveQueue(); });
new ResizeObserver(() => Wave.draw()).observe(Wave.canvas);
}
// ---- player bar and drawers -------------------------------------------------------------------
let drawer = null; // "mixer" | "lyrics" | "queue"
const Lyr = { id: null, data: null, idx: -1 };
const artOf = (t, size) => t?.srv ? img(t.srv, t.thumb, size) : "";
// Feishin-style big art at the foot of the sidebar, opened from the art in the player bar.
const wide = matchMedia("(min-width: 861px)");
const SideArt = {
src: "",
show(on) { S.sideArt = on; save(); this.fill(); },
fill() {
const t = Radio.station ? null : Q.cur(), src = artOf(t, 640), on = !!(S.sideArt && src && wide.matches);
$("#app").classList.toggle("sideart", on);
$("#player").classList.toggle("sideart", on);
if (!on || src === this.src) return;
// Swap only once the new art has decoded, so it never flashes empty between tracks.
this.src = src;
const im = new Image(); im.src = src;
im.decode().catch(() => {}).then(() => { if (this.src === src) $("#sideart img").src = src; });
},
};
const UI = {
all() { this.track(); this.transport(); this.progress(); this.drawer(); marks(); },
track() {
const st = Radio.station;
$("#player").classList.toggle("radio", !!st);
if (st) {
$("#player").classList.remove("empty");
$("#np-title").textContent = st.name;
$("#np-sub").textContent = "Web Radio";
$("#np-art").removeAttribute("src");
$("#b-art").hidden = true; SideArt.fill(); ArtTheme.set("");
document.title = `${st.name} · Stemify`;
if ("mediaSession" in navigator) navigator.mediaSession.metadata = new MediaMetadata({ title: st.name, artist: "Web Radio" });
return;
}
const t = Q.cur();
$("#player").classList.toggle("empty", !t);
$("#np-title").textContent = t?.title || "Nothing playing";
$("#np-sub").textContent = t ? [t.artist, t.album].filter(Boolean).join(" · ") : "";
const art = artOf(t, 120);
if (art) $("#np-art").src = art; else $("#np-art").removeAttribute("src");
$("#b-art").hidden = !art; SideArt.fill(); ArtTheme.set(artOf(t, 64));
document.title = t ? `${t.title} · Stemify` : "Stemify";
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = t ? new MediaMetadata({
title: t.title, artist: t.artist, album: t.album, artwork: art ? [{ src: artOf(t, 512), sizes: "512x512" }] : [],
}) : null;
}
},
transport() {
const p = $("#b-play"), radio = !!Radio.station, playing = radio ? Radio.playing : E.playing, busy = !radio && E.buffering;
p.innerHTML = busy ? ICON.busy : playing ? ICON.pause : ICON.play;
p.classList.toggle("busy", busy);
p.title = E.loading ? `Loading stems ${Math.round(E.loadFrac * 100)}%` : "Play (Space)";
$("#b-shuffle").classList.toggle("on", S.shuffle);
$("#b-repeat").innerHTML = S.repeat === "one" ? ICON.repeat1 : ICON.repeat;
$("#b-repeat").classList.toggle("on", S.repeat !== "off");
$("#b-repeat").title = `Repeat: ${S.repeat} (R)`;
$("#speed").value = String(S.speed);
$("#speed").classList.toggle("on", S.speed !== 1);
for (const d of ["mixer", "lyrics", "queue"]) $(`#b-${d}`).classList.toggle("on", drawer === d);
$("#b-mixer").classList.toggle("dot", S.karaoke);
if ("mediaSession" in navigator) navigator.mediaSession.playbackState = playing ? "playing" : "paused";
if (drawer === "mixer") Meter.start();
},
progress() {
$("#t-pos").textContent = E.loading ? `${Math.round(E.loadFrac * 100)}%` : fmtTime(E.position());
$("#t-dur").textContent = fmtTime(E.duration());
Wave.draw();
const d = E.duration();
if (d && !Radio.station && navigator.mediaSession?.setPositionState) {
try { navigator.mediaSession.setPositionState({ duration: d, position: Math.min(d, E.position()), playbackRate: S.speed }); } catch {}
}
},
drawer() {
const d = $("#drawer");
d.hidden = !drawer;
if (drawer) {
const tabs = `<nav class="tabs">${["mixer", "lyrics", "queue"].map(k => `<button data-drawer="${k}" class="${drawer === k ? "on" : ""}">${k[0].toUpperCase() + k.slice(1)}</button>`).join("")}
<button class="x" data-drawer="" title="Close">×</button></nav>`;
d.innerHTML = tabs + `<div id="dbody">${drawer === "mixer" ? mixerHtml() : drawer === "queue" ? queueHtml() : lyricsShell()}</div>`;
if (drawer === "lyrics") loadLyrics();
if (drawer === "queue") $(".q-item.cur", d)?.scrollIntoView({ block: "center" });
d.classList.toggle("mixing", drawer === "mixer");
}
this.transport();
},
};
const toggleDrawer = m => { drawer = drawer === m || !m ? null : m; UI.drawer(); };
const mixNames = () => E.entry ? E.entry.stems.map(s => s.name).filter(n => E.names.includes(n)) : [];
const karaokeHtml = () => `<div class="kara">
<button class="chip ${S.karaoke ? "on" : ""}" data-kara title="Karaoke (K)">Karaoke</button>
<div class="seg">${[["off", "No vocals"], ["soft", "Soft vocals"], ["on", "Vocals on"]].map(([m, l]) => `<button class="${S.karaokeMode === m ? "on" : ""}" data-kmode="${m}">${l}</button>`).join("")}</div>
${S.karaokeMode === "soft" ? `<label class="note">Soft vocals: <b id="softdb">${S.softDb} dB</b><input type="range" min="-30" max="-3" step="1" value="${S.softDb}" data-softdb></label>` : ""}</div>`;
// Stem colors match the iOS app.
const STEM_COLORS = { vocals: "#ff7ab6", drums: "#ffb547", bass: "#7c8cff", other: "#4cd07d", guitar: "#ff8a5c", piano: "#b48cff", instrumental: "#3dd6c6" };
const pct = v => Math.round(v * 100) + "%";
function presetsHtml(names) {
const cur = currentPreset(names), lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset);
return presets().map(p => `<button class="chip ${cur?.id === p.id ? "on" : ""} ${lock?.id === p.id ? "locked" : ""}" data-preset="${esc(p.id)}" ${p.build(names) ? "" : "disabled"}
title="Tap again for Full Mix. Long press to ${lock?.id === p.id ? "unlock" : "lock"}.">${lock?.id === p.id ? ICON.lock : ""}${esc(presetLabel(p.name))}</button>`).join("") + `<button class="chip" data-newpreset title="Save this mix as a preset">+</button>`;
}
function mixFoot(names) {
const saved = songMixes[E.entry.key], same = saved && sameMix(saved, S.mix, names);
return `<div class="mixacts">
<button class="mact ${same ? "on" : ""}" data-savemix>${same ? ICON.check : ICON.save}<span>${same ? "Mix saved" : saved ? "Update mix" : "Save mix"}</span></button>
<button class="mact" data-mixtopl>${ICON.pladd}<span>Add to playlist</span></button>
${saved ? `<button class="mact ic" data-forgetmix title="Forget this song's saved mix">${ICON.x}</button>` : ""}
</div>`;
}
function mixerHtml() {
const names = mixNames();
if (!names.length) return `<p class="note">${E.loading ? "Loading stems…" : Q.cur() ? "No stems for this track." : "Nothing playing."}</p>`;
return `<div id="mixer" data-names="${esc(names.join(","))}">
<div class="presets">${presetsHtml(names)}</div>
<div class="strips">${names.map(n => {
const s = setting(n);
return `<div class="stem ${stemGain(n, names) ? "" : "silent"} ${s.muted ? "muted" : ""}" data-stem="${esc(n)}" style="--c:${STEM_COLORS[n] || "#8e8e93"}">
<div class="pct">${pct(s.level)}</div>
<div class="fader" data-fader="${esc(n)}" role="slider" aria-orientation="vertical" tabindex="0" aria-label="${esc(n)} level" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(s.level * 100)}" style="--v:${s.level}">
<i class="lvl"></i><i class="mtr"></i><i class="cap"><b></b></i></div>
<div class="name" title="${esc(n)}">${esc(n)}</div>
<div class="msrow"><button class="ms mute ${s.muted ? "on" : ""}" data-mute="${esc(n)}" title="Mute">M</button><button class="ms solo ${s.solo ? "on" : ""}" data-solo="${esc(n)}" title="Solo">S</button></div></div>`;
}).join("")}</div>
<div id="mixfoot">${mixFoot(names)}</div></div>`;
}
// Updates the open mixer in place, so taps answer at once and the slider being dragged keeps
// its grip. False when the stems changed and it needs a full render.
function syncMixer() {
const box = $("#mixer"), names = mixNames();
if (!box || box.dataset.names !== names.join(",")) return false;
const presetBox = box.querySelector(".presets"), html = presetsHtml(names);
if (presetBox.innerHTML !== html) presetBox.innerHTML = html;
for (const row of box.querySelectorAll(".stem")) {
const n = row.dataset.stem, st = setting(n);
row.classList.toggle("silent", !stemGain(n, names));
row.classList.toggle("muted", !!st.muted);
row.querySelector(".mute").classList.toggle("on", !!st.muted);
row.querySelector(".solo").classList.toggle("on", !!st.solo);
paintFader(row.querySelector(".fader"), st.level);
}
box.querySelector("#mixfoot").innerHTML = mixFoot(names);
return true;
}
const paintFader = (f, v) => {
if (f.style.getPropertyValue("--v") === String(v)) return;
f.style.setProperty("--v", v); f.setAttribute("aria-valuenow", Math.round(v * 100)); f.parentNode.querySelector(".pct").textContent = pct(v);
};
// Live meters: each stem's bar rises and falls with its audio (pre-fader peak, shown under the
// fader's level like the iOS mixer). Runs on animation frames only while the mixer is open and
// playing or still falling, and writes nothing but transforms.
const Meter = {
raf: 0, rows: null, box: null, shown: new Map(),
start() { if (!this.raf) this.raf = requestAnimationFrame(this.tick); },
tick: () => {
const M = Meter, box = $("#mixer");
M.raf = 0;
if (!box || drawer !== "mixer" || document.hidden) return;
if (M.box !== box) { M.box = box; M.rows = [...box.querySelectorAll(".stem")].map(r => ({ n: r.dataset.stem, el: r.querySelector(".mtr") })); M.shown.clear(); }
const playing = E.playing && !E.buffering, names = mixNames();
let moving = false;
for (const r of M.rows) {
const st = setting(r.n), live = playing && stemGain(r.n, names) ? E.meter(r.n) * st.level : 0;
const prev = M.shown.get(r.n) || 0, v = live >= prev ? live : Math.max(live, prev - 0.025);
if (Math.abs(v - prev) > 0.002 || (v === 0 && prev !== 0)) { r.el.style.transform = `scaleY(${v.toFixed(3)})`; M.shown.set(r.n, v); }
if (v > 0) moving = true;
}
if (playing || moving) M.start();
},
};
// Sets a stem's level live; the save and mixer refresh wait until the gesture settles.
let levelSave = 0;
function setLevel(n, v) {
v = Math.round(Math.max(0, Math.min(1, v)) * 100) / 100;
if (setting(n).level === v) return;
S.mix[n] = { ...setting(n), level: v }; E.applyGains(); Wave.draw();
const f = $(`#mixer .fader[data-fader="${CSS.escape(n)}"]`); if (f) paintFader(f, v);
clearTimeout(levelSave); levelSave = setTimeout(() => { save(); syncMixer(); }, 250);
}
function queueHtml() {
if (!Q.items.length) return `<p class="note">Empty.</p>`;
const left = Q.items.length - Q.i - 1;
return `<div class="row"><span class="note">${plural(left, "track")} up next</span><button class="btn small" data-qclear>Clear</button></div>
${Q.items.map((x, i) => `
<div class="q-item ${i === Q.i ? "cur" : i < Q.i ? "past" : ""}" data-q="${i}" draggable="true">
${artOf(x.t, 80) ? `<img loading="lazy" src="${esc(artOf(x.t, 80))}" alt="">` : `<div class="ph"></div>`}
<div class="tx"><div>${esc(x.t.title)}${x.mix ? ' <span class="tag">MIX</span>' : ""}</div><div>${esc(x.t.artist)}</div></div>
${i === Q.i ? "" : `<button class="x" data-qx="${i}" title="Remove">×</button>`}
</div>`).join("")}`;
}
const lyricsShell = () => `<div id="lyrhead">${mixNames().includes("vocals") ? karaokeHtml() : ""}</div><div id="lyr" class="note">Looking for lyrics…</div>`;
async function loadLyrics() {
const t = Q.cur(), box = $("#lyr");
Lyr.idx = -1;
if (!t) { box.textContent = "Nothing playing."; return; }
if (Lyr.id !== t.id) { Lyr.id = t.id; Lyr.data = null; Lyr.data = await lyricsFor(t).catch(() => null); }
if (Lyr.id !== t.id || drawer !== "lyrics" || !$("#lyr")) return;
const d = Lyr.data, el = $("#lyr");
if (!d) { el.textContent = "No lyrics found on LRCLIB."; return; }
if (d.instrumental) { el.textContent = "Instrumental."; return; }
el.className = d.lines ? "synced" : "plain";
el.innerHTML = d.lines ? d.lines.map((l, i) => `<p data-li="${i}">${esc(l.text) || "♪"}</p>`).join("") : esc(d.plain || "").replace(/\n/g, "<br>");
}
function tickLyrics() {
const lines = Lyr.data?.lines;
if (drawer !== "lyrics" || !lines || Lyr.id !== Q.cur()?.id) return;
const i = lineAt(lines, E.position());
if (i === Lyr.idx) return;
Lyr.idx = i;
$$("#lyr p.on").forEach(p => p.classList.remove("on"));
const p = $(`#lyr p[data-li="${i}"]`);
if (p) { p.classList.add("on"); p.scrollIntoView({ block: "center", behavior: "smooth" }); }
}
const d$ = $("#drawer");
d$.addEventListener("click", ev => {
const b = ev.target.closest("button, .q-item, #lyr p");
if (!b) return;
const names = mixNames(), ds = b.dataset;
if (ds.drawer != null) toggleDrawer(ds.drawer || null);
else if (ds.preset) applyPreset(currentPreset(names)?.id === ds.preset ? allPresets().find(p => p.id === "b:Full Mix") : presets().find(p => p.id === ds.preset), names);
else if ("newpreset" in ds) newPreset();
else if (ds.mute) { S.mix[ds.mute] = { ...setting(ds.mute), muted: !setting(ds.mute).muted }; mixChanged(); }
else if (ds.solo) { S.mix[ds.solo] = { ...setting(ds.solo), solo: !setting(ds.solo).solo }; mixChanged(); }
else if ("kara" in ds) setKaraoke(!S.karaoke);
else if (ds.kmode) setKaraokeMode(ds.kmode);
else if ("savemix" in ds) { saveSongMix(E.entry.key, S.mix); toast("Saved the mix for this song"); syncMixer() || UI.drawer(); }
else if ("forgetmix" in ds) { forgetSongMix(E.entry.key); syncMixer() || UI.drawer(); }
else if ("mixtopl" in ds) { const r = b.getBoundingClientRect(); pickPlaylist(r.left, r.bottom, [Q.cur()], S.mix); }
else if ("qclear" in ds) Q.clear();
else if (ds.qx) Q.remove(+ds.qx);
else if (ds.q) Q.jump(+ds.q);
else if (ds.li) E.seek(Lyr.data.lines[+ds.li].t);
});
// Faders: vertical. Grabbing the cap (or any touch) moves it from where it is; a mouse press
// elsewhere on the track jumps there first. Touches never scroll the drawer from a fader.
{
let drag = null;
const span = r => r.height - 8, val = (r, y) => (r.bottom - 4 - y) / span(r);
d$.addEventListener("pointerdown", ev => {
const f = ev.target.closest(".fader");
if (!f || ev.button) return;
ev.preventDefault();
const n = f.dataset.fader, r = f.getBoundingClientRect(), v = setting(n).level;
const onCap = Math.abs(ev.clientY - (r.bottom - 4 - v * span(r))) < 14;
drag = { f, n, id: ev.pointerId, y0: ev.clientY, v0: v, r, rel: onCap || ev.pointerType !== "mouse" };
f.setPointerCapture(ev.pointerId); f.classList.add("drag");
if (!drag.rel) setLevel(n, val(r, ev.clientY));
});
d$.addEventListener("pointermove", ev => {
if (!drag || ev.pointerId !== drag.id) return;
setLevel(drag.n, drag.rel ? drag.v0 + (drag.y0 - ev.clientY) / span(drag.r) : val(drag.r, ev.clientY));
});
const end = ev => {
if (!drag || ev.pointerId !== drag.id) return;
drag.f.classList.remove("drag"); drag = null;
};
d$.addEventListener("pointerup", end);
d$.addEventListener("pointercancel", end);
d$.addEventListener("dblclick", ev => { const f = ev.target.closest(".fader"); if (f) setLevel(f.dataset.fader, 1); });
d$.addEventListener("wheel", ev => {
const f = ev.target.closest(".fader");
if (!f) return;
ev.preventDefault();
setLevel(f.dataset.fader, setting(f.dataset.fader).level - Math.sign(ev.deltaY || ev.deltaX) * 0.02);
}, { passive: false });
d$.addEventListener("keydown", ev => {
const f = ev.target.closest(".fader");
if (!f) return;
const n = f.dataset.fader, v = setting(n).level, step = ev.shiftKey ? 0.1 : 0.02;
const to = { ArrowRight: v + step, ArrowUp: v + step, ArrowLeft: v - step, ArrowDown: v - step, Home: 0, End: 1 }[ev.key];
if (to == null) return;
ev.preventDefault(); ev.stopPropagation(); setLevel(n, to);
});
}
d$.addEventListener("input", ev => {
const ds = ev.target.dataset;
if (ds.softdb) $("#softdb").textContent = ev.target.value + " dB";
});
d$.addEventListener("change", ev => {
if (ev.target.dataset.softdb) setKaraokeMode("soft", +ev.target.value);
});
// Long press (or right-click) a preset chip to lock it.
{
let timer = 0, fired = false;
const lock = id => { fired = true; clearTimeout(timer); toggleLock(id, mixNames()); };
d$.addEventListener("pointerdown", ev => {
fired = false;
const b = ev.target.closest("[data-preset]");
if (b && !ev.button) timer = setTimeout(() => lock(b.dataset.preset), 550);
});
for (const e of ["pointerup", "pointerleave", "pointercancel"]) d$.addEventListener(e, () => clearTimeout(timer));
d$.addEventListener("contextmenu", ev => {
const b = ev.target.closest("[data-preset]");
if (!b) return;
ev.preventDefault();
if (!fired) lock(b.dataset.preset);
});
d$.addEventListener("click", ev => { if (fired && ev.target.closest("[data-preset]")) { ev.stopImmediatePropagation(); fired = false; } }, true);
}
function newPreset() {
const n = prompt("Name this preset");
if (n == null) return;
const err = savePreset(n, S.mix);
toast(err || `Saved “${n.trim()}”`);
}
{
let from = -1;
d$.addEventListener("dragstart", ev => { from = +ev.target.closest("[data-q]")?.dataset.q; });
d$.addEventListener("dragover", ev => { if (ev.target.closest("[data-q]")) ev.preventDefault(); });
d$.addEventListener("drop", ev => { const to = ev.target.closest("[data-q]"); if (to && from >= 0) { ev.preventDefault(); Q.move(from, +to.dataset.q); } from = -1; });
}
$("#b-play").innerHTML = ICON.play;
$("#b-prev").innerHTML = ICON.prev;
$("#b-next").innerHTML = ICON.next;
$("#b-shuffle").innerHTML = ICON.shuffle;
$("#b-mixer").innerHTML = ICON.mixer;
$("#b-lyrics").innerHTML = ICON.lyrics;
$("#b-queue").innerHTML = ICON.queue;
$("#speed").innerHTML = SPEEDS.map(v => `<option value="${v}">${v}×</option>`).join("");
$("#volume").value = S.volume; $("#volume").style.setProperty("--v", S.volume * 100 + "%");
const togglePlay = () => { if (Radio.station) return Radio.toggle(); if (!Q.cur()) return; E.playing ? E.pause() : E.play(); saveQueue(); };
$("#b-play").onclick = togglePlay;
$("#b-prev").onclick = () => Q.prev();
{
// Hold Next to skip the rest of the album.
const nb = $("#b-next");
let timer = 0, held = false;
nb.addEventListener("pointerdown", ev => { held = false; if (!ev.button) timer = setTimeout(() => { held = true; Q.skipAlbum(); }, 600); });
for (const e of ["pointerup", "pointerleave", "pointercancel"]) nb.addEventListener(e, () => clearTimeout(timer));
nb.addEventListener("contextmenu", ev => ev.preventDefault());
nb.onclick = () => { if (held) held = false; else Q.next(); };
}
$("#b-shuffle").onclick = () => Q.toggleShuffle();
$("#b-repeat").onclick = () => Q.cycleRepeat();
$("#b-mixer").onclick = () => toggleDrawer("mixer");
$("#b-lyrics").onclick = () => toggleDrawer("lyrics");
$("#b-queue").onclick = () => toggleDrawer("queue");
$("#speed").onchange = ev => setSpeed(+ev.target.value);
$("#volume").oninput = ev => { S.volume = +ev.target.value; ev.target.style.setProperty("--v", S.volume * 100 + "%"); E.applyGains(); save(); };
function applyBar() {
$("#speed").style.display = S.bar.speed ? "" : "none";
for (const k of ["mixer", "lyrics", "queue"]) $(`#b-${k}`).style.display = S.bar[k] ? "" : "none";
}
$("#b-art").onclick = ev => { if (wide.matches) { ev.stopPropagation(); SideArt.show(true); } };
$("#sideart .sa-col").onclick = () => SideArt.show(false);
$("#sideart .sa-img").onclick = () => { const t = Q.cur(); if (t?.albumKey) location.hash = `#/album/${t.srv}:${t.albumKey}`; };
wide.addEventListener("change", () => SideArt.fill());
$(".np").onclick = () => { const t = Q.cur(); if (t?.albumKey) location.hash = `#/album/${t.srv}:${t.albumKey}`; };
if ("mediaSession" in navigator) {
const ms = navigator.mediaSession;
ms.setActionHandler("play", () => Radio.station ? Radio.playing || Radio.toggle() : E.play());
ms.setActionHandler("pause", () => Radio.station ? Radio.playing && Radio.toggle() : E.pause());
ms.setActionHandler("previoustrack", () => Q.prev());
ms.setActionHandler("nexttrack", () => Q.next());
try { ms.setActionHandler("seekto", d => E.seek(d.seekTime)); } catch {}
}
document.addEventListener("keydown", ev => {
if (ev.key === "Escape") { Finder.close(); return Menu.close(); }
if (ev.target.closest("input, select, textarea") || ev.metaKey || ev.ctrlKey || ev.altKey) return;
const k = ev.key.toLowerCase();
if (k === "/" || (k === "s" && !ev.shiftKey)) { ev.preventDefault(); return Finder.open(); }
if (k === " ") { ev.preventDefault(); togglePlay(); }
else if (k === "arrowright") E.seek(Math.min(E.duration(), E.position() + (ev.shiftKey ? 30 : 5)));
else if (k === "arrowleft") E.seek(Math.max(0, E.position() - (ev.shiftKey ? 30 : 5)));
else if (k === "s") Q.toggleShuffle(); // Shift+S
else if (k === "r") Q.cycleRepeat();
else if (k === "m") toggleDrawer("mixer");
else if (k === "l") toggleDrawer("lyrics");
else if (k === "q") toggleDrawer("queue");
else if (k === "k") setKaraoke(!S.karaoke);
else if (k === "p") nextPreset(mixNames());
else if (k === "]" || k === "[") { const i = SPEEDS.indexOf(S.speed) + (k === "]" ? 1 : -1); if (SPEEDS[i]) setSpeed(SPEEDS[i]); }
});
// The clock, waveform and lyrics follow playback 5 times a second instead of every frame:
// none of them change faster than that, and a 120 Hz loop keeps phones warm.
setInterval(() => {
if (document.hidden || !E.playing || E.loading) return;
const t = fmtTime(E.position()), el = $("#t-pos");
if (el.textContent !== t) el.textContent = t;
Wave.follow(); tickLyrics();
}, 200);
setInterval(() => { if (E.playing) { UI.progress(); saveQueue(); } }, 5000);
on("track", () => { UI.track(); UI.transport(); UI.progress(); Wave.load(Q.cur()); marks(); if (drawer) UI.drawer(); });
on("transport", () => UI.transport());
on("progress", () => UI.progress());
on("loading", () => { UI.transport(); UI.progress(); });
on("attached", () => { UI.progress(); if (drawer === "mixer") UI.drawer(); });
on("queue", () => { if (drawer === "queue") UI.drawer(); });
on("radio", () => { UI.track(); UI.transport(); const el = $("#stations"); if (el) el.innerHTML = stationsHtml(); });
on("mix", () => {
Wave.draw(); UI.transport();
if (drawer === "mixer") syncMixer() || UI.drawer();
else if (drawer === "lyrics" && $("#lyrhead")) $("#lyrhead").innerHTML = mixNames().includes("vocals") ? karaokeHtml() : "";
});
// ---- live stem status ---------------------------------------------------------------------------
const base = p => (p || "").split("/").pop().replace(/\.[^.]+$/, "");
// Stems are the norm, so only songs without them get a tag (once the index has loaded).
const badge = t => {
if (Stems.find(t)) return "";
const s = Live.state(t);
if (s) return `<span class="tag ${s}">${{ queued: "QUEUED", stemming: "STEMMING", failed: "FAILED" }[s]}</span>`;
return Stems.entries.length ? '<span class="tag nostems">NO STEMS</span>' : "";
};
// Refreshes playing, stem and download markers in whatever is on screen.
function marks() {
const id = Q.cur()?.id;
document.body.classList.toggle("stems-ready", Stems.entries.length > 0);
for (const r of $$("tr[data-list]", view)) {
const t = lists[r.dataset.list]?.[+r.dataset.i];
if (!t) continue;
r.classList.toggle("playing", t.id === id);
r.classList.toggle("nostem", !Stems.find(t));
const b = $(".badge", r), html = badge(t);
if (b.innerHTML !== html) b.innerHTML = html;
$(".off", r).innerHTML = Offline.has(t.id) ? ICON.download : "";
}
for (const c of $$(".card[data-nk]", view)) c.classList.toggle("nostem", !stemSets()[c.dataset.kind]?.has(c.dataset.nk));
}
function liveStatus() {
const el = $("#live"), n = Live.pending.size;
el.hidden = !Live.busy;
el.innerHTML = Live.current ? `<span class="pulse"></span>Stemming “${esc(base(Live.current))}”${n ? ` · ${n} queued` : ""}` : n ? `${n} queued for stems` : "";
}
on("live", () => { marks(); liveStatus(); });
on("stems", () => { stemSetCache = null; marks(); });
on("offline", () => marks());
on("newstems", fresh => {
toast(fresh.length === 1 ? `Stems ready: ${base(fresh[0].key)}` : `Stems ready for ${fresh.length} tracks`);
const t = Q.cur();
if (t && !E.entry && !E.loading && Stems.find(t)) Q.reload();
});
document.addEventListener("visibilitychange", () => { if (!document.hidden) Live.poll(); });
// ---- context menu -------------------------------------------------------------------------------
const Menu = {
el: null,
open(x, y, items) {
this.close();
items = items.filter(Boolean);
const m = document.createElement("div");
m.id = "menu";
m.innerHTML = items.map((it, i) => it === "-" ? "<hr>" : it.head ? `<h5>${esc(it.head)}</h5>` : `<button data-mi="${i}" ${it.run ? "" : "disabled"} ${"check" in it ? `class="chk ${it.check ? "on" : ""}"` : ""}>${"check" in it ? ICON.check : ""}${esc(it.label)}</button>`).join("");
document.body.append(m);
const r = m.getBoundingClientRect();
m.style.left = Math.max(8, Math.min(x, innerWidth - r.width - 8)) + "px";
m.style.top = Math.max(8, Math.min(y, innerHeight - r.height - 8)) + "px";
m.onclick = ev => { const b = ev.target.closest("[data-mi]"); if (b) { const it = items[+b.dataset.mi]; this.close(); it.run(); } };
this.el = m;
},
close() { this.el?.remove(); this.el = this.from = null; },
};
addEventListener("pointerdown", ev => { if (Menu.el && !Menu.el.contains(ev.target) && !Menu.from?.contains(ev.target)) Menu.close(); }, true);
addEventListener("blur", () => Menu.close());
view.addEventListener("scroll", () => Menu.close(), { passive: true });
// ---- universal search (S) -----------------------------------------------------------------------
// One box over every enabled server: songs, artists, albums and playlists, plus stem playlists.
// Arrow keys move, Enter opens (or plays a song), Esc closes.
const Finder = {
el: null, items: [], at: 0, n: 0, timer: 0, pls: null, plsAt: 0,
build() {
const f = document.createElement("div");
f.id = "finder"; f.hidden = true;
f.innerHTML = `<div class="fbox" role="dialog" aria-label="Search"><label class="fin">${ICON.search}<input type="text" placeholder="Search songs, artists, albums, playlists" autocomplete="off" spellcheck="false"><kbd>esc</kbd></label><div class="fres" role="listbox"></div></div>`;
document.body.append(f);
const inp = f.querySelector("input"), res = f.querySelector(".fres");
f.addEventListener("pointerdown", ev => { if (ev.target === f) this.close(); });
inp.addEventListener("input", () => { clearTimeout(this.timer); this.timer = setTimeout(() => this.run(inp.value.trim()), 180); });
inp.addEventListener("keydown", ev => {
if (ev.key === "ArrowDown" || ev.key === "ArrowUp") { ev.preventDefault(); this.move(ev.key === "ArrowDown" ? 1 : -1); }
else if (ev.key === "Enter") { ev.preventDefault(); this.pick(this.at, ev.shiftKey); }
else if (ev.key === "Escape") { ev.preventDefault(); this.close(); }
});
res.addEventListener("pointermove", ev => { const r = ev.target.closest("[data-fi]"); if (r && +r.dataset.fi !== this.at) this.move(+r.dataset.fi - this.at); });
res.addEventListener("click", ev => { const r = ev.target.closest("[data-fi]"); if (r) this.pick(+r.dataset.fi, ev.shiftKey); });
this.el = f; this.inp = inp; this.res = res;
},
open() {
if (!this.el) this.build();
Menu.close();
this.el.hidden = false;
document.body.classList.add("finding");
this.inp.select(); this.inp.focus();
if (!this.inp.value) this.hint();
},
close() { if (!this.el || this.el.hidden) return; this.el.hidden = true; document.body.classList.remove("finding"); this.inp.blur(); },
hint() { this.items = []; this.res.innerHTML = `<p class="fmsg">Type to search every server. <kbd>↑</kbd><kbd>↓</kbd> to move, <kbd>↵</kbd> to open, <kbd>⇧↵</kbd> to queue a song.</p>`; },
// Plex playlists aren't in hub search results per section, so keep a short-lived list of them.
async plexPlaylists() {
if (!this.pls || Date.now() - this.plsAt > 120000) {
this.plsAt = Date.now();
this.pls = everything(liveServers().map(srv => ({ srv })), "/playlists", { playlistType: "audio" }).catch(() => []);
}
return this.pls;
},
async run(q) {
const n = ++this.n;
if (!q) return this.hint();
this.res.classList.add("busy");
const lq = q.toLowerCase(), has = s => (s || "").toLowerCase().includes(lq);
const [hubs, pls] = await Promise.all([
Promise.all(sources().map(s => px(s.srv, "/hubs/search", { query: q, limit: 8, sectionId: s.sec })
.then(mc => (mc.Hub || []).flatMap(h => (h.Metadata || []).map(m => (m._srv = s.srv.id, m._type = h.type, m)))).catch(() => []))).then(a => a.flat()),
this.plexPlaylists(),
]);
if (n !== this.n) return;
this.res.classList.remove("busy");
const of = t => hubs.filter(m => m._type === t), dedupe = (a, k) => [...new Map(a.map(x => [k(x), x])).values()];
const songs = dedupe(of("track").map(m => track(m._srv, m)), t => t.id).slice(0, 8);
const groups = [
["Songs", songs.map(t => ({ kind: "song", t: t.title, s: [t.artist, t.album].filter(Boolean).join(" · "), art: artOf(t, 96), track: t }))],
["Artists", dedupe(of("artist"), m => m._srv + m.ratingKey).slice(0, 5).map(m => ({ kind: "artist", t: m.title, s: "Artist", art: img(m._srv, m.thumb, 96), round: true, href: `#/artist/${m._srv}:${m.ratingKey}` }))],
["Albums", dedupe(of("album"), m => m._srv + m.ratingKey).slice(0, 6).map(m => ({ kind: "album", t: m.title, s: [m.parentTitle, m.year].filter(Boolean).join(" · "), art: img(m._srv, m.thumb, 96), href: `#/album/${m._srv}:${m.ratingKey}` }))],
["Playlists", [
...playlists.filter(p => has(p.title)).map(p => ({ kind: "playlist", t: p.title, s: `Stem playlist · ${plural(p.items.length, "track")}`, art: artOf(p.items[0]?.track, 96), href: `#/stemplaylist/${p.id}` })),
...pls.filter(p => has(p.title)).map(p => ({ kind: "playlist", t: p.title, s: `Playlist · ${plural(p.leafCount || 0, "track")}`, art: img(p._srv, p.thumb || p.composite, 96), href: `#/playlist/${p._srv}:${p.ratingKey}` })),
].slice(0, 6)],
].filter(g => g[1].length);
this.items = groups.flatMap(g => g[1]);
this.items.push({ kind: "all", t: `See all results for “${q}”`, href: "#/search/" + encodeURIComponent(q) });
let i = 0;
const row = it => `<div class="frow ${it.kind === "all" ? "fall" : ""}" role="option" data-fi="${i++}">${it.kind === "all" ? `<span class="fic">${ICON.search}</span>`
: `<span class="fart ${it.round ? "round" : ""}">${it.art ? `<img src="${esc(it.art)}" alt="" loading="lazy" decoding="async" ${FB}>` : ""}</span>`}
<span class="ftx"><b>${esc(it.t)}</b>${it.s ? `<small>${esc(it.s)}</small>` : ""}</span>${it.kind === "song" ? `<span class="fkey">Play</span>` : it.kind === "all" ? "" : `<span class="fkey">Open</span>`}</div>`;
this.res.innerHTML = (groups.length ? "" : `<p class="fmsg">No matches.</p>`) +
groups.map(([h, its]) => `<div class="fgrp"><h4>${h}</h4>${its.map(row).join("")}</div>`).join("") + row(this.items.at(-1));
this.at = 0; this.move(0);
},
move(d) {
if (!this.items.length) return;
this.at = (this.at + d + this.items.length) % this.items.length;
this.res.querySelector(".frow.on")?.classList.remove("on");
const r = this.res.querySelector(`[data-fi="${this.at}"]`);
r?.classList.add("on");
if (d) r?.scrollIntoView({ block: "nearest" });
},
pick(i, queue) {
const it = this.items[i];
if (!it) return;
this.close();
if (it.track) return queue ? Q.add([it.track], false) : Q.playList([it.track], 0, false);
location.hash = it.href;
},
};
$("#b-search").innerHTML = ICON.search;
$("#b-search").onclick = () => Finder.open();
const download = (tracks, group = null) => saveOffline(tracks, m => m && toast(m, 120000), group);
function stemItem(tracks) {
const need = tracks.filter(t => !Stems.find(t));
if (!need.length) return { label: tracks.length === 1 ? "Has stems" : "All have stems" };
if (tracks.length === 1) {
const s = Live.state(tracks[0]);
if (s === "stemming") return { label: "Stemming now…" };
if (s === "queued") return { label: "Queued for stems" };
if (!tracks[0].file) return { label: "Stem Now (no file path)" };
}
return { label: tracks.length === 1 ? "Stem Now" : `Stem Now (${need.length})`, run: () => stemNow(tracks) };
}
// Stem playlists live in the browser. Plex playlists take the songs from their own server.
async function pickPlaylist(x, y, tracks, mix = null) {
const add = p => { addToPlaylist(p, tracks, mix); toast(`Added to “${p.title}”${mix ? " with this mix" : ""}`); };
const srv = tracks.find(t => t.srv && t.key)?.srv, pts = tracks.filter(t => t.srv === srv && t.key);
const pls = srv && server(srv) && !mix ? ((await px(srv, "/playlists", { playlistType: "audio" }).catch(() => ({}))).Metadata || []).filter(p => !p.smart) : [];
const toPlex = async (key, title) => {
try {
const uri = await plexUri(srv, pts.map(t => t.key));
if (key) await pxSend(srv, "PUT", `/playlists/${key}/items`, { uri });
else await pxSend(srv, "POST", "/playlists", { type: "audio", title, smart: 0, uri });
Finder.pls = null;
toast(`Added to “${title}”`);
if (location.hash === `#/playlist/${srv}:${key}`) route();
} catch (e) { toast(e.message); }
};
Menu.open(x, y, [
{ head: "Stem playlists" },
{ label: "New stem playlist…", run: () => { const n = prompt("Stem playlist name"); if (n?.trim()) add(newPlaylist(n.trim())); } },
...playlists.map(p => ({ label: p.title, run: () => add(p) })),
...(srv && server(srv) && !mix ? ["-", { head: `Plex playlists · ${server(srv).name}` },
{ label: "New Plex playlist…", run: () => { const n = prompt("Plex playlist name"); if (n?.trim()) toPlex(null, n.trim()); } },
...pls.map(p => ({ label: p.title, run: () => toPlex(p.ratingKey, p.title) }))] : []),
]);
}
function trackMenu(x, y, listId, i) {
const t = lists[listId][i], pl = listId.startsWith("spl:") && playlists.find(p => p.id === listId.slice(4));
Menu.open(x, y, [
{ label: "Play", run: () => playFrom(listId, i) },
{ label: "Play next", run: () => Q.add([listItems[listId]?.[i] || t], true) },
{ label: "Add to queue", run: () => Q.add([listItems[listId]?.[i] || t]) },
"-",
stemItem([t]),
{ label: "Add to playlist…", run: () => pickPlaylist(x, y, [t]) },
Offline.has(t.id) ? { label: "Remove download", run: () => Offline.remove(t.id).then(() => emit("offline")) }
: { label: "Download for offline", run: () => download([t]) },
(t.albumKey || t.artistKey) && "-",
t.albumKey && { label: "Go to album", run: () => { location.hash = `#/album/${t.srv}:${t.albumKey}`; } },
t.artistKey && { label: "Go to artist", run: () => { location.hash = `#/artist/${t.srv}:${t.artistKey}`; } },
pl && "-",
pl && Q.cur()?.id === t.id && E.entry && { label: "Use the current mix here", run: () => { pl.items[i].mix = JSON.parse(JSON.stringify(S.mix)); savePlaylists(); route(); } },
pl && pl.items[i].mix && { label: "Clear this item's mix", run: () => { pl.items[i].mix = null; savePlaylists(); route(); } },
pl && { label: "Remove from playlist", run: () => { pl.items.splice(i, 1); pl.updated = Date.now(); savePlaylists(); route(); } },
listId === "playlist" && curPx?.editable && t.pid != null && "-",
listId === "playlist" && curPx?.editable && t.pid != null && { label: "Remove from playlist", run: async () => {
try { await pxSend(curPx.srv, "DELETE", `/playlists/${curPx.key}/items/${t.pid}`); Finder.pls = null; route(); } catch (e) { toast(e.message); }
} },
]);
}
async function leaves(srv, key) { return ((await px(srv, `/library/metadata/${key}/allLeaves`)).Metadata || []).map(m => track(srv, m)); }
// The image's current src plus its fallback (Plex playlist composites often fail to transcode).
const artUrls = im => im ? [im.src, im.getAttribute("data-fb")].filter(u => u && !u.startsWith("data:")) : [];
function listMenu(x, y, get, group = null) {
const run = fn => async () => { try { fn(visible(await get())); } catch (e) { toast(e.message); } };
Menu.open(x, y, [
{ label: "Play", run: run(ts => Q.playList(ts, 0, false)) },
{ label: "Shuffle", run: run(ts => Q.playList(ts, -1, true)) },
{ label: "Play next", run: run(ts => Q.add(ts, true)) },
{ label: "Add to queue", run: run(ts => Q.add(ts)) },
"-",
{ label: "Stem Now", run: run(ts => stemNow(ts)) },
{ label: "Add to playlist…", run: run(ts => pickPlaylist(x, y, ts)) },
{ label: "Download for offline", run: run(ts => download(ts, group)) },
]);
}
// ---- views --------------------------------------------------------------------------------------
let curPx = null, pxEdit = null;
let lists = {}, listItems = {}, seq = 0, kick = null, genreCache = null;
const visible = tracks => S.stemFilter ? tracks.filter(t => !!Stems.find(t.t || t) === (S.stemFilter === "stems")) : tracks;
function playFrom(listId, i) {
const all = listItems[listId] || lists[listId], pick = all[i];
const vis = visible(all);
Q.playList(vis.includes(pick) ? vis : all, Math.max(0, (vis.includes(pick) ? vis : all).indexOf(pick)), false);
}
// A broken image tries its fallback (data-fb) once, then shows the placeholder.
const FB = `onerror="if(this.dataset.fb){this.src=this.dataset.fb;this.dataset.fb=''}else{this.onerror=null;this.src='data:image/gif;base64,R0lGODlhAQABAAAAACw='}"`;
function card({ href, img: src, fb, t, s = "", round, kind, srv, key, dl }) {
const nk = kind === "album" || kind === "artist" ? nameKey(t) : "";
const hide = nk && !stemSets()[kind].has(nk);
return `<a class="card ${round ? "round" : ""} ${hide ? "nostem" : ""}" href="${href}" ${kind ? `data-kind="${kind}" data-srv="${esc(srv)}" data-key="${esc(key)}"` : ""} ${dl != null ? `data-dl="${dl}"` : ""} ${nk ? `data-nk="${esc(nk)}"` : ""}>
<div class="art">${src ? `<img loading="lazy" decoding="async" src="${esc(src)}" ${fb ? `data-fb="${esc(fb)}"` : ""} ${FB} alt="">` : `<div class="ph"></div>`}${kind || dl != null ? `<button class="cplay" data-cardplay title="Play">${ICON.play}</button>` : ""}</div><div class="t">${esc(t)}</div><div class="s">${esc(s)}</div></a>`;
}
// Tracks behind a card, for its play button and right-click menu.
async function cardTracks(c) {
const { kind, srv, key, dl } = c.dataset;
if (dl != null) return lists["dl:" + dl] || [];
if (kind === "playlist") return ((await px(srv, `/playlists/${key}/items`)).Metadata || []).map(m => track(srv, m));
return leaves(srv, key);
}
const albumCard = m => card({ href: `#/album/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, s: [m.parentTitle, m.year].filter(Boolean).join(" · "), kind: "album", srv: m._srv, key: m.ratingKey });
const artistCard = m => card({ href: `#/artist/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, round: true, kind: "artist", srv: m._srv, key: m.ratingKey });
const rowHtml = (listId, t, i, { numbers, album = true, mix } = {}) => `
<tr data-list="${listId}" data-i="${i}" class="${Stems.find(t) ? "" : "nostem"} ${Q.cur()?.id === t.id ? "playing" : ""}">
<td class="n">${numbers ? t.index ?? i + 1 : i + 1}</td>
<td class="ti"><div class="tt">${esc(t.title)}<span class="badge">${badge(t)}</span>${mix ? '<span class="tag">MIX</span>' : ""}</div><small>${esc(t.artist || "")}</small></td>
${album ? `<td class="al">${esc(t.album || "")}</td>` : ""}
<td class="off">${Offline.has(t.id) ? ICON.download : ""}</td>
<td class="d">${fmtTime(t.duration / 1000)}</td>
<td class="acts"><button data-add title="Add to queue (shift: play next)">+</button><button data-menu title="More">${ICON.more}</button></td>
</tr>`;
const CLOCK = '<svg viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20zm0 2a8 8 0 1 0 0 16 8 8 0 0 0 0-16zm-1 3h2v4.6l3.4 2-1 1.7L11 12.7V7z"/></svg>';
const thead = (album = true) => `<thead><tr><th class="n">#</th><th class="ti">Title</th>${album ? '<th class="al">Album</th>' : ""}<th class="off"></th><th class="d">${CLOCK}</th><th class="acts"></th></tr></thead>`;
function trackTable(listId, tracks, opts = {}) {
lists[listId] = tracks;
if (!tracks.length) return `<p class="empty-msg">Nothing here.</p>`;
return `<table class="tracks">${thead(opts.album)}<tbody>${tracks.map((t, i) => rowHtml(listId, t, i, { ...opts, mix: listItems[listId]?.[i]?.mix })).join("")}</tbody></table>
<p class="empty-msg only-stems">None of these have stems yet.</p><p class="empty-msg only-nostems">All of these have stems.</p>`;
}
const stemsChip = () => `<div class="seg stemfilter">${[["stems", "Stems Only"], ["nostems", "No Stems"]].map(([v, l]) =>
`<button class="${S.stemFilter === v ? "on" : ""}" data-stemfilter="${v}">${l}</button>`).join("")}</div>`;
function sortControl(screen) {
const st = sortState(screen);
return `<button class="sortbtn" data-sortmenu="${screen}" title="Sort" aria-haspopup="menu">${ICON.sort}<span>${st.o[0]}</span>` +
`${st.random ? "" : `<small>${st.desc ? st.o[4] : st.o[3]}</small>`}<i class="caret"></i></button>`;
}
// The sort menu: fields with a check on the current one, then the two directions (or reshuffle).
function sortMenu(btn) {
const screen = btn.dataset.sortmenu, st = sortState(screen), r = btn.getBoundingClientRect(), go = f => () => { f(); route(); };
Menu.open(r.left, r.bottom + 6, [
{ head: "Sort by" },
...st.opts.map((o, i) => ({ label: o[0], check: i === st.i, run: go(() => i !== st.i && pickSort(screen, i)) })),
"-",
...(st.random ? [{ label: "Shuffle again", run: () => route() }]
: [{ label: st.o[3], check: !st.desc, run: go(() => pickSort(screen, st.i, false)) }, { label: st.o[4], check: st.desc, run: go(() => pickSort(screen, st.i, true)) }]),
]);
Menu.el.classList.add("sortmenu"); Menu.from = btn;
}
const bar = (title, { sort, filter = true, extra = "" } = {}) =>
`<div class="bar"><h1>${esc(title)}</h1><span class="sub" id="count"></span><span class="grow"></span>${extra}${filter ? stemsChip() : ""}${sort ? sortControl(sort) : ""}</div>`;
const actions = id => `<div class="actions">
<button class="bigplay" data-play="${id}" title="Play">${ICON.play}</button>
<button class="ibtn" data-play="${id}" data-mode="shuffle" title="Shuffle">${ICON.shuffle}</button>
<button class="btn" data-play="${id}" data-mode="stem">Stem Now</button>
<button class="ibtn" data-listmenu="${id}" title="More">${ICON.more}</button></div>`;
const hero = (src, kind, title, sub, id, round, fb) => `<header class="hero">${src ? `<div class="hero-bg"><img src="${esc(src)}" alt="" onerror="this.style.display='none'"></div>` : ""}
<div class="hero-in">${src ? `<img class="art ${round ? "round" : ""}" src="${esc(src)}" ${fb ? `data-fb="${esc(fb)}"` : ""} ${FB} alt="">` : `<div class="ph ${round ? "round" : ""}"></div>`}
<div class="meta"><div class="kind">${kind}</div><h1>${esc(title)}</h1><div class="sub">${sub}</div></div></div></header>${id ? actions(id) : ""}`;
function needPlex() {
view.innerHTML = `<h1>Welcome</h1><p class="sub">Add a Plex server in <a class="link" href="#/settings">Settings</a> to browse your library, or <a class="link" href="#/stems">browse the stems</a> on their own.</p>`;
}
const splitKey = arg => { const i = arg.lastIndexOf(":"); return [arg.slice(0, i), arg.slice(i + 1)]; };
const count = (n, w) => { const c = $("#count"); if (c) c.textContent = n ? plural(n, w) : ""; };
// Appends pages from a Pager as you scroll. `html(items, offset)` renders a page.
async function paged(mySeq, target, pager, size, html, word) {
const more = document.createElement("div");
more.className = "more";
(target.closest("table") || target).after(more);
let busy = false, shown = 0;
const next = async () => {
if (busy || pager.done || mySeq !== seq) return;
busy = true;
let items;
try { items = await pager.next(size); }
catch (e) { more.textContent = e.message; busy = false; return; }
if (mySeq !== seq) return;
target.insertAdjacentHTML("beforeend", html(items, shown));
shown += items.length;
count(pager.total, word);
busy = false;
if (pager.done && !shown) more.outerHTML = `<p class="empty-msg">Nothing here.</p>`;
else if (!pager.done && more.getBoundingClientRect().top < innerHeight * 1.5) next();
};
kick = next;
new IntersectionObserver(es => { if (es[0].isIntersecting) next(); }, { root: view, rootMargin: "600px" }).observe(more);
await next();
}
const secPath = s => `/library/sections/${s.sec}/all`;
async function genres() {
if (genreCache && Date.now() - genreCache.at < 10 * 60e3) return genreCache.list;
const by = new Map();
for (const g of await everything(sources(), s => `/library/sections/${s.sec}/genre`, { type: 9 })) {
const k = g.title.toLowerCase();
if (!by.has(k)) by.set(k, { title: g.title, srcs: [] });
const src = sources().find(s => s.srv.id === g._srv && s.sec === g._sec);
by.get(k).srcs.push({ ...src, params: { genre: g.key.match(/(\d+)\D*$/)?.[1] ?? g.key } });
}
genreCache = { at: Date.now(), list: [...by.values()].sort((a, b) => a.title.localeCompare(b.title)) };
return genreCache.list;
}
const hue = s => [...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 360, 7);
// Downloads the way iOS shows them: Playlists, Albums and Artists as card grids, then loose songs.
let dlUrls = [];
const DL_KINDS = [["Playlists", h => !/^#\/(album|artist)\//.test(h)], ["Albums", h => h.startsWith("#/album/")], ["Artists", h => h.startsWith("#/artist/")]];
function dlGroups(recs) {
const by = new Map(), loose = [];
for (const r of recs) {
const k = r.group?.href;
if (!k) { loose.push(r); continue; }
if (!by.has(k)) by.set(k, { g: r.group, recs: [] });
by.get(k).recs.push(r);
}
const gs = [...by.values()];
gs.forEach((x, n) => { x.n = n; x.recs.sort((a, b) => a.saved - b.saved); lists["dl:" + n] = x.recs.map(r => r.track); });
dlUrls.forEach(u => URL.revokeObjectURL(u)); dlUrls = [];
const blobUrl = b => b instanceof Blob ? (dlUrls.push(URL.createObjectURL(b)), dlUrls.at(-1)) : "";
const tile = ({ g, recs, n }) => {
const t = recs[0].track, h = g.href, songs = plural(recs.length, "song");
const art = blobUrl(g.art) || blobUrl(recs.find(r => r.group?.art instanceof Blob)?.group.art) || blobUrl(recs.find(r => r.art)?.art) || artOf(recs.find(r => r.track.thumb)?.track, 300);
const s = h.startsWith("#/album/") ? t.artist || "" : h.startsWith("#/artist/") ? songs : `Playlist · ${songs}`;
return card({ href: esc(h), img: art, t: g.title, s, round: h.startsWith("#/artist/"), dl: n });
};
return DL_KINDS.map(([title, test]) => {
const list = gs.filter(x => test(x.g.href));
return list.length ? `<section class="dlgroup"><div class="bar sm"><h2>${title}</h2></div><div class="grid">${list.map(tile).join("")}</div></section>` : "";
}).join("") + (loose.length ? `<section class="dlgroup"><div class="bar sm"><h2>Other Songs</h2><span class="grow"></span>
<button class="chip" data-dlgroup="loose">Remove</button></div>${trackTable("dl:loose", loose.map(r => r.track))}</section>` : "");
}
// Albums whose original release date falls today (or within three days) in an earlier year.
function birthdays(albums) {
const now = new Date(), y = now.getFullYear(), today = new Date(y, now.getMonth(), now.getDate());
const leap = new Date(y, 1, 29).getMonth() === 1, onDay = [], week = [];
for (const m of albums) {
const d = m.originallyAvailableAt || "";
if (d.length < 10) continue;
const ry = +d.slice(0, 4), mo = +d.slice(5, 7) - 1;
let da = +d.slice(8, 10);
if (!ry || ry >= y) continue;
if (mo === 1 && da === 29 && !leap) da = 28;
const when = new Date(y, mo, da), diff = Math.round((when - today) / 864e5), years = y - ry;
if (!diff) onDay.push({ m, years });
else if (Math.abs(diff) <= 3) week.push({ m, years, when, diff });
}
onDay.sort((a, b) => b.years - a.years);
week.sort((a, b) => a.diff - b.diff || b.years - a.years);
return { onDay, week };
}
const bdayCard = ({ m, years, when, diff }) => card({
href: `#/album/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, kind: "album", srv: m._srv, key: m.ratingKey,
s: when ? `${diff < 0 ? "Turned" : "Turns"} ${years} · ${when.toLocaleDateString(undefined, { month: "short", day: "numeric" })}` : `${m.parentTitle} · ${years === 1 ? "1 year ago" : `${years} years ago`}`,
});
const shelf = cards => `<div class="shelf ${cards.length > 4 ? "two" : ""}">${cards.join("")}</div>`;
const stationsHtml = () => S.stations.length ? `<div class="stationlist">${S.stations.map(st => {
const on = Radio.station?.id === st.id, playing = on && Radio.playing;
return `<div class="stn ${on ? "on" : ""}"><button class="btn icon ${playing ? "primary" : ""}" data-radio="${esc(st.id)}" title="${playing ? "Stop" : "Play"}">${playing ? ICON.pause : ICON.play}</button>
<div class="tx"><b>${esc(st.name)}</b><span class="note">${esc(st.url)}</span></div>
<button class="btn small" data-rdrename="${esc(st.id)}">Rename</button><button class="btn small" data-rddelete="${esc(st.id)}">Delete</button></div>`;
}).join("")}</div>` : `<p class="empty-msg">No stations yet.</p>`;
const routes = {
async home(my) {
const srcs = sources();
if (!srcs.length) return needPlex();
const today = new Date().toLocaleDateString(undefined, { month: "long", day: "numeric" });
view.innerHTML = `<h1>Home</h1>
<section id="h-recent"><h2>Recent Plays</h2><p class="note">Loading…</p></section>
<section id="h-added"><h2>Recently Added</h2><p class="note">Loading…</p></section>
<section id="h-otd"><h2>On This Day</h2><p class="sub">${esc(today)}</p><p class="note">Loading…</p></section>
<section><h2>Stations</h2><div class="stations">
<button class="station" data-station="library"><b>Library Radio</b><span>Random songs from your whole library</span></button>
<button class="station" data-station="albums"><b>Random Album Radio</b><span>Ten random albums, each played in order</span></button></div></section>`;
const fill = (id, html) => { const el = $(id); if (el && my === seq) { el.querySelector(".note").outerHTML = html; marks(); } };
const fail = id => e => fill(id, `<p class="note">${esc(e.message)}</p>`);
await Promise.all([
new Pager(srcs, secPath, { type: 9, sort: "lastViewedAt:desc", "viewCount>>": 0 }, 24).next(24)
.then(ms => fill("#h-recent", ms.length ? shelf(ms.map(albumCard)) : `<p class="note">Nothing played yet.</p>`), fail("#h-recent")),
new Pager(srcs, secPath, { type: 10, sort: "addedAt:desc" }, 10).next(10)
.then(ms => my === seq && fill("#h-added", trackTable("added", ms.map(m => track(m._srv, m)))), fail("#h-added")),
everything(srcs, secPath, { type: 9 }).then(all => {
const { onDay, week } = birthdays(all);
fill("#h-otd", (onDay.length ? shelf(onDay.map(bdayCard)) : `<p class="note">${week.length ? "No album birthdays today. Coming up and just past:" : "No albums in your library came out this week in any year."}</p>`)
+ (onDay.length && week.length ? `<p class="note">Coming up and just past</p>` : "") + (week.length ? shelf(week.map(bdayCard)) : ""));
}, fail("#h-otd")),
]);
},
radio() {
view.innerHTML = bar("Web Radio", { filter: false }) + `<div id="stations">${stationsHtml()}</div>
<h2>Add a station</h2><div class="form">
<label>Name<input type="text" id="rname" placeholder="KEXP"></label>
<label>Stream URL<input type="url" id="rurl" placeholder="https://example.com/stream.mp3"></label>
<div class="row"><button class="btn primary" data-rdadd>Add station</button></div></div>`;
},
async albums(my) {
const srcs = sources();
if (!srcs.length) return needPlex();
view.innerHTML = bar("Albums", { sort: "albums" }) + `<div class="grid"></div>`;
await paged(my, $(".grid", view), new Pager(srcs, secPath, { type: 9, sort: sortState("albums").param }), 120, ms => ms.map(albumCard).join(""), "album");
},
async artists(my) {
const srcs = sources();
if (!srcs.length) return needPlex();
view.innerHTML = bar("Artists", { sort: "artists" }) + `<div class="grid"></div>`;
await paged(my, $(".grid", view), new Pager(srcs, secPath, { type: 8, sort: sortState("artists").param }), 120, ms => ms.map(artistCard).join(""), "artist");
},
async songs(my) {
const srcs = sources();
if (!srcs.length) return needPlex();
view.innerHTML = bar("Songs", { sort: "songs", extra: `<button class="chip" data-shuffleall>${ICON.shuffle} Shuffle all</button>` })
+ `<table class="tracks">${thead()}<tbody></tbody></table><p class="empty-msg only-stems">No songs with stems yet.</p><p class="empty-msg only-nostems">Every song has stems.</p>`;
lists.songs = [];
const size = S.stemFilter ? 1000 : 150;
await paged(my, $("tbody", view), new Pager(srcs, secPath, { type: 10, sort: sortState("songs").param }, size), size, (ms, off) => {
const ts = ms.map(m => track(m._srv, m));
lists.songs.push(...ts);
return ts.map((t, i) => rowHtml("songs", t, off + i)).join("");
}, "song");
},
async genres(my) {
if (!sources().length) return needPlex();
view.innerHTML = bar("Genres", { filter: false }) + `<p class="note">Loading…</p>`;
const list = await genres();
if (my !== seq) return;
count(list.length, "genre");
view.innerHTML = bar("Genres", { filter: false }) + (list.length ? `<div class="grid genres">${list.map(g =>
`<a class="genre" style="--h:${hue(g.title)}" href="#/genre/${encodeURIComponent(g.title)}">${esc(g.title)}</a>`).join("")}</div>` : `<p class="empty-msg">No genres.</p>`);
count(list.length, "genre");
},
async genre(my, title) {
const g = (await genres()).find(x => x.title === title);
if (my !== seq) return;
if (!g) { view.innerHTML = `<h1>${esc(title)}</h1><p class="empty-msg">No albums in this genre.</p>`; return; }
view.innerHTML = bar(g.title, { sort: "albums", extra: `<button class="chip" data-genreplay="shuffle">${ICON.shuffle} Shuffle</button>` }) + `<div class="grid"></div>`;
view.dataset.genre = g.title;
await paged(my, $(".grid", view), new Pager(g.srcs, secPath, { type: 9, sort: sortState("albums").param }), 120, ms => ms.map(albumCard).join(""), "album");
},
async playlists(my) {
const st = sortState("playlists");
view.innerHTML = bar("Playlists", { sort: "playlists", filter: false })
+ `<div class="bar sm"><h2>Stem playlists</h2><button class="chip" data-newpl>+ New</button></div>`
+ (playlists.length ? `<div class="grid">${playlists.map(p => card({ href: `#/stemplaylist/${p.id}`, img: artOf(p.items[0]?.track, 300), t: p.title, s: plural(p.items.length, "track") })).join("")}</div>`
: `<p class="empty-msg">No stem playlists.</p>`)
+ `<h2>Plex playlists</h2><div id="plexpl"><p class="note">${liveServers().length ? "Loading…" : "No Plex server set up."}</p></div>`;
if (!liveServers().length) return;
let pls = await everything(liveServers().map(srv => ({ srv })), "/playlists", { playlistType: "audio" });
if (my !== seq) return;
pls = st.random ? pls.sort(() => Math.random() - 0.5) : pls.sort(comparator(st.param));
count(pls.length + playlists.length, "playlist");
$("#plexpl").innerHTML = pls.length ? `<div class="grid">${pls.map(p => card({ href: `#/playlist/${p._srv}:${p.ratingKey}`, img: img(p._srv, p.thumb || p.composite), fb: p.composite && rawImg(p._srv, p.composite), t: p.title, s: plural(p.leafCount || 0, "track"), kind: "playlist", srv: p._srv, key: p.ratingKey })).join("")}</div>`
: `<p class="empty-msg">No music playlists.</p>`;
},
async album(my, arg) {
const [srv, key] = splitKey(arg);
const [info, kids] = await Promise.all([px(srv, `/library/metadata/${key}`), px(srv, `/library/metadata/${key}/children`)]);
if (my !== seq) return;
const a = info.Metadata?.[0] || {}, tracks = sortTracks((kids.Metadata || []).map(m => track(srv, m)), sortState("album"));
const stems = tracks.filter(t => Stems.find(t)).length;
view.innerHTML = hero(img(srv, a.thumb, 420), "Album", a.title,
`<a href="#/artist/${srv}:${a.parentRatingKey}">${esc(a.parentTitle)}</a>${a.year ? " · " + a.year : ""} · ${plural(tracks.length, "track")}${stems ? ` · ${stems} with stems` : ""}`, "album")
+ `<div class="bar sm"><span class="grow"></span>${stemsChip()}${sortControl("album")}</div>` + trackTable("album", tracks, { numbers: !sortState("album").o[1], album: false });
},
async artist(my, arg) {
const [srv, key] = splitKey(arg);
const [info, kids] = await Promise.all([px(srv, `/library/metadata/${key}`), px(srv, `/library/metadata/${key}/children`)]);
if (my !== seq) return;
const a = info.Metadata?.[0] || {}, albums = (kids.Metadata || []).map(m => (m._srv = srv, m));
view.innerHTML = hero(img(srv, a.thumb, 420), "Artist", a.title, plural(albums.length, "album"), "artist", true)
+ `<div class="bar sm"><h2>Albums</h2><span class="grow"></span>${stemsChip()}</div><div class="grid">${albums.map(albumCard).join("")}</div>
<div class="bar sm"><h2>Songs</h2><span class="grow"></span>${sortControl("artist")}</div><div id="artist-songs"><p class="note">Loading…</p></div>`;
const tracks = sortTracks(await leaves(srv, key), sortState("artist"));
if (my !== seq) return;
$("#artist-songs").innerHTML = trackTable("artist", tracks);
},
async playlist(my, arg) {
const [srv, key] = splitKey(arg);
const [info, items] = await Promise.all([px(srv, `/playlists/${key}`), px(srv, `/playlists/${key}/items`)]);
if (my !== seq) return;
const p = info.Metadata?.[0] || {}, raw = (items.Metadata || []).map(m => track(srv, m)), tracks = sortTracks(raw, sortState("playlist"));
curPx = { srv, key, title: p.title, editable: !p.smart, raw };
const id = esc(arg), tools = p.smart ? " · Smart playlist" : ` · <button class="link" data-pxedit="${id}">Edit</button> · <button class="link" data-pxrename="${id}">Rename</button> · <button class="link" data-pxdelete="${id}">Delete</button>`;
view.innerHTML = hero(img(srv, p.thumb || p.composite, 420), "Playlist", p.title, plural(tracks.length, "track") + tools, "playlist", false, p.composite && rawImg(srv, p.composite, 420))
+ `<div id="pxbody"><div class="bar sm"><span class="grow"></span>${stemsChip()}${sortControl("playlist")}</div>${trackTable("playlist", tracks)}</div>`;
},
async stemplaylist(my, id) {
const p = playlists.find(x => x.id === id);
if (!p) { view.innerHTML = `<h1>Not found</h1><p class="sub">This stem playlist was deleted.</p>`; return; }
const lid = "spl:" + id;
listItems[lid] = p.items.map(x => ({ t: x.track, mix: x.mix }));
view.innerHTML = hero(artOf(p.items[0]?.track, 420), "Stem playlist", p.title,
`${plural(p.items.length, "track")} · ${p.items.filter(x => x.mix).length} with their own mix
· <button class="link" data-plrename="${id}">Rename</button> · <button class="link" data-pldelete="${id}">Delete</button>`, lid)
+ `<div class="bar sm"><span class="grow"></span>${stemsChip()}</div>` + trackTable(lid, p.items.map(x => x.track));
},
async search(my, q) {
const srcs = sources();
if (!srcs.length) return needPlex();
const hubs = (await Promise.all(srcs.map(s => px(s.srv, "/hubs/search", { query: q, limit: 12, sectionId: s.sec })
.then(mc => (mc.Hub || []).map(h => ({ ...h, Metadata: (h.Metadata || []).map(m => (m._srv = s.srv.id, m)) }))).catch(() => [])))).flat();
if (my !== seq) return;
const hub = t => hubs.filter(h => h.type === t).flatMap(h => h.Metadata);
const artists = hub("artist"), albums = hub("album"), tracks = sortTracks(hub("track").map(m => track(m._srv, m)), sortState("search"));
view.innerHTML = bar(`“${q}”`) +
(artists.length ? `<h2>Artists</h2><div class="grid">${artists.map(artistCard).join("")}</div>` : "") +
(albums.length ? `<h2>Albums</h2><div class="grid">${albums.map(albumCard).join("")}</div>` : "") +
(tracks.length ? `<div class="bar sm"><h2>Songs</h2><span class="grow"></span>${sortControl("search")}</div>${trackTable("search", tracks)}` : "") +
(!artists.length && !albums.length && !tracks.length ? `<p class="empty-msg">No results.</p>` : "");
},
async downloads(my) {
const recs = (await Offline.all().catch(() => [])).sort((a, b) => b.saved - a.saved);
if (my !== seq) return;
const total = recs.reduce((a, r) => a + r.size, 0);
const est = await navigator.storage?.estimate?.().catch(() => null);
lists["dl:all"] = recs.map(r => r.track);
view.innerHTML = bar("Downloads", { filter: false, extra: recs.length ? `<button class="chip" data-dlclear>Remove all</button>` : "" })
+ `<p class="note">${plural(recs.length, "song")} · ${fmtBytes(total)} stored in this browser${est?.quota && !isSecureContext ? ` (${fmtBytes(est.usage)} of ${fmtBytes(est.quota)} used)` : ""}.
Downloads play without the network. ${isSecureContext ? "" : "This page isn't on HTTPS, so the browser may clear them when space runs low."}</p>`
+ (recs.length ? actions("dl:all") + dlGroups(recs) : `<p class="empty-msg">Nothing downloaded. Right-click any playlist, album or artist and choose Download for offline.</p>`);
count(recs.length, "track");
},
async stems(my) {
if (!Stems.entries.length) await Stems.refresh();
if (my !== seq) return;
const all = Stems.entries.map(stemTrack).sort((a, b) => a.id.localeCompare(b.id));
view.innerHTML = bar("All stems", { filter: false, extra: `<input type="text" id="sf" placeholder="Filter ${all.length} tracks">` }) + `<div id="sl"></div>`;
const render = () => {
const f = $("#sf").value.toLowerCase();
const hits = f ? all.filter(t => t.stem.key.toLowerCase().includes(f)) : all;
$("#sl").innerHTML = (hits.length ? trackTable("stems", hits.slice(0, 400)) : `<p class="empty-msg">${Stems.ok ? "No matches." : "Can't reach stemserve. Check Settings."}</p>`)
+ (hits.length > 400 ? `<p class="note">400 of ${hits.length}</p>` : "");
};
$("#sf").oninput = render;
render();
},
settings: renderSettings,
};
async function route() {
const my = ++seq;
pxEdit = null; curPx = null;
const [, name = "home", ...rest] = (location.hash || "#/home").split("/");
const arg = decodeURIComponent(rest.join("/"));
$$("#nav a").forEach(a => a.classList.toggle("on", a.dataset.nav === name || (a.dataset.nav === "genres" && name === "genre") || (a.dataset.nav === "playlists" && /playlist$/.test(name))));
lists = {}; listItems = {}; kick = null;
delete view.dataset.genre;
view.scrollTop = 0;
Menu.close();
try { await (routes[name] || routes.home)(my, arg); }
catch (e) { if (my === seq) view.innerHTML = `<h1>Something went wrong</h1><p class="sub">${esc(e.message)}</p>`; }
if (my === seq) marks();
}
addEventListener("hashchange", route);
view.addEventListener("click", async ev => {
const el = ev.target.closest("button, tr[data-list]");
if (!el) return;
const ds = el.dataset, row = ev.target.closest("tr[data-list]");
if ("cardplay" in ds) {
ev.preventDefault();
const ts = await cardTracks(el.closest(".card"));
return ts.length ? Q.playList(ts, 0, false) : toast("Nothing to play");
}
if (ds.stemfilter) { S.stemFilter = S.stemFilter === ds.stemfilter ? "" : ds.stemfilter; save(); applyStemFilter(); return; }
if (ds.sortmenu) return Menu.el ? Menu.close() : sortMenu(el);
if ("add" in ds && row) return Q.add([listItems[row.dataset.list]?.[+row.dataset.i] || lists[row.dataset.list][+row.dataset.i]], ev.shiftKey);
if ("menu" in ds && row) { const r = el.getBoundingClientRect(); return trackMenu(r.left, r.bottom, row.dataset.list, +row.dataset.i); }
if (el === row) return playFrom(row.dataset.list, +row.dataset.i);
if (ds.play) {
const all = listItems[ds.play] || lists[ds.play] || [], tracks = visible(all);
if (ds.mode === "stem") return stemNow(all.map(x => x.t || x));
if (!tracks.length) return toast(!all.length ? "Still loading…" : S.stemFilter === "nostems" ? "All of these have stems" : "None of these have stems yet");
return Q.playList(tracks, ds.mode === "shuffle" ? -1 : 0, ds.mode === "shuffle");
}
if (ds.listmenu) { const r = el.getBoundingClientRect(); return listMenu(r.left, r.bottom, async () => listItems[ds.listmenu] || lists[ds.listmenu] || [], { title: $(".hero h1", view)?.textContent || "", href: location.hash, art: artUrls($(".hero img.art", view)) }); }
if (ds.station) {
try {
let ts;
if (ds.station === "library") ts = (await new Pager(sources(), secPath, { type: 10, sort: "random" }, 200).next(200)).map(m => track(m._srv, m));
else ts = (await Promise.all((await new Pager(sources(), secPath, { type: 9, sort: "random" }, 10).next(10)).map(m => leaves(m._srv, m.ratingKey)))).flat();
return ts.length ? Q.playList(ts, 0, false) : toast("Nothing to play");
} catch { return toast("Couldn't start station"); }
}
if ("rdadd" in ds) {
const name = $("#rname").value.trim(), url = $("#rurl").value.trim();
if (!name || !/^https?:\/\//i.test(url)) return toast("Need a name and an http(s) stream URL");
S.stations.push({ id: uuid(), name, url }); save();
return route();
}
if (ds.radio) { const st = S.stations.find(x => x.id === ds.radio); return Radio.station?.id === st.id && Radio.playing ? Radio.stop() : Radio.play(st); }
if (ds.rdrename) {
const st = S.stations.find(x => x.id === ds.rdrename), n = prompt("Rename", st.name);
if (n?.trim()) { st.name = n.trim(); save(); if (Radio.station?.id === st.id) Radio.station.name = st.name; UI.track(); route(); }
return;
}
if (ds.rddelete) {
if (!confirm("Delete this station?")) return;
if (Radio.station?.id === ds.rddelete) Radio.stop();
S.stations = S.stations.filter(x => x.id !== ds.rddelete); save();
return route();
}
if (ds.dlgroup) return removeDl(ds.dlgroup, "these songs");
if ("shuffleall" in ds) {
const ts = (await new Pager(sources(), secPath, { type: 10, sort: "random" }, 200).next(200)).map(m => track(m._srv, m));
return Q.playList(visible(ts), -1, true);
}
if (ds.genreplay) {
const g = (await genres()).find(x => x.title === view.dataset.genre);
const albums = await new Pager(g.srcs, secPath, { type: 9, sort: "random" }, 12).next(12);
const ts = (await Promise.all(albums.map(m => leaves(m._srv, m.ratingKey)))).flat();
return Q.playList(visible(ts), -1, true);
}
if (ds.pxrename && curPx) {
const n = prompt("Rename playlist", curPx.title);
if (n?.trim() && n.trim() !== curPx.title) try { await pxSend(curPx.srv, "PUT", `/playlists/${curPx.key}`, { title: n.trim() }); Finder.pls = null; route(); } catch (e) { toast(e.message); }
return;
}
if (ds.pxdelete && curPx) {
if (confirm(`Delete “${curPx.title}” from Plex? This can't be undone.`)) try { await pxSend(curPx.srv, "DELETE", `/playlists/${curPx.key}`); Finder.pls = null; location.hash = "#/playlists"; } catch (e) { toast(e.message); }
return;
}
if (ds.pxedit && curPx) { pxEdit = { orig: curPx.raw, cur: [...curPx.raw] }; drawPxEdit(); return; }
if ("pxcancel" in ds) { pxEdit = null; route(); return; }
if (ds.pxrm != null && pxEdit) { pxEdit.cur.splice(+ds.pxrm, 1); drawPxEdit(); return; }
if ("pxdone" in ds && pxEdit) { el.disabled = true; await commitPxEdit(); return; }
if ("newpl" in ds) { const n = prompt("Stem playlist name"); if (n?.trim()) { newPlaylist(n.trim()); route(); } return; }
if (ds.plrename) { const p = playlists.find(x => x.id === ds.plrename), n = prompt("Rename", p.title); if (n?.trim()) { p.title = n.trim(); savePlaylists(); route(); } return; }
if (ds.pldelete) { if (confirm("Delete this stem playlist?")) { playlists.splice(playlists.findIndex(x => x.id === ds.pldelete), 1); savePlaylists(); location.hash = "#/playlists"; } return; }
if ("dlclear" in ds) { if (confirm("Remove every download?")) { for (const id of [...Offline.ids]) await Offline.remove(id); emit("offline"); route(); } }
});
// ---- Plex playlist edit mode (iOS PlaylistScreens): drag to reorder, remove, then Done ----------
function drawPxEdit() {
const body = $("#pxbody", view);
if (!body || !pxEdit) return;
body.innerHTML = `<div class="bar sm"><span class="note">Drag to reorder</span><span class="grow"></span><button class="chip" data-pxcancel>Cancel</button><button class="chip on" data-pxdone>Done</button></div>
<div class="pxedit">${pxEdit.cur.map((t, i) => `<div class="pxrow" data-i="${i}"><span class="grip" title="Drag">${ICON.queue}</span><img src="${esc(artOf(t, 96))}" alt="" ${FB}><div class="pxt"><b>${esc(t.title)}</b><small>${esc(t.artist)}</small></div><button class="ib bad" data-pxrm="${i}" title="Remove">${ICON.x}</button></div>`).join("") || `<p class="empty-msg">Nothing left. Done will empty the playlist.</p>`}</div>`;
}
// Pointer drag on the grip, so it works with touch too. Only transforms move during the drag.
view.addEventListener("pointerdown", e => {
const g = e.target.closest(".pxrow .grip");
if (!g || !pxEdit) return;
e.preventDefault();
const row = g.parentElement, wrap = row.parentElement, rows = [...wrap.children], from = +row.dataset.i;
const h = row.getBoundingClientRect().height + parseFloat(getComputedStyle(wrap).rowGap || 0), y0 = e.clientY;
let to = from;
row.classList.add("drag"); g.setPointerCapture(e.pointerId);
const move = ev => {
const dy = ev.clientY - y0;
to = Math.max(0, Math.min(rows.length - 1, from + Math.round(dy / h)));
row.style.transform = `translateY(${dy}px)`;
rows.forEach((r, i) => { if (r !== row) r.style.transform = i > from && i <= to ? `translateY(${-h}px)` : i < from && i >= to ? `translateY(${h}px)` : ""; });
};
const up = () => {
g.removeEventListener("pointermove", move); g.removeEventListener("pointerup", up); g.removeEventListener("pointercancel", up);
if (to !== from) pxEdit.cur.splice(to, 0, ...pxEdit.cur.splice(from, 1));
drawPxEdit();
};
g.addEventListener("pointermove", move); g.addEventListener("pointerup", up); g.addEventListener("pointercancel", up);
});
// Removals first, then replay the new order as move-after calls against a simulated list.
async function commitPxEdit() {
const { srv, key } = curPx, keep = new Set(pxEdit.cur.map(t => t.pid));
try {
for (const t of pxEdit.orig) if (!keep.has(t.pid)) await pxSend(srv, "DELETE", `/playlists/${key}/items/${t.pid}`);
const sim = pxEdit.orig.filter(t => keep.has(t.pid)).map(t => t.pid);
for (let i = 0; i < pxEdit.cur.length; i++) {
const pid = pxEdit.cur[i].pid;
if (sim[i] === pid) continue;
const after = i ? pxEdit.cur[i - 1].pid : null;
await pxSend(srv, "PUT", `/playlists/${key}/items/${pid}/move`, { after });
sim.splice(sim.indexOf(pid), 1); sim.splice(i, 0, pid);
}
toast("Playlist saved");
} catch (e) { toast(e.message); }
pxEdit = null; Finder.pls = null; route();
}
async function removeDl(n, what) {
const ts = lists["dl:" + n] || [];
if (!confirm(`Remove ${what} (${plural(ts.length, "download")})? They will no longer play offline.`)) return;
for (const t of ts) await Offline.remove(t.id);
emit("offline"); route();
}
function dlMenu(x, y, n, title) {
const ts = () => lists["dl:" + n] || [];
Menu.open(x, y, [
{ label: "Play", run: () => Q.playList(ts(), 0, false) },
{ label: "Shuffle", run: () => Q.playList(ts(), -1, true) },
{ label: "Play next", run: () => Q.add(ts(), true) },
{ label: "Add to queue", run: () => Q.add(ts()) },
"-",
{ label: "Remove download", run: () => removeDl(n, `“${title}”`) },
]);
}
view.addEventListener("contextmenu", ev => {
const row = ev.target.closest("tr[data-list]"), c = ev.target.closest(".card[data-kind]"), d = ev.target.closest(".card[data-dl]");
if (d) { ev.preventDefault(); dlMenu(ev.clientX, ev.clientY, d.dataset.dl, $(".t", d).textContent); }
else if (row) { ev.preventDefault(); trackMenu(ev.clientX, ev.clientY, row.dataset.list, +row.dataset.i); }
else if (c) { ev.preventDefault(); listMenu(ev.clientX, ev.clientY, () => cardTracks(c), { title: $(".t", c).textContent, href: c.getAttribute("href"), art: artUrls($("img", c)) }); }
});
// ---- settings -----------------------------------------------------------------------------------
const SECTIONS = [["plex", "Plex"], ["stems", "Stem server"], ["stemopts", "Stems"], ["presets", "Stem Editor"], ["karaoke", "Karaoke"], ["look", "Appearance"],
["offline", "Offline"], ["backup", "Backup"], ["keys", "Keys"], ["about", "About"]];
const BAR = [["speed", "Speed"], ["mixer", "Mixer"], ["lyrics", "Lyrics"], ["queue", "Queue"]];
// Settings rows: label on the left, control on the right, grouped into cards.
const srow = (title, ctrl, sub = "") => `<div class="sr"><div class="sl"><span>${title}</span>${sub ? `<small>${sub}</small>` : ""}</div><div class="sc">${ctrl}</div></div>`;
const stog = (title, input, sub = "") => `<label class="sr"><div class="sl"><span>${title}</span>${sub ? `<small>${sub}</small>` : ""}</div><div class="sc">${input}</div></label>`;
const sw = (attrs, on) => `<input type="checkbox" class="sw" ${attrs} ${on ? "checked" : ""}>`;
function presetEditor() {
const ps = presets(), lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset);
return `<div class="sg">${srow("Locked preset", lock
? `<span class="val">${ICON.lock}${esc(presetLabel(lock.name))}</span><button class="btn small" data-plock="${esc(lock.id)}">Unlock</button>`
: `<span class="val dim">None</span>`)}</div>
<h3 class="sgh">Mixer bar</h3>
<div class="sg">${ps.map((p, i) => `<div class="sr"><div class="sl"><span>${esc(presetLabel(p.name))}${p.custom ? ' <span class="tag">CUSTOM</span>' : ""}</span></div><div class="sc ibs">
<button class="ib ${lock?.id === p.id ? "on" : ""}" data-plock="${esc(p.id)}" title="${lock?.id === p.id ? "Unlock" : "Lock"}">${ICON.lock}</button>
<button class="ib" data-pmove="${esc(p.id)}" data-pdir="-1" ${i ? "" : "disabled"} title="Move up">${ICON.up}</button>
<button class="ib" data-pmove="${esc(p.id)}" data-pdir="1" ${i < ps.length - 1 ? "" : "disabled"} title="Move down">${ICON.down}</button>
<button class="ib bad" data-pdel="${esc(p.id)}" ${p.id === "b:Full Mix" ? "disabled" : ""} title="Delete">${ICON.x}</button></div></div>`).join("")}</div>
<div class="sg">
<button class="sr act" data-padd ${mixNames().length ? "" : "disabled"}>Save current mix as preset</button>
<button class="sr act" data-prestore ${S.hiddenPresets.length ? "" : "disabled"}>Restore deleted presets</button>
<button class="sr act bad" data-pclear ${S.customPresets.length ? "" : "disabled"}>Delete all custom presets</button></div>`;
}
on("presets", () => { const el = $("#pedit"); if (el) el.innerHTML = presetEditor(); });
const FORMATS = [["opus96", "Opus 96 kbps"], ["opus160", "Opus 160 kbps"], ["opus256", "Opus 256 kbps"], ["flac", "FLAC (original)"]];
function serverHtml(srv) {
const dup = srv.mid && S.servers.find(o => o !== srv && o.mid === srv.mid && S.servers.indexOf(o) < S.servers.indexOf(srv));
const secs = srv.sections || [];
return `<div class="sr srv"><div class="sl"><span>${esc(srv.name || srv.url)}</span><small>${srv.env ? "Through stemserve" : esc(srv.url)}</small></div><div class="sc">
<button class="btn small" data-refsrv="${esc(srv.id)}">Refresh</button>
${srv.env ? "" : `<button class="btn small" data-rmsrv="${esc(srv.id)}">Remove</button>`}</div>
<div class="libs">${dup ? `<small>Duplicate of ${esc(dup.name)}</small>`
: secs.length ? secs.map(sec => `<label class="lib"><input type="checkbox" data-sec="${esc(srv.id)}|${esc(sec.key)}" ${sec.on ? "checked" : ""}>${esc(sec.title)}</label>`).join("")
: `<small>No music libraries</small>`}</div></div>`;
}
const KEYS = [["Space", "Play / pause"], ["← →", "Seek 5 s"], ["⇧ ← →", "Seek 30 s"], ["S", "Search"], ["⇧ S", "Shuffle"], ["R", "Repeat"], ["[ ]", "Speed"],
["M", "Mixer"], ["L", "Lyrics"], ["Q", "Queue"], ["K", "Karaoke"], ["P", "Next preset"]];
function renderSettings() {
const nMix = Object.keys(songMixes).length;
view.innerHTML = `<div class="settings"><nav class="toc">${SECTIONS.map(([id, l]) => `<a href="#/settings" data-jump="${id}">${l}</a>`).join("")}</nav><div class="panes">
<h1>Settings</h1>
<section id="set-plex"><h2>Plex</h2>
<div class="sg">${S.servers.map(serverHtml).join("") || srow(`<span class="dim">No servers</span>`, "")}
${srow(`<span class="dim" id="sstatus"></span>`, `<button class="btn primary small" id="signin">Sign in with Plex</button>`)}</div>
<details class="sg"><summary class="sr"><div class="sl"><span>Add by URL and token</span></div><div class="sc chev">${ICON.down}</div></summary>
${srow("Server URL", `<input type="url" id="purl" placeholder="http://10.0.0.2:32400">`)}
${srow("Token", `<input type="password" id="ptok">`)}
<div class="sr end"><button class="btn small" id="padd">Add server</button></div></details>
</section>
<section id="set-stems"><h2>Stem server</h2><div class="sg">
${srow("Status", `<span class="stat" id="stem-info">Checking…</span>`)}
${srow("URL", `<input type="url" id="surl" placeholder="${esc(location.origin)}" value="${esc(S.stemUrl)}">`)}
${srow("Token", `<input type="password" id="stok" value="${esc(S.stemToken)}" placeholder="None">`)}
<div class="sr end"><button class="btn small" id="ssave">Save and reconnect</button></div></div>
</section>
<section id="set-stemopts"><h2>Stems</h2><div class="sg">
${srow("Format", `<select id="fmt">${FORMATS.map(([v, l]) => `<option value="${v}" ${S.fmt === v ? "selected" : ""}>${l}</option>`).join("")}</select>`)}
${srow("Cache ahead", `<input type="range" id="precache" min="0" max="50" step="1" value="${S.precache}"><input type="number" id="precachen" min="0" max="50" value="${S.precache}"><span class="dim">songs</span>`)}
${stog("Keep mix between songs", sw(`id="keepmix"`, S.keepMix))}
${srow("Saved song mixes", `<span class="val">${nMix}</span>${nMix ? `<button class="btn small" id="forgetall">Forget all</button>` : ""}`)}</div>
</section>
<section id="set-presets"><h2>Stem Editor</h2><div id="pedit">${presetEditor()}</div></section>
<section id="set-karaoke"><h2>Karaoke</h2><div class="sg">
${stog(`Karaoke <kbd>K</kbd>`, sw(`id="kon"`, S.karaoke))}
${srow("Vocals", `<select id="kmode">${[["off", "Off"], ["soft", "Soft"], ["on", "Left on (lyrics only)"]].map(([v, l]) => `<option value="${v}" ${S.karaokeMode === v ? "selected" : ""}>${l}</option>`).join("")}</select>`)}
${srow("Soft vocal level", `<input type="range" id="kdb" min="-30" max="-3" step="1" value="${S.softDb}"><span class="val num" id="kdbv">${S.softDb} dB</span>`)}</div>
</section>
<section id="set-look"><h2>Appearance</h2>
<div class="sg"><div class="sr col"><div class="sl"><span>Theme</span></div>
<div class="themes">${Object.entries(THEMES).map(([k, t]) => `<button class="tcard ${S.theme === k ? "on" : ""}" data-theme="${k}">
<span class="tmock" style="background:${t.bg};border-color:${t.line}"><i style="background:${t.text}"></i>${"<b></b>".repeat(3).replaceAll("<b>", `<b style="background:${t.raised === t.bg ? t.panel : t.raised}">`)}<u style="background:${accentOf(t)}"></u></span>${t.label}</button>`).join("")}</div></div>
<div class="sr col"><div class="sl"><span>Accent</span><small>${(ACCENTS[S.accent] || ACCENTS.music)[0]}</small></div>
<div class="accents">${Object.entries(ACCENTS).map(([k, [l]]) => `<button class="dot ${(ACCENTS[S.accent] ? S.accent : "music") === k ? "on" : ""}" data-accent="${k}" title="${l}" aria-label="${l}" style="--c:${accentOf(THEMES[S.theme] || THEMES.dark, k)}"></button>`).join("")}</div></div>
${stog("Match album art", sw(`id="arttheme"`, S.artTheme))}
${stog("Call the vocals-only preset “Acapella”", sw(`id="acapella"`, S.acapella))}</div>
<h3 class="sgh">Player bar</h3>
<div class="sg">${BAR.map(([k, l]) => stog(l, sw(`data-bar="${k}"`, S.bar[k]))).join("")}</div>
<h3 class="sgh">Custom CSS</h3>
<div class="sg"><div class="sr col"><textarea id="css" rows="7" spellcheck="false" placeholder=":root { --accent: #7cf; --radius: 4px; }\n.card img { border-radius: 0; }">${esc(S.css)}</textarea>
<small class="mono">--bg --panel --raised --line --text --muted --accent --accent-ink --radius --wave --wave-ghost</small></div></div>
</section>
<section id="set-offline"><h2>Offline</h2><div class="sg">
${srow("Downloads", `<span class="val" id="storage-info">${plural(Offline.ids.size, "track")}</span><a class="btn small" href="#/downloads">Manage</a>`)}
${isSecureContext && navigator.storage?.persist ? srow("Keep downloads", `<button class="btn small" id="persist">Ask browser</button>`) : ""}</div>
</section>
<section id="set-backup"><h2>Backup</h2><div class="sg">
${srow("Settings, mixes and playlists", `<button class="btn small" id="export">Export</button><label class="btn small">Import<input type="file" id="import" accept="application/json" hidden></label>`, "Includes your Plex tokens")}</div>
</section>
<section id="set-keys"><h2>Keys</h2><div class="sg"><div class="keys">${KEYS.map(([k, l]) => `<div><span>${l}</span>${k.split(" ").map(x => `<kbd>${x}</kbd>`).join("")}</div>`).join("")}</div></div></section>
<section id="set-about"><h2>About</h2><div class="sg">
${srow("Stemify", `<span class="val dim" id="about-ver"></span>`, "Your Plex and Jellyfin music, split into stems you can mix")}
${srow("Chris Nutter", `<a class="btn small" href="https://iamchrisama.com" target="_blank" rel="noopener">Website</a><a class="btn small" href="https://buymeacoffee.com/cdnutter" target="_blank" rel="noopener">Buy Me a Coffee</a>`, "Web UI and iOS app")}
${srow("Kevin Viers", `<a class="btn small" href="https://github.com/kevinViers/" target="_blank" rel="noopener">GitHub</a><a class="btn small" href="https://venmo.com/code?user_id=2910252785729536546&amp;created=1792897467" target="_blank" rel="noopener">Venmo</a>`, "stemd and Android app")}</div>
</section>
</div></div>`;
// Slow bits fill in after the page is up.
fetch(api("/api/info"), { signal: AbortSignal.timeout(5000) }).then(r => r.ok ? r.json() : null).catch(() => null).then(info => {
const el = $("#stem-info");
const v = $("#about-ver");
if (v && info) v.textContent = `stemserve v${info.version}`;
if (el) { el.textContent = info ? `v${info.version} · ${info.tracks} tracks${info.ffmpeg ? " · Opus" : ""}` : "Unreachable"; el.classList.add(info ? "ok" : "bad"); }
});
navigator.storage?.estimate?.().then(e => { const el = $("#storage-info"); if (el && e?.quota) el.insertAdjacentText("beforeend", ` · ${fmtBytes(e.usage)} of ${fmtBytes(e.quota)}`); }).catch(() => {});
// The section in view lights up in the side list.
const toc = [...view.querySelectorAll(".toc a")];
const spy = new IntersectionObserver(es => {
for (const e of es) if (e.isIntersecting) for (const a of toc) a.classList.toggle("on", "set-" + a.dataset.jump === e.target.id);
}, { root: view, rootMargin: "0px 0px -70% 0px" });
view.querySelectorAll(".panes section").forEach(s => spy.observe(s));
const again = () => { if (location.hash.startsWith("#/settings")) renderSettings(); };
const plexChanged = () => { genreCache = null; save(); };
$("#signin").onclick = async () => {
const st = $("#sstatus");
try { const ok = await signIn(m => { st.textContent = m; }); plexChanged(); toast(`Added ${plural(ok.length, "server")}`); again(); }
catch (e) { st.textContent = e.message; }
};
$("#padd").onclick = async () => {
const url = $("#purl").value.trim().replace(/\/+$/, ""), token = $("#ptok").value.trim();
if (!url || !token) return toast("Need both a URL and a token");
const srv = addServer(manualServer(url, token));
try { await refreshServer(srv); } catch (e) { toast(e.message); }
plexChanged(); again();
};
$("#ssave").onclick = async () => {
S.stemUrl = $("#surl").value.trim(); S.stemToken = $("#stok").value.trim();
Stems.etag = null; save(); await Stems.refresh(); Live.poll(); again();
};
$("#fmt").onchange = ev => { S.fmt = ev.target.value; save(); };
$("#keepmix").onchange = ev => { S.keepMix = ev.target.checked; if (!S.keepMix && S.karaoke) setKaraoke(false); save(); };
const ahead = v => { S.precache = Math.max(0, Math.min(50, Math.round(+v || 0))); $("#precache").value = $("#precachen").value = S.precache; save(); };
$("#precache").oninput = ev => ahead(ev.target.value);
$("#precachen").onchange = ev => ahead(ev.target.value);
$("#arttheme").onchange = ev => { S.artTheme = ev.target.checked; save(); ArtTheme.set(S.artTheme ? artOf(Q.cur(), 64) : ""); };
$("#acapella").onchange = ev => { S.acapella = ev.target.checked; save(); emit("presets"); emit("mix"); };
if ($("#forgetall")) $("#forgetall").onclick = () => { for (const k of Object.keys(songMixes)) forgetSongMix(k); again(); };
$("#kon").onchange = ev => setKaraoke(ev.target.checked);
$("#kmode").onchange = ev => setKaraokeMode(ev.target.value);
$("#kdb").oninput = ev => { $("#kdbv").textContent = ev.target.value + " dB"; };
$("#kdb").onchange = ev => setKaraokeMode(S.karaokeMode, +ev.target.value);
let cssTimer;
$("#css").oninput = ev => { clearTimeout(cssTimer); cssTimer = setTimeout(() => { S.css = ev.target.value; applyTheme(); save(); }, 250); };
if ($("#persist")) $("#persist").onclick = async () => toast(await navigator.storage.persist() ? "Downloads will be kept" : "The browser said no");
$("#export").onclick = () => {
const blob = new Blob([JSON.stringify({ stemify: 1, settings: S, mixes: songMixes, playlists }, null, 2)], { type: "application/json" });
const a = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: "stemify-web.json" });
a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
};
$("#import").onchange = async ev => {
try {
const j = JSON.parse(await ev.target.files[0].text());
if (!j.stemify) throw new Error("Not a Stemify backup");
store("stemify-web", { ...j.settings, clientId: S.clientId });
if (j.mixes) store("stemify-web-mixes", j.mixes);
if (j.playlists) store("stemify-web-playlists", j.playlists);
location.reload();
} catch (e) { toast(e.message); }
};
const sv = $(".settings");
sv.addEventListener("click", async ev => {
const b = ev.target.closest("[data-jump], [data-theme], [data-accent], [data-refsrv], [data-rmsrv], [data-plock], [data-pmove], [data-pdel], [data-padd], [data-prestore], [data-pclear]");
if (!b) return;
const ds = b.dataset;
if (ds.jump) { ev.preventDefault(); $("#set-" + ds.jump).scrollIntoView({ behavior: "smooth", block: "start" }); }
else if (ds.theme) { S.theme = ds.theme; applyTheme(); save(); again(); }
else if (ds.accent) { S.accent = ds.accent; applyTheme(); save(); again(); }
else if (ds.refsrv) { try { await refreshServer(server(ds.refsrv)); toast("Refreshed"); } catch (e) { toast(e.message); } plexChanged(); again(); }
else if (ds.rmsrv && confirm("Remove this server?")) { S.servers = S.servers.filter(s => s.id !== ds.rmsrv); plexChanged(); again(); }
else if (ds.plock) toggleLock(ds.plock, mixNames());
else if (ds.pmove) movePreset(ds.pmove, +ds.pdir);
else if (ds.pdel) { if (ds.pdel.startsWith("b:") || confirm("Delete this preset?")) deletePreset(ds.pdel); }
else if ("padd" in ds) newPreset();
else if ("prestore" in ds) restorePresets();
else if ("pclear" in ds && confirm("Delete every custom preset?")) deleteAllCustom();
});
sv.addEventListener("change", ev => {
const bk = ev.target.dataset.bar;
if (bk) { S.bar = { ...S.bar, [bk]: ev.target.checked }; save(); applyBar(); return; }
const k = ev.target.dataset.sec;
if (!k) return;
const [id, key] = k.split("|"), sec = server(id)?.sections.find(s => s.key === key);
if (sec) { sec.on = ev.target.checked; plexChanged(); }
});
}
on("mix", () => { if ($("#kon")) $("#kon").checked = S.karaoke; });
// ---- start --------------------------------------------------------------------------------------
// The server's own PLEX_URL / PLEX_TOKEN show up as a server proxied through stemserve, and a
// local stemserve is tried when this page's server has none.
async function connect() {
const ok = await Stems.refresh();
if (!ok && !Stems.ok && !S.stemUrl && !/^(localhost|127\.0\.0\.1)$/.test(location.hostname)) {
for (const u of ["http://localhost:8765", "http://127.0.0.1:8765"]) {
try {
const r = await fetch(u + "/api/info", { signal: AbortSignal.timeout(1500) });
if (r.ok) { S.stemUrl = u; save(); await Stems.refresh(); break; }
} catch {}
}
}
try {
const c = await fetch(api("/api/config"), { signal: AbortSignal.timeout(4000) }).then(r => r.ok ? r.json() : null);
if (c?.plex) addServer({ id: "env", env: true, token: c.plex.token, url: stemBase() + "/plex" });
else if (c) S.servers = S.servers.filter(s => !s.env);
} catch {}
await Promise.all(S.servers.filter(s => !s.sections?.length || !s.mid).map(s => refreshServer(s).catch(() => {})));
save();
}
let connecting = null;
(async () => {
applyTheme();
applyStemFilter();
applyBar();
await Offline.init();
connecting = connect();
await Promise.race([connecting, new Promise(r => setTimeout(r, 5000))]);
Q.restore();
UI.all();
route();
Live.poll();
setInterval(() => { if (!document.hidden) { Stems.refresh(); } }, 5 * 60 * 1000);
})();