Redesign the bar, sheets and cards, and add likes queue, history and sleep timer

Feed modes move into tabs in the bar; likes, history, filters and settings,
and account open as one kind of sheet: a drawer on wide screens, a bottom
sheet with a drag handle on phones, with a scrim, Esc, a focus trap and
focus restore.

Cards get an artist avatar, follow and radio pills, a "new" chip, counts
under round action buttons, an up-next pill and a redrawn waveform with
rounded bars, a reflection and the buffered range. The start overlay names
the track behind a big round play button.

New: undo on dislike, a searchable likes list that plays as a queue
(in order or shuffled), a local history of what played, deep links to a
track (?t=handle/slug), a sleep timer, adjustable crossfade, bass boost,
wheel up (w or a long press on the drop) and more keys.
This commit is contained in:
nvrl committed 2026-11-01 19:33:49 +01:00
1 parent 53ac54b178
commit 62b28bd30e
10 files changed
+1312 -339

No files matched your search

+6 -1
View File
@@ -81,7 +81,7 @@ export type Mode =
| { mode: "classic" | "riddim" | "fresh" | "deep" }
| { mode: "artist"; artist: string; name: string; img?: string | null };
export type EventKind = "play" | "like" | "unlike" | "skip" | "complete" | "dislike";
export type EventKind = "play" | "like" | "unlike" | "skip" | "complete" | "dislike" | "undislike";
export class HttpError extends Error {
constructor(message: string, readonly status: number) {
@@ -125,12 +125,17 @@ export function feed(filters: Filters, mode: Mode) {
export const artist = (handle: string) => getJSON<ArtistInfo>("/local/artist?" + new URLSearchParams({ handle }));
export const track = (handle: string, slug: string) =>
getJSON<{ track: Track }>("/local/track?" + new URLSearchParams({ handle, slug }));
export const likes = () => getJSON<{ tracks: Track[] }>("/local/likes");
export const me = () => getJSON<Me>("/local/me");
export const PL8 = "https://pl8list.com";
export const trackUrl = (t: Track) => `${PL8}/${t.handle}/${t.slug}`;
/// A link that opens this app on the track.
export const appTrackUrl = (t: Track) => `${location.origin}/?t=${encodeURIComponent(t.handle)}/${encodeURIComponent(t.slug)}`;
export const artistUrl = (t: Track) => `${PL8}/${t.handle}`;
// Images come through our server, so pl8list never sees the visitor's address.
export const imgUrl = (id: string | null) => (id ? `/img/${encodeURIComponent(id)}` : null);
+5
View File
@@ -49,6 +49,11 @@ export class Spin {
this.toMatrix();
}
/// Throw it round: add `v` (rad/s, a rotation vector in view space) to its speed.
fling(v: [number, number, number]): void {
for (let i = 0; i < 3; i++) this.vel[i] += v[i];
}
/// Advance by `dt` seconds. True while it still moves.
step(dt: number): boolean {
if (this.held) return true;
+54 -13
View File
@@ -20,6 +20,12 @@ export interface CardActions {
// Uploads are often titled after their file name.
export const cleanTitle = (t: string) => t.replace(/\.(wav|mp3|flac|aiff?|ogg|m4a)$/i, "");
export const fmtTime = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
/// 1234 → "1.2k", as counts under the action buttons.
export const compact = (n: number) =>
n < 1000 ? String(n) : n < 10000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : `${Math.round(n / 1000)}k`;
const NEW_DAYS = 7; // uploads younger than this get a "new" chip
const BAR = 3; // px per waveform bar, gap included
const MIRROR = 0.28; // share of the waveform's height its reflection takes
const tpl = document.getElementById("card-tpl") as HTMLTemplateElement;
@@ -62,6 +68,7 @@ export class Card {
if (img) {
$(".bg").style.backgroundImage = `url("${img}")`;
$(".art").style.backgroundImage = `url("${img}")`;
$(".artist-avatar").style.backgroundImage = `url("${img}")`;
if (this.accent) el.style.setProperty("--card-accent", this.accent);
else accentFor(img).then((c) => {
this.accent = c;
@@ -72,6 +79,7 @@ export class Card {
});
} else {
$(".initial").textContent = (t.artist_name || "?")[0].toUpperCase();
$(".artist-avatar").textContent = (t.artist_name || "?")[0].toUpperCase();
el.style.setProperty("--card-accent", accentForName(t.artist_name || "?"));
}
@@ -91,6 +99,7 @@ export class Card {
if (cls) s.className = cls;
chips.append(s);
};
if (t.created_at && Date.now() - Date.parse(t.created_at) < NEW_DAYS * 86400e3) chip("new", "new");
if (t.bpm) chip(`${Math.round(t.bpm)} bpm`);
if (t.key) chip(t.key);
chip(t.price ? `$${t.price}` : "free", t.price ? "" : "free");
@@ -98,9 +107,11 @@ export class Card {
// Tempo tags repeat the BPM chip.
for (const tag of (t.tags ?? []).filter((g) => !/^\d+$/.test(g)).slice(0, 4)) chip(tag, "tag");
$(".counts").textContent =
`${t.saves} saves · ${t.downloads} downloads · ${t.comments} comments` +
(t.purchases ? ` · ${t.purchases} sold` : "");
$(".counts").textContent = [t.downloads && `${compact(t.downloads)} downloads`, t.purchases && `${compact(t.purchases)} sold`]
.filter(Boolean)
.join(" · ");
$(".saves").textContent = compact(t.saves);
$(".comments").textContent = compact(t.comments);
$(".like").addEventListener("click", () => this.actions.like(this));
$(".dislike").addEventListener("click", () => this.actions.dislike(this));
@@ -143,8 +154,10 @@ export class Card {
showFollow(): void {
const btn = this.el?.querySelector(".follow");
if (!btn) return;
btn.classList.toggle("on", !!this.track.followed);
btn.textContent = this.track.followed ? "following" : "follow";
const on = !!this.track.followed;
btn.classList.toggle("on", on);
btn.querySelector("span")!.textContent = on ? "following" : "follow";
btn.querySelector("use")!.setAttribute("href", on ? "#i-check" : "#i-plus");
}
setTime(seconds: number): void {
@@ -153,19 +166,24 @@ export class Card {
}
private lastProgress = 0;
private lastBuffered = 0;
/// Draw the waveform with `progress` (0..1) played. Cheap to call every frame:
/// Draw the waveform with `progress` (0..1) played and up to `buffered` (0..1)
/// loaded: rounded bars standing on a line, the played ones in the card's colour
/// with a soft glow, and a faint reflection under them. Cheap to call every frame:
/// it only redraws when a bar changes colour or the size changed.
drawWave(progress: number, force = false): void {
drawWave(progress: number, force = false, buffered = this.lastBuffered): void {
if (this.dragging && !force) return;
this.lastProgress = progress;
this.lastBuffered = buffered;
const canvas = this.canvas;
if (!canvas) return;
const w = canvas.clientWidth, h = canvas.clientHeight;
if (!w) return;
const bars = Math.max(1, Math.floor(w / 3));
const bars = Math.max(1, Math.floor(w / BAR));
const played = Math.round(progress * bars);
const key = `${w}x${h}:${played}`;
const loaded = Math.round(buffered * bars);
const key = `${w}x${h}:${played}:${loaded}`;
if (!force && key === this.drawn) return;
this.drawn = key;
const dpr = window.devicePixelRatio || 1;
@@ -179,12 +197,35 @@ export class Card {
const data = this.track.waveform || [];
const max = Math.max(1, ...data);
const accent = getComputedStyle(canvas).getPropertyValue("--card-accent").trim() || "#ff4d6d";
const base = Math.round(h * (1 - MIRROR)) - 1;
const below = h - base - 2;
const level = (i: number) => (data.length ? data[Math.floor((i / bars) * data.length)] / max : 0.15);
const grad = ctx.createLinearGradient(0, base, 0, 0);
grad.addColorStop(0, accent);
grad.addColorStop(0.65, accent);
grad.addColorStop(1, "#fff");
for (let i = 0; i < bars; i++) {
const v = data.length ? data[Math.floor((i / bars) * data.length)] / max : 0.15;
const bh = Math.max(2, v * h);
ctx.fillStyle = i < played ? accent : "rgba(255,255,255,0.35)";
ctx.fillRect(i * 3, (h - bh) / 2, 2, bh);
const v = level(i);
const x = i * BAR;
const top = Math.max(2, v * (base - 2));
const color = i < played ? accent : i < loaded ? "rgba(255,255,255,0.5)" : "rgba(255,255,255,0.22)";
// The bar, standing on the line; played ones glow.
ctx.globalAlpha = 1;
ctx.fillStyle = i < played ? grad : color;
ctx.shadowBlur = i < played ? 6 : 0;
ctx.shadowColor = accent;
ctx.beginPath();
ctx.roundRect(x, base - top, BAR - 1, top, 1);
ctx.fill();
// Its reflection, faint, under the line.
ctx.shadowBlur = 0;
ctx.globalAlpha = 0.22;
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(x, base + 2, BAR - 1, Math.max(1, v * below), 1);
ctx.fill();
}
ctx.globalAlpha = 1;
}
/// Loudness at `progress` from the waveform, 0..1. Stands in for the analyser
+35
View File
@@ -0,0 +1,35 @@
// What this browser played lately, newest first, for the history sheet. Kept on
// the device only; the server has its own record of plays for the feed.
import type { Track } from "./api";
const KEY = "pl8inf.history";
const MAX = 100;
export interface Heard {
track: Track;
/// ms since the epoch.
at: number;
}
export function load(): Heard[] {
try {
const list = JSON.parse(localStorage.getItem(KEY) || "[]");
return Array.isArray(list) ? list.filter((h) => h?.track?.id && typeof h.at === "number") : [];
} catch {
return [];
}
}
/// Note a track as heard; a track heard again moves to the top.
export function add(track: Track): void {
// Why it was in a radio says nothing once it is replayed from here.
const list = [{ track: { ...track, why: undefined }, at: Date.now() }, ...load().filter((h) => h.track.id !== track.id)].slice(0, MAX);
try {
localStorage.setItem(KEY, JSON.stringify(list));
} catch { /* storage full: history is a nicety */ }
}
export function clear(): void {
localStorage.removeItem(KEY);
}
+480 -165
View File
@@ -2,9 +2,12 @@ import "./style.css";
import * as api from "./api";
import type { Filters, Mode, Pl8Status, Stats, Track, User } from "./api";
import { Card, type CardActions, cleanTitle } from "./cards";
import { Card, type CardActions, cleanTitle, fmtTime } from "./cards";
import { accentForName } from "./color";
import * as heard from "./history";
import { Pager } from "./pager";
import { Player } from "./player";
import { Sheet } from "./sheet";
import { Station } from "./station";
import { type VisualsSetting, Visualizer } from "./visual";
@@ -12,8 +15,12 @@ const PREFETCH_AHEAD = 4; // fetch more when this close to the end
const SKIP_SECONDS = 8; // leaving earlier than this counts as a skip
const COMPLETE_RATIO = 0.85;
const DOUBLE_TAP_MS = 300;
const LONG_PRESS_MS = 550; // holding the drop this long rewinds the tune
const PRELOAD_AFTER_MS = 2500; // start buffering the next track once this one has played a bit
const KEEP_BUILT = 3; // cards further than this from the current one drop their elements
const HISTORY_AFTER = 1; // s heard before a track goes into the history
const SLEEP_FADE = 10; // s the sleep timer fades out over
const BPM_RANGE = [60, 200]; // the BPM slider's ends, which mean "no limit"
const FILTERS_KEY = "pl8inf.filters";
const MODE_KEY = "pl8inf.mode";
const HINT_KEY = "pl8inf.hintShown";
@@ -25,21 +32,26 @@ const feedStatus = $("feed-status");
const statsEl = $("stats");
const filtersForm = $<HTMLFormElement>("filters");
const filtersBtn = $("filters-btn");
const likesPanel = $("likes");
const likesBtn = $("likes-btn");
const accountPanel = $("account");
const accountBtn = $("account-btn");
const startEl = $("start");
const helpEl = $("help");
const toastEl = $("toast");
const loginEl = $("login");
const upNext = $<HTMLButtonElement>("up-next");
const radioEnd = $("radio-end");
const isTouch = !matchMedia("(hover: hover) and (pointer: fine)").matches;
const radioEnd = $("radio-end");
const player = new Player();
const visual = new Visualizer(player, isTouch);
const sheets = {
filters: new Sheet(filtersForm, filtersBtn),
likes: new Sheet($("likes"), $("likes-btn")),
history: new Sheet($("history"), $("history-btn")),
account: new Sheet($("account"), accountBtn),
help: new Sheet($("help")),
};
// Installable as an app; see public/sw.js. The dev server has no /sw.js.
if ("serviceWorker" in navigator && import.meta.env.PROD) {
navigator.serviceWorker.register("/sw.js", { scope: "/" }).catch((err) => console.warn("no service worker:", err));
@@ -53,12 +65,15 @@ let listened = 0; // seconds actually heard on the active card
let lastTime = 0;
let reported = false; // final event already sent for the active card
let advanced = false; // already mixed into the next track
let remembered = false; // the active card is in the history
let preloadTimer = 0;
let filters: Filters = loadFilters();
let mode: Mode = loadMode();
let stats: Stats | null = null;
let jumpOnLoad = false; // a radio just started: go to its first track as soon as it is here
let radioDry = false; // the artist radio found nothing more; say so on its last card
/// Playing the likes in order (or shuffled) instead of the feed. Null for the feed.
let queue: { tracks: Track[]; next: number } | null = null;
const current = () => cards[active] as Card | undefined;
@@ -78,6 +93,10 @@ function setStatus(text: string): void {
async function loadMore(): Promise<void> {
if (loading) return;
if (queue) {
fromQueue();
return;
}
loading = true;
if (!cards.length) setStatus("crawling pl8list, first tracks in a few seconds…");
const gen = feedGen;
@@ -100,11 +119,7 @@ async function loadMore(): Promise<void> {
radioDry = false;
updateRadioEnd();
const station = mode.mode === "artist" ? mode.name : undefined;
cards.push(...data.tracks.map((t) => new Card(t, actions, { station })));
pager.refresh();
if (active < 0) activate(0);
else if (jumpOnLoad) go(active + 1);
jumpOnLoad = false;
addCards(data.tracks.map((t) => new Card(t, actions, { station })));
} catch (err) {
if (gen !== feedGen) return;
if (err instanceof api.HttpError && err.status === 401) {
@@ -118,17 +133,38 @@ async function loadMore(): Promise<void> {
loading = false;
}
function addCards(more: Card[]): void {
cards.push(...more);
pager.refresh();
if (active < 0) activate(0);
else if (jumpOnLoad) go(active + 1);
jumpOnLoad = false;
showUpNext();
}
function showStats(s?: Stats): void {
if (s) stats = s;
if (stats) statsEl.textContent = `${stats.tracks} tracks · ${stats.artists_crawled}/${stats.artists} artists crawled · ${stats.liked} liked`;
}
let toastTimer = 0;
function toast(text: string, ms = 2200): void {
toastEl.textContent = text;
/// A short note at the bottom; `action` adds a button to it, like "undo".
function toast(text: string, ms = 2200, action?: { label: string; run: () => void }): void {
toastEl.replaceChildren(text);
if (action) {
const b = document.createElement("button");
b.type = "button";
b.textContent = action.label;
b.addEventListener("click", () => {
toastEl.classList.remove("show");
action.run();
}, { once: true });
toastEl.append(b);
}
toastEl.classList.toggle("has-action", !!action);
toastEl.classList.add("show");
clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => toastEl.classList.remove("show"), ms);
toastTimer = window.setTimeout(() => toastEl.classList.remove("show"), action ? Math.max(ms, 5000) : ms);
}
function finishActive(): void {
@@ -152,11 +188,13 @@ function activate(idx: number): void {
lastTime = 0;
reported = false;
advanced = false;
remembered = false;
const card = cards[idx];
if (pager.index !== idx) pager.go(idx, { instant: true });
card.element().classList.add("current");
visual.attach(card);
if (started) play(card.track);
else showStart(card);
clearTimeout(preloadTimer);
preloadTimer = window.setTimeout(() => {
const next = cards[active + 1];
@@ -164,6 +202,7 @@ function activate(idx: number): void {
}, PRELOAD_AFTER_MS);
if (idx >= cards.length - PREFETCH_AHEAD) loadMore();
updateRadioEnd();
showUpNext();
cards.forEach((c, i) => { if (c.el && Math.abs(i - idx) > KEEP_BUILT) c.release(); });
}
@@ -181,6 +220,31 @@ function playbackFailed(): void {
go(active + 1);
}
/// Put `track` right after the current card and go there.
function playNow(track: Track, liked = false): void {
Sheet.closeAll();
if (!started) start();
cards.splice(active + 1, 0, new Card(track, actions, { liked }));
pager.refresh();
go(active + 1);
}
// Up next -----------------------------------------------------------------
function showUpNext(): void {
const next = cards[active + 1];
upNext.hidden = !next || !started;
if (!next) return;
const t = next.track;
upNext.querySelector(".up-next-title")!.textContent = `${cleanTitle(t.title)} · ${t.artist_name}`;
const av = upNext.querySelector<HTMLElement>(".up-next-avatar")!;
const img = api.artistImg(t);
av.style.backgroundImage = img ? `url("${img}")` : "";
av.style.backgroundColor = img ? "" : accentForName(t.artist_name || "?");
av.textContent = img ? "" : (t.artist_name || "?")[0].toUpperCase();
}
upNext.addEventListener("click", () => go(active + 1));
// Card actions ------------------------------------------------------------
const actions: CardActions = {
@@ -206,9 +270,17 @@ function setLike(card: Card, liked: boolean): void {
function dislike(card: Card): void {
api.sendEvent(card.track, "dislike");
if (card === current()) reported = true; // a dislike says more than a skip
if (card.liked) setLike(card, false);
toast("got it, less like this");
const wasLiked = card.liked;
if (wasLiked) setLike(card, false);
go(cards.indexOf(card) + 1);
toast("skipped, less of this", 5000, {
label: "undo",
run: () => {
api.sendEvent(card.track, "undislike");
if (wasLiked) setLike(card, true);
go(cards.indexOf(card));
},
});
}
async function setFollow(card: Card, follow: boolean): Promise<void> {
@@ -228,12 +300,14 @@ async function setFollow(card: Card, follow: boolean): Promise<void> {
}
}
/// Shares a link that opens this app on the track, with pl8list's own link in the text.
async function share(card: Card): Promise<void> {
const { track } = card;
const url = api.trackUrl(track);
const url = api.appTrackUrl(track);
const title = cleanTitle(track.title);
if (navigator.share && isTouch) {
try {
await navigator.share({ title: cleanTitle(track.title), text: `${cleanTitle(track.title)} by ${track.artist_name}`, url });
await navigator.share({ title, text: `${title} by ${track.artist_name} · ${api.trackUrl(track)}`, url });
} catch { /* dismissed */ }
return;
}
@@ -245,6 +319,14 @@ async function share(card: Card): Promise<void> {
}
}
/// The rewind: spin the drop back, slow the tune down, and run it again.
function wheelUp(): void {
if (!current()) return;
visual.wheelUp();
player.wheelUp();
toast("wheel up!");
}
// Player events -----------------------------------------------------------
player.on("timeupdate", () => {
@@ -253,10 +335,16 @@ player.on("timeupdate", () => {
const d = t - lastTime;
if (d > 0 && d < 1.5) listened += d; // ignore seeks
lastTime = t;
current()?.setTime(t);
const card = current();
card?.setTime(t);
updatePosition();
// Where tracks can be mixed, start the next one just before this one ends.
if (player.mixing && !advanced && !document.hidden && a.duration && a.duration - t < 1 && cards[active + 1]) {
if (card && !remembered && listened >= HISTORY_AFTER) {
remembered = true;
heard.add(card.track);
}
// Where tracks can be mixed, start the next one so they overlap by the crossfade.
const lead = Math.max(1, player.crossfade);
if (player.mixing && !advanced && !document.hidden && a.duration && a.duration - t < lead && cards[active + 1] && !sleepAtEnd) {
advanced = true;
if (!reported) { api.sendEvent(cards[active].track, "complete", listened); reported = true; }
go(active + 1);
@@ -269,6 +357,12 @@ player.on("ended", () => {
api.sendEvent(card.track, "complete", listened);
reported = true;
}
if (sleepAtEnd) {
sleepAtEnd = false;
showSleep();
toast("good night");
return;
}
go(active + 1);
});
@@ -333,13 +427,38 @@ if ("mediaSession" in navigator) {
}
}
// Tap to play/pause, double-tap to like ------------------------------------
// Tap to play/pause, double-tap to like, hold to rewind ---------------------
let lastTap: { at: number; card: Card | null; toggled: boolean } = { at: 0, card: null, toggled: false };
let swallowClick = false; // the tap that only closed a panel
let press: { timer: number; x: number; y: number } | null = null;
let pressFired = false;
feedEl.addEventListener("pointerdown", (e) => {
if (!started || !(e.target as Element).closest(".card.current .art")) return;
pressFired = false;
press = {
x: e.clientX,
y: e.clientY,
timer: window.setTimeout(() => {
press = null;
pressFired = true;
wheelUp();
}, LONG_PRESS_MS),
};
});
const cancelPress = (e: PointerEvent) => {
if (press && (e.type !== "pointermove" || Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10)) {
clearTimeout(press.timer);
press = null;
}
};
for (const ev of ["pointermove", "pointerup", "pointercancel"]) feedEl.addEventListener(ev, (e) => cancelPress(e as PointerEvent));
// A long press opens the context menu on some phones.
feedEl.addEventListener("contextmenu", (e) => { if ((e.target as Element).closest(".art")) e.preventDefault(); });
feedEl.addEventListener("click", (e) => {
if (swallowClick || pager.suppressClick) { swallowClick = false; return; }
if (pager.suppressClick) return;
if (pressFired) { pressFired = false; return; }
const target = e.target as Element;
if (target.closest("button, a, input, .wave-wrap")) return;
const el = target.closest(".card");
@@ -371,36 +490,6 @@ feedEl.addEventListener("click", (e) => {
// Any gesture may set up the audio graph; browsers only allow it from one.
for (const ev of ["pointerdown", "keydown"]) document.addEventListener(ev, () => { if (started) player.unlock(); }, true);
// Panels and overlays -----------------------------------------------------
const panels: [HTMLElement, HTMLElement][] = [[filtersForm, filtersBtn], [likesPanel, likesBtn], [accountPanel, accountBtn]];
function closePanels(): void {
for (const [panel, btn] of panels) {
panel.hidden = true;
btn.setAttribute("aria-expanded", "false");
}
}
function togglePanel(panel: HTMLElement): boolean {
const open = panel.hidden !== false;
closePanels();
if (open) {
panel.hidden = false;
panels.find(([p]) => p === panel)![1].setAttribute("aria-expanded", "true");
}
return open;
}
document.addEventListener("pointerdown", (e) => {
const open = panels.find(([p]) => !p.hidden);
const target = e.target as Element;
if (!open || open[0].contains(target) || target.closest("#bar")) return;
closePanels();
swallowClick = true;
setTimeout(() => { swallowClick = false; }, 500);
}, true);
// Volume ------------------------------------------------------------------
const volumeEl = $("volume");
@@ -439,22 +528,16 @@ volumeSlider.addEventListener("wheel", (e) => {
setVolume(player.volume - Math.sign(e.deltaY) * 0.05);
}, { passive: false });
let helpOpener: HTMLElement | null = null;
const showHelp = () => {
helpOpener = document.activeElement as HTMLElement | null;
helpEl.hidden = false;
$("help-close").focus();
};
const hideHelp = () => {
if (helpEl.hidden) return;
helpEl.hidden = true;
helpOpener?.focus();
};
$("help-btn").addEventListener("click", showHelp);
// The bar has no room for "?" on phones; the account panel has a way in.
$("help-open").addEventListener("click", () => { closePanels(); showHelp(); });
$("help-close").addEventListener("click", hideHelp);
helpEl.addEventListener("click", (e) => { if (e.target === helpEl) hideHelp(); });
// Start -------------------------------------------------------------------
$("help-close").addEventListener("click", () => sheets.help.close());
for (const id of ["help-open", "help-open-settings"]) $(id).addEventListener("click", () => sheets.help.open());
/// The overlay before the first tap names what will play.
function showStart(card: Card): void {
const t = card.track;
startEl.querySelector(".start-track")!.textContent = `${cleanTitle(t.title)} · ${t.artist_name}`;
}
function start(): void {
if (started) return;
@@ -463,9 +546,10 @@ function start(): void {
player.unlock();
const card = current();
if (card) activateAgain(card);
showUpNext();
if (!localStorage.getItem(HINT_KEY)) {
localStorage.setItem(HINT_KEY, "1");
toast(isTouch ? "tap to pause · double-tap to like · swipe up for next"
toast(isTouch ? "tap to pause · double-tap to like · hold the drop to rewind"
: "click to pause · double-click to like · ? for shortcuts", 5000);
}
}
@@ -483,47 +567,160 @@ function activateAgain(card: Card): void {
// Likes -----------------------------------------------------------------
likesBtn.addEventListener("click", async () => {
if (!togglePanel(likesPanel)) return;
const list = $("likes-list");
let tracks: Track[];
const likesList = $("likes-list");
const likesSearch = $<HTMLInputElement>("likes-search");
const likesShuffle = $<HTMLInputElement>("likes-shuffle");
let likedTracks: Track[] = [];
/// A row in the likes or history sheet: artwork with a play button, title, artist.
function trackRow(t: Track, sub: string, extra?: HTMLElement): HTMLLIElement {
const li = document.createElement("li");
li.className = "track-row";
const play = document.createElement("button");
play.type = "button";
play.className = "row-play";
play.title = "play now";
play.setAttribute("aria-label", `play ${cleanTitle(t.title)}`);
const img = api.artistImg(t);
if (img) play.style.backgroundImage = `url("${img}")`;
else play.style.backgroundColor = accentForName(t.artist_name || "?");
play.innerHTML = '<svg><use href="#i-play"/></svg>';
play.addEventListener("click", () => playNow(t, likedTracks.some((l) => l.id === t.id)));
const meta = document.createElement("div");
meta.className = "meta";
const a = document.createElement("a");
a.href = api.trackUrl(t);
a.target = "_blank";
a.rel = "noopener";
a.textContent = cleanTitle(t.title);
const by = document.createElement("span");
by.textContent = sub;
meta.append(a, by);
li.append(play, meta);
if (extra) li.append(extra);
return li;
}
const matches = (t: Track, q: string) => !q || `${t.title} ${t.artist_name} ${(t.tags ?? []).join(" ")}`.toLowerCase().includes(q);
function setCardsLiked(id: number, liked: boolean): void {
for (const c of cards) {
if (c.track.id !== id) continue;
c.liked = liked;
c.showLike();
}
}
function showLikes(): void {
const q = likesSearch.value.trim().toLowerCase();
const shown = likedTracks.filter((t) => matches(t, q));
likesList.replaceChildren(...shown.map((t) => {
const unlike = document.createElement("button");
unlike.type = "button";
unlike.className = "icon-btn row-unlike";
unlike.title = "unlike";
unlike.setAttribute("aria-label", `unlike ${cleanTitle(t.title)}`);
unlike.innerHTML = '<svg><use href="#i-heart"/></svg>';
unlike.addEventListener("click", () => {
api.sendEvent(t, "unlike");
if (stats) { stats.liked--; showStats(); }
setCardsLiked(t.id, false);
const at = likedTracks.indexOf(t);
likedTracks.splice(at, 1);
showLikes();
toast("unliked", 4000, {
label: "undo",
run: () => {
api.sendEvent(t, "like");
if (stats) { stats.liked++; showStats(); }
setCardsLiked(t.id, true);
likedTracks.splice(at, 0, t);
showLikes();
},
});
});
const sub = t.artist_name + (t.followed ? " · following" : "") + (t.bpm ? ` · ${Math.round(t.bpm)} bpm` : "");
return trackRow(t, sub, unlike);
}));
if (!likedTracks.length) likesList.textContent = "nothing liked yet. double-tap a track you like.";
else if (!shown.length) likesList.textContent = "no likes match that.";
$<HTMLButtonElement>("likes-play").disabled = !shown.length;
}
sheets.likes.onOpen = async () => {
likesList.textContent = "loading…";
try {
({ tracks } = await api.likes());
({ tracks: likedTracks } = await api.likes());
} catch (err) {
list.textContent = `couldn't load your likes: ${(err as Error).message}`;
likesList.textContent = `couldn't load your likes: ${(err as Error).message}`;
return;
}
list.replaceChildren(...tracks.map((t) => {
const li = document.createElement("li");
const btn = document.createElement("button");
btn.type = "button";
btn.className = "play-now";
btn.title = "play now";
btn.innerHTML = '<svg><use href="#i-play"/></svg>';
btn.addEventListener("click", () => {
closePanels();
if (!started) start();
cards.splice(active + 1, 0, new Card(t, actions, { liked: true }));
pager.refresh();
go(active + 1);
});
const meta = document.createElement("div");
meta.className = "meta";
const a = document.createElement("a");
a.href = api.trackUrl(t);
a.target = "_blank";
a.rel = "noopener";
a.textContent = cleanTitle(t.title);
const by = document.createElement("span");
by.textContent = t.artist_name + (t.followed ? " · following" : "");
meta.append(a, by);
li.append(btn, meta);
return li;
}));
if (!tracks.length) list.textContent = "nothing liked yet. double-tap a track you like.";
showLikes();
};
likesSearch.addEventListener("input", showLikes);
/// Play the likes shown, in order or shuffled, instead of the feed.
$("likes-play").addEventListener("click", () => {
const list = likedTracks.filter((t) => matches(t, likesSearch.value.trim().toLowerCase()));
if (!list.length) return;
if (likesShuffle.checked) {
for (let i = list.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[list[i], list[j]] = [list[j], list[i]];
}
}
Sheet.closeAll();
if (!started) start();
queue = { tracks: list, next: 0 };
showMode();
for (const c of cards.splice(active + 1)) c.release();
feedGen++;
loading = false;
jumpOnLoad = true;
fromQueue();
toast(`playing ${list.length} like${list.length === 1 ? "" : "s"}${likesShuffle.checked ? ", shuffled" : ""}`);
});
// Filters ---------------------------------------------------------------
/// The next few tracks of the likes queue as cards.
function fromQueue(): void {
if (!queue) return;
const more = queue.tracks.slice(queue.next, queue.next + 5);
queue.next += more.length;
if (!more.length) {
setStatus("that was all of them. tap the chip up top for your feed.");
return;
}
addCards(more.map((t) => new Card(t, actions, { liked: true })));
}
// History ---------------------------------------------------------------
const historyList = $("history-list");
/// `ts` in seconds since the epoch.
function ago(ts: number): string {
const m = Math.round((Date.now() / 1000 - ts) / 60);
if (m < 1) return "just now";
if (m < 60) return `${m} min ago`;
if (m < 48 * 60) return `${Math.round(m / 60)} h ago`;
return `${Math.round(m / 1440)} days ago`;
}
sheets.history.onOpen = () => {
const list = heard.load();
historyList.replaceChildren(...list.map((h) => trackRow(h.track, `${h.track.artist_name} · ${ago(h.at / 1000)}`)));
if (!list.length) historyList.textContent = "nothing played on this device yet.";
};
$("history-clear").addEventListener("click", () => {
heard.clear();
historyList.textContent = "cleared.";
});
// Filters and settings --------------------------------------------------
const bpmMin = filtersForm.elements.namedItem("bpm_min") as HTMLInputElement;
const bpmMax = filtersForm.elements.namedItem("bpm_max") as HTMLInputElement;
const bpmOut = $("bpm-out");
function loadFilters(): Filters {
try {
@@ -533,28 +730,42 @@ function loadFilters(): Filters {
}
}
function showBpm(): void {
// The two thumbs never cross.
if (Number(bpmMin.value) > Number(bpmMax.value)) [bpmMin.value, bpmMax.value] = [bpmMax.value, bpmMin.value];
const [lo, hi] = [Number(bpmMin.value), Number(bpmMax.value)];
const anyLo = lo <= BPM_RANGE[0], anyHi = hi >= BPM_RANGE[1];
bpmOut.textContent = anyLo && anyHi ? "any" : anyLo ? `up to ${hi}` : anyHi ? `${lo} and up` : lo === hi ? `${lo}` : `${lo}–${hi}`;
const span = BPM_RANGE[1] - BPM_RANGE[0];
filtersForm.style.setProperty("--lo", `${((lo - BPM_RANGE[0]) / span) * 100}%`);
filtersForm.style.setProperty("--hi", `${((hi - BPM_RANGE[0]) / span) * 100}%`);
for (const b of filtersForm.querySelectorAll<HTMLButtonElement>("[data-bpm]")) {
b.setAttribute("aria-pressed", String(b.dataset.bpm === `${lo}-${hi}`));
}
}
function showFilters(): void {
const f = filtersForm.elements as unknown as Record<string, HTMLInputElement>;
f.free.checked = filters.free === "1";
f.bpm_min.value = filters.bpm_min || "";
f.bpm_max.value = filters.bpm_max || "";
(filtersForm.elements.namedItem("free") as HTMLInputElement).checked = filters.free === "1";
bpmMin.value = filters.bpm_min || String(BPM_RANGE[0]);
bpmMax.value = filters.bpm_max || String(BPM_RANGE[1]);
showBpm();
filtersBtn.classList.toggle("active", Object.keys(filters).length > 0);
}
function applyFilters(): void {
const f = new FormData(filtersForm);
filters = {};
if (f.get("free")) filters.free = "1";
if (f.get("bpm_min")) filters.bpm_min = String(f.get("bpm_min"));
if (f.get("bpm_max")) filters.bpm_max = String(f.get("bpm_max"));
if ((filtersForm.elements.namedItem("free") as HTMLInputElement).checked) filters.free = "1";
if (Number(bpmMin.value) > BPM_RANGE[0]) filters.bpm_min = bpmMin.value;
if (Number(bpmMax.value) < BPM_RANGE[1]) filters.bpm_max = bpmMax.value;
localStorage.setItem(FILTERS_KEY, JSON.stringify(filters));
showFilters();
closePanels();
Sheet.closeAll();
refill();
}
/// Drop cards after the current one so a new filter or mode applies right away.
function refill(): void {
queue = null;
for (const c of cards.splice(active + 1)) c.release();
pager.refresh();
feedGen++;
@@ -562,9 +773,106 @@ function refill(): void {
loadMore();
}
for (const input of [bpmMin, bpmMax]) input.addEventListener("input", showBpm);
for (const b of filtersForm.querySelectorAll<HTMLButtonElement>("[data-bpm]")) {
b.addEventListener("click", () => {
[bpmMin.value, bpmMax.value] = b.dataset.bpm!.split("-");
showBpm();
});
}
function showSetting(name: string, value: string): void {
for (const input of filtersForm.querySelectorAll<HTMLInputElement>(`input[name=${name}]`)) input.checked = input.value === value;
}
function setVisuals(v: VisualsSetting): void {
visual.visuals = v;
showSetting("visuals", v);
}
filtersForm.addEventListener("change", (e) => {
const input = e.target as HTMLInputElement;
if (input.name === "visuals") setVisuals(input.value as VisualsSetting);
else if (input.name === "crossfade") player.crossfade = Number(input.value);
else if (input.name === "bass") player.bassBoost = input.checked;
else if (input.name === "sleep") setSleep(input.value);
});
filtersForm.addEventListener("submit", (e) => { e.preventDefault(); applyFilters(); });
$("filters-clear").addEventListener("click", () => {
(filtersForm.elements.namedItem("free") as HTMLInputElement).checked = false;
[bpmMin.value, bpmMax.value] = BPM_RANGE.map(String);
applyFilters();
});
function showSettings(): void {
showSetting("visuals", visual.visuals);
// A saved crossfade that is not one of the choices shows as the nearest one.
const fades = [...filtersForm.querySelectorAll<HTMLInputElement>("input[name=crossfade]")].map((i) => Number(i.value));
const fade = fades.reduce((a, b) => (Math.abs(b - player.crossfade) < Math.abs(a - player.crossfade) ? b : a));
showSetting("crossfade", String(fade));
const bass = filtersForm.elements.namedItem("bass") as HTMLInputElement;
bass.checked = player.bassBoost;
bass.closest("label")!.hidden = !player.canMix;
showSleep();
}
sheets.filters.onOpen = showSettings;
// Sleep timer -----------------------------------------------------------
let sleepTimer = 0;
let sleepUntil = 0;
let sleepAtEnd = false;
let sleepFade = 0;
function setSleep(value: string): void {
clearTimeout(sleepTimer);
cancelAnimationFrame(sleepFade);
player.dimmed = 1;
sleepUntil = 0;
sleepAtEnd = value === "end";
if (value !== "off" && value !== "end") {
const ms = Number(value) * 60_000;
sleepUntil = Date.now() + ms;
sleepTimer = window.setTimeout(sleepNow, Math.max(0, ms - SLEEP_FADE * 1000));
}
showSleep();
if (value !== "off") toast(value === "end" ? "stopping after this track" : `stopping in ${value} min`);
}
/// Fade out over SLEEP_FADE seconds, then pause.
function sleepNow(): void {
const stop = () => {
player.pause();
player.dimmed = 1;
sleepUntil = 0;
showSleep();
};
// Hidden tabs get no animation frames: there it stops at once.
if (document.hidden) {
stop();
return;
}
const t0 = performance.now();
const step = () => {
const k = (performance.now() - t0) / 1000 / SLEEP_FADE;
player.dimmed = 1 - k;
if (k < 1) sleepFade = requestAnimationFrame(step);
else stop();
};
sleepFade = requestAnimationFrame(step);
}
function showSleep(): void {
if (!sleepUntil) showSetting("sleep", sleepAtEnd ? "end" : "off");
$("sleep-left").textContent = sleepUntil
? `${fmtTime(Math.max(0, sleepUntil - Date.now()) / 1000)} left`
: sleepAtEnd ? "after this track" : "";
}
// Feed modes --------------------------------------------------------------
const modeChip = $("mode-chip");
const modeTabs = $("mode-tabs");
const MODE_NAMES = { classic: "for you", riddim: "riddim", fresh: "fresh", deep: "deep cuts" };
function loadMode(): Mode {
@@ -577,31 +885,45 @@ function loadMode(): Mode {
const modeName = (m: Mode) => (m.mode === "artist" ? `${m.name} radio` : MODE_NAMES[m.mode]);
const MODE_ICONS = { riddim: "◆", fresh: "✦", deep: "◎" };
function showMode(): void {
modeChip.hidden = mode.mode === "classic";
modeChip.querySelector(".chip-label")!.textContent = modeName(mode);
// A radio or the likes queue shows as a chip that leads back; the tabs make way.
const chip = mode.mode === "artist" || queue !== null;
modeChip.hidden = !chip;
modeTabs.hidden = chip;
for (const b of modeTabs.querySelectorAll<HTMLButtonElement>("button")) {
b.setAttribute("aria-pressed", String(b.dataset.mode === mode.mode));
}
const avatar = modeChip.querySelector<HTMLElement>(".chip-avatar")!;
const label = modeChip.querySelector(".chip-label")!;
if (queue) {
label.textContent = "your likes";
avatar.style.backgroundImage = "";
avatar.innerHTML = '<svg><use href="#i-heart"/></svg>';
return;
}
label.textContent = modeName(mode);
const img = mode.mode === "artist" ? mode.img : null;
avatar.style.backgroundImage = img ? `url("${img}")` : "";
avatar.textContent = img ? "" : mode.mode === "artist" ? mode.name[0]?.toUpperCase() ?? "" : mode.mode === "classic" ? "" : MODE_ICONS[mode.mode];
for (const input of filtersForm.querySelectorAll<HTMLInputElement>("input[name=mode]")) input.checked = input.value === mode.mode;
avatar.textContent = img || mode.mode !== "artist" ? "" : mode.name[0]?.toUpperCase() ?? "";
}
function setMode(m: Mode): void {
radioDry = false;
updateRadioEnd();
if (JSON.stringify(m) === JSON.stringify(mode)) return;
if (JSON.stringify(m) === JSON.stringify(mode) && !queue) return;
mode = m;
queue = null;
localStorage.setItem(MODE_KEY, JSON.stringify(mode));
showMode();
closePanels();
Sheet.closeAll();
toast(m.mode === "classic" ? "back to your feed" : `now playing: ${modeName(m)}`);
refill();
}
modeChip.addEventListener("click", () => setMode({ mode: "classic" }));
for (const b of modeTabs.querySelectorAll<HTMLButtonElement>("button")) {
b.addEventListener("click", () => setMode({ mode: b.dataset.mode as "classic" | "riddim" | "fresh" | "deep" }));
}
const station = new Station((m) => {
if (!started) start();
@@ -627,28 +949,9 @@ function updateRadioEnd(): void {
}
}
$("radio-end-feed").addEventListener("click", () => setMode({ mode: "classic" }));
filtersForm.addEventListener("change", (e) => {
const input = e.target as HTMLInputElement;
if (input.name === "mode") setMode({ mode: input.value as "classic" | "riddim" | "fresh" | "deep" });
if (input.name === "visuals") setVisuals(input.value as VisualsSetting);
});
function setVisuals(v: VisualsSetting): void {
visual.visuals = v;
for (const input of filtersForm.querySelectorAll<HTMLInputElement>("input[name=visuals]")) input.checked = input.value === v;
}
setVisuals(visual.visuals);
showMode();
filtersBtn.addEventListener("click", () => togglePanel(filtersForm));
filtersForm.addEventListener("submit", (e) => { e.preventDefault(); applyFilters(); });
$("filters-clear").addEventListener("click", () => {
filtersForm.reset();
// reset() also clears the mode and visuals radios, which "clear" leaves alone.
showMode();
setVisuals(visual.visuals);
applyFilters();
});
showFilters();
// Keyboard --------------------------------------------------------------
@@ -658,29 +961,33 @@ document.addEventListener("keydown", (e) => {
const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
if (k === "Escape") {
setZen(false);
closePanels();
hideHelp();
station.close();
return;
}
if (k === "?") { helpEl.hidden ? showHelp() : hideHelp(); return; }
if (station.isOpen || !helpEl.hidden || !loginEl.hidden) return;
if (k === "?") { sheets.help.toggle(); return; }
if (station.isOpen || Sheet.current || !loginEl.hidden) return;
if (!started) {
if (k !== "Tab" && k !== "Shift") { e.preventDefault(); start(); }
return;
}
const card = current();
const a = player.audio;
if (k === "ArrowDown" || k === "j") { e.preventDefault(); go(active + 1); }
if (k === "ArrowDown" || k === "j" || k === "n") { e.preventDefault(); go(active + 1); }
else if (k === "ArrowUp" || k === "k") { e.preventDefault(); go(active - 1); }
else if (k === " ") { e.preventDefault(); player.toggle(); card?.flash(!a.paused); }
else if (k === "ArrowRight") player.seek(a.currentTime + 10);
else if (k === "ArrowLeft") player.seek(a.currentTime - 10);
else if (k === ".") player.seek(a.currentTime + 5);
else if (k === ",") player.seek(a.currentTime - 5);
else if (/^[0-9]$/.test(k) && a.duration) player.seek((Number(k) / 10) * a.duration);
else if (k === "l" && card) setLike(card, !card.liked);
else if (k === "f" && card) setFollow(card, !card.track.followed);
else if (k === "r" && card) actions.radio(card);
else if (k === "x" && card) dislike(card);
else if (k === "s" && card) share(card);
else if (k === "w") wheelUp();
else if (k === "h") sheets.history.open();
else if (k === "c") sheets.filters.open();
else if (k === "v") { setVisuals(visual.visuals === "liquid" ? "simple" : "liquid"); toast(`${visual.visuals} visuals`); }
else if (k === "m") { setMuted(!player.muted); toast(player.muted ? "muted" : "sound on"); }
else if (k === "+" || k === "=") { setVolume(player.volume + 0.1); toast(`volume ${Math.round(player.volume * 100)}%`); }
@@ -693,7 +1000,7 @@ function setZen(on: boolean): void {
if (document.body.classList.contains("zen") === on) return;
document.body.classList.toggle("zen", on);
if (on) {
closePanels();
Sheet.closeAll();
toast("zen · z or esc to leave");
}
}
@@ -713,9 +1020,10 @@ let signedInUser: User | null = null;
// `resync`: already signed in, signing in again only to sync with pl8list.
function showLogin({ resync = false } = {}): void {
closePanels();
Sheet.closeAll();
$("bar").hidden = true;
startEl.hidden = true;
upNext.hidden = true;
loginEl.hidden = false;
emailForm.hidden = false;
codeForm.hidden = true;
@@ -782,14 +1090,6 @@ const deleteConfirm = $<HTMLInputElement>("delete-confirm");
const syncStatus = $("sync-status");
const disconnectBtn = $("disconnect-btn");
function ago(ts: number): string {
const m = Math.round((Date.now() / 1000 - ts) / 60);
if (m < 1) return "just now";
if (m < 60) return `${m} min ago`;
if (m < 48 * 60) return `${Math.round(m / 60)} h ago`;
return `${Math.round(m / 1440)} days ago`;
}
function showSync(s: Pl8Status | undefined): void {
const connected = !!s?.connected;
syncStatus.classList.toggle("on", connected);
@@ -800,11 +1100,10 @@ function showSync(s: Pl8Status | undefined): void {
disconnectBtn.hidden = !connected;
}
accountBtn.addEventListener("click", async () => {
if (!togglePanel(accountPanel)) return;
sheets.account.onOpen = async () => {
deleteForm.hidden = true;
try { showSync((await api.me()).pl8list); } catch { /* keep what is shown */ }
});
};
$("sync-btn").addEventListener("click", async () => {
try {
@@ -848,9 +1147,8 @@ deleteForm.addEventListener("submit", async (e) => {
e.preventDefault();
try {
await api.postJSON("/account/delete", { confirm: deleteConfirm.value.trim() });
localStorage.removeItem(FILTERS_KEY);
localStorage.removeItem(MODE_KEY);
localStorage.removeItem(HINT_KEY);
for (const key of [FILTERS_KEY, MODE_KEY, HINT_KEY]) localStorage.removeItem(key);
heard.clear();
location.reload();
} catch (err) {
toast((err as Error).message, 4000);
@@ -862,13 +1160,30 @@ function signedIn(user: User, pl8list?: Pl8Status): void {
if (pl8list) showSync(pl8list);
loginEl.hidden = true;
$("bar").hidden = false;
accountBtn.textContent = `@${user.handle}`;
accountBtn.textContent = (user.name || user.handle)[0]?.toUpperCase() ?? "?";
accountBtn.style.backgroundColor = accentForName(user.handle);
accountBtn.title = `@${user.handle}`;
$("account-handle").textContent = `@${user.handle}`;
$("delete-handle").textContent = user.handle;
// Typing the login code counts as a user gesture, so playback may start right away.
if (navigator.userActivation?.hasBeenActive) start();
else if (!started) startEl.hidden = false;
if (!cards.length) loadMore();
if (!cards.length) openLinkOrFeed();
}
/// `/?t=handle/slug` opens on that track; the feed carries on after it.
async function openLinkOrFeed(): Promise<void> {
const link = new URLSearchParams(location.search).get("t")?.split("/");
if (link?.length === 2) {
history.replaceState(null, "", location.pathname);
try {
const { track } = await api.track(link[0], link[1]);
addCards([new Card(track, actions)]);
} catch (err) {
toast(`couldn't open that link: ${(err as Error).message}`, 4000);
}
}
loadMore();
}
api.me().then(
+89 -13
View File
@@ -3,17 +3,24 @@
//
// Where the browser allows it, both <audio> elements run through a Web Audio graph:
// a gain per deck (for the crossfade) into one analyser (for the visuals), then a
// master gain for the volume, so the visuals look the same at any volume. iOS is
// master gain for the volume, so the visuals look the same at any volume. A
// low shelf between the two boosts the bass when asked, also after the analyser,
// so the visuals do not change with it. iOS is
// left out: its element volume is read-only and Web Audio stops when the screen
// locks, which would break lock-screen playback. There tracks switch with a cut.
import type HlsType from "hls.js/light";
import { type Track, streamUrl } from "./api";
const CROSSFADE = 0.9; // seconds
const CROSSFADE = 0.9; // seconds, unless set otherwise
const PRELOAD_BUFFER = 6; // seconds buffered of the track after the current one
const PLAY_BUFFER = 30;
const VOLUME_KEY = "pl8inf.volume";
const CROSSFADE_KEY = "pl8inf.crossfade";
const BASS_KEY = "pl8inf.bass";
const BASS_DB = 6; // gain of the bass boost's low shelf …
const BASS_HZ = 120; // … below this
const TAPE_STOP = 0.45; // s the rewind's tape stop takes
type Hls = HlsType;
type HlsClass = typeof HlsType;
@@ -47,9 +54,10 @@ export type PlayerEvent = "timeupdate" | "ended" | "play" | "pause" | "waiting"
const FORWARDED: PlayerEvent[] = ["timeupdate", "ended", "play", "pause", "waiting", "playing"];
/// Equal-power fade of `param` from its current value to `to`. A fade can start
/// while the previous one still runs (fast flicking), so it starts where that one is.
function fade(param: AudioParam, to: number, at: number): void {
/// Equal-power fade of `param` from its current value to `to` over `length`
/// seconds. A fade can start while the previous one still runs (fast flicking), so
/// it starts where that one is.
function fade(param: AudioParam, to: number, at: number, length: number): void {
const from = param.value;
param.cancelScheduledValues(0);
const up = to > from;
@@ -58,7 +66,7 @@ function fade(param: AudioParam, to: number, at: number): void {
return up ? from + (to - from) * Math.sin(x) : to + (from - to) * Math.cos(x);
});
try {
param.setValueCurveAtTime(curve, at, CROSSFADE);
param.setValueCurveAtTime(curve, at, length);
} catch {
param.value = to;
}
@@ -71,6 +79,12 @@ export class Player {
private unlocking: Promise<void> | null = null;
private fadeEnd = 0;
private master: GainNode | null = null;
private shelf: BiquadFilterNode | null = null;
private bass = localStorage.getItem(BASS_KEY) === "1";
/// Seconds two tracks overlap; 0 cuts.
private fadeFor = Number(localStorage.getItem(CROSSFADE_KEY) ?? CROSSFADE);
/// The sleep timer's fade, 1 down to 0, on top of the volume.
private dim = 1;
private vol = Number(localStorage.getItem(VOLUME_KEY) ?? 1);
private listeners = new Map<PlayerEvent, Set<() => void>>();
analyser: AnalyserNode | null = null;
@@ -89,6 +103,7 @@ export class Player {
};
this.decks = [deck(), deck()];
if (!(this.vol >= 0 && this.vol <= 1)) this.vol = 1;
if (!(this.fadeFor >= 0 && this.fadeFor <= 12)) this.fadeFor = CROSSFADE;
this.volume = this.vol;
for (const d of this.decks) {
for (const ev of FORWARDED) {
@@ -157,7 +172,11 @@ export class Player {
analyser.fftSize = 2048;
analyser.smoothingTimeConstant = 0.2; // features.ts smooths per feature; this only takes the edge off the FFT
const master = ctx.createGain();
analyser.connect(master).connect(ctx.destination);
const shelf = ctx.createBiquadFilter();
shelf.type = "lowshelf";
shelf.frequency.value = BASS_HZ;
shelf.gain.value = this.bass ? BASS_DB : 0;
analyser.connect(shelf).connect(master).connect(ctx.destination);
for (const d of this.decks) {
d.el.volume = 1; // the master gain takes over
const gain = ctx.createGain();
@@ -168,6 +187,7 @@ export class Player {
this.ctx = ctx;
this.analyser = analyser;
this.master = master;
this.shelf = shelf;
this.volume = this.vol;
}
@@ -186,19 +206,20 @@ export class Player {
} else {
this.load(to, track, PLAY_BUFFER);
}
const crossfade = this.mixing && !document.hidden && !from.el.paused && from.track !== null;
const crossfade = this.fadeFor > 0 && this.mixing && !document.hidden && !from.el.paused && from.track !== null;
this.cur = toIdx;
to.wantPlay = true;
if (this.ctx?.state === "suspended") this.ctx.resume().catch(() => {});
if (crossfade && to.gain && from.gain) {
const t = this.ctx!.currentTime;
fade(to.gain.gain, 1, t);
fade(from.gain.gain, 0, t);
this.fadeEnd = performance.now() + CROSSFADE * 1000;
const length = this.fadeFor;
fade(to.gain.gain, 1, t, length);
fade(from.gain.gain, 0, t, length);
this.fadeEnd = performance.now() + length * 1000;
const gen = from.gen;
setTimeout(() => {
if (from.gen === gen && from !== this.decks[this.cur]) this.unload(from);
}, CROSSFADE * 1000 + 50);
}, length * 1000 + 50);
} else {
if (to.gain) {
to.gain.gain.cancelScheduledValues(0);
@@ -280,6 +301,32 @@ export class Player {
this.audio.pause();
}
/// The soundsystem rewind: the record is pulled back, the music slows down and
/// drops in pitch, and the tune starts again from the top.
async wheelUp(): Promise<void> {
const a = this.audio;
if (a.paused) {
this.seek(0);
this.resume();
return;
}
const pitch = a.preservesPitch;
a.preservesPitch = false;
const t0 = performance.now();
await new Promise<void>((done) => {
const step = () => {
const k = Math.min(1, (performance.now() - t0) / 1000 / TAPE_STOP);
a.playbackRate = Math.max(0.1, 1 - 0.9 * k * k);
if (k < 1) requestAnimationFrame(step);
else done();
};
requestAnimationFrame(step);
});
a.playbackRate = 1;
a.preservesPitch = pitch;
this.seek(0);
}
seek(seconds: number): void {
const a = this.audio;
a.currentTime = Math.max(0, Math.min(a.duration || 0, seconds));
@@ -302,8 +349,37 @@ export class Player {
set volume(v: number) {
this.vol = Math.max(0, Math.min(1, v));
localStorage.setItem(VOLUME_KEY, String(this.vol));
const out = this.vol * this.vol;
this.applyVolume();
}
private applyVolume(): void {
const out = this.vol * this.vol * this.dim;
if (this.master) this.master.gain.value = out;
else for (const d of this.decks) d.el.volume = out;
}
/// The sleep timer's fade, 0..1. Where the volume is read-only (iOS) it does nothing.
set dimmed(k: number) {
this.dim = Math.max(0, Math.min(1, k));
this.applyVolume();
}
get crossfade(): number {
return this.fadeFor;
}
set crossfade(s: number) {
this.fadeFor = s;
localStorage.setItem(CROSSFADE_KEY, String(s));
}
get bassBoost(): boolean {
return this.bass;
}
set bassBoost(on: boolean) {
this.bass = on;
localStorage.setItem(BASS_KEY, on ? "1" : "0");
if (this.shelf && this.ctx) this.shelf.gain.setTargetAtTime(on ? BASS_DB : 0, this.ctx.currentTime, 0.05);
}
}
+140
View File
@@ -0,0 +1,140 @@
// Sheets: likes, history, settings, account and help. A drawer on the right on
// wide screens, a sheet from the bottom on phones, which a downward swipe on its
// handle closes. One is open at a time, over a scrim that closes it when tapped,
// so a tap meant to close a sheet never reaches the feed. Focus moves into the
// sheet, stays there while it is open, and goes back to what opened it.
const FOCUSABLE = "button:not([disabled]), a[href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex='-1'])";
const CLOSE_DRAG = 0.25; // share of the sheet's height a swipe must cover to close it
const CLOSE_FLING = 0.5; // px/ms; or this fast
const scrim = document.createElement("div");
scrim.className = "scrim";
scrim.hidden = true;
document.body.append(scrim);
let current: Sheet | null = null;
scrim.addEventListener("click", () => current?.close());
document.addEventListener("keydown", (e) => {
if (!current) return;
if (e.key === "Escape") {
e.preventDefault();
current.close();
} else if (e.key === "Tab") {
current.trap(e);
}
});
export class Sheet {
/// Called after the sheet opened, e.g. to load what it shows.
onOpen: (() => void) | null = null;
onClose: (() => void) | null = null;
private opener: HTMLElement | null = null;
/// `button`, if given, opens and closes the sheet and shows whether it is open.
constructor(
readonly el: HTMLElement,
private button?: HTMLElement,
) {
el.classList.add("sheet");
el.setAttribute("role", "dialog");
el.setAttribute("aria-modal", "true");
el.tabIndex = -1;
el.hidden = true;
const handle = document.createElement("div");
handle.className = "sheet-handle";
handle.setAttribute("aria-hidden", "true");
el.prepend(handle);
this.dragToClose(handle);
button?.setAttribute("aria-expanded", "false");
button?.addEventListener("click", () => this.toggle());
}
/// The sheet that is open, if any.
static get current(): Sheet | null {
return current;
}
static closeAll(): void {
current?.close();
}
get isOpen(): boolean {
return current === this;
}
toggle(): void {
if (this.isOpen) this.close();
else this.open();
}
open(): void {
if (this.isOpen) return;
const opener = current?.opener ?? (document.activeElement as HTMLElement | null);
current?.close(false);
current = this;
this.opener = opener;
scrim.hidden = false;
this.el.hidden = false;
this.el.style.transform = "";
this.button?.setAttribute("aria-expanded", "true");
const first = this.el.querySelector<HTMLElement>("[autofocus]") ?? this.el;
first.focus({ preventScroll: true });
this.onOpen?.();
}
/// `restore`: give focus back to what opened the sheet.
close(restore = true): void {
if (!this.isOpen) return;
current = null;
scrim.hidden = true;
this.el.hidden = true;
this.button?.setAttribute("aria-expanded", "false");
if (restore) this.opener?.focus({ preventScroll: true });
this.onClose?.();
}
/// Keep Tab inside the sheet.
trap(e: KeyboardEvent): void {
const items = [...this.el.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((x) => x.offsetParent !== null);
if (!items.length) return;
const [first, last] = [items[0], items[items.length - 1]];
const at = document.activeElement;
if (e.shiftKey && (at === first || at === this.el)) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && at === last) {
e.preventDefault();
first.focus();
}
}
/// On phones the handle drags the sheet down; far or fast enough closes it.
private dragToClose(handle: HTMLElement): void {
let start: { id: number; y: number; t: number } | null = null;
let dy = 0;
handle.addEventListener("pointerdown", (e) => {
start = { id: e.pointerId, y: e.clientY, t: performance.now() };
dy = 0;
handle.setPointerCapture(e.pointerId);
this.el.classList.add("dragging");
});
handle.addEventListener("pointermove", (e) => {
if (start?.id !== e.pointerId) return;
dy = Math.max(0, e.clientY - start.y);
this.el.style.transform = `translateY(${dy}px)`;
});
const end = (e: PointerEvent) => {
if (start?.id !== e.pointerId) return;
dy = Math.max(0, e.clientY - start.y);
const speed = dy / Math.max(1, performance.now() - start.t);
start = null;
this.el.classList.remove("dragging");
this.el.style.transform = "";
if (e.type === "pointerup" && (dy > this.el.offsetHeight * CLOSE_DRAG || speed > CLOSE_FLING)) this.close();
};
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
}
+385 -110
View File
@@ -57,48 +57,89 @@ button {
.sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
/* Header and panels ------------------------------------------------------ */
/* Header ----------------------------------------------------------------- */
#bar {
position: fixed;
inset: 0 0 auto 0;
z-index: 10;
display: flex;
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 0.75rem;
padding: 0.6rem 1rem;
padding-top: max(0.6rem, env(safe-area-inset-top));
background: linear-gradient(#000c, #0000);
}
body.zen #bar { display: none; }
.logo { font-weight: 600; margin-right: auto; display: inline-flex; align-items: center; gap: 0.4em; white-space: nowrap; }
.logo { font-weight: 600; display: inline-flex; align-items: center; gap: 0.4em; white-space: nowrap; justify-self: start; }
.logo b { color: var(--accent); font-weight: 700; }
.logo svg { width: 1.3em; height: 1.3em; color: var(--accent); flex: none; }
#stats { color: var(--muted); font-size: 0.8rem; }
#help-btn { width: 2.2em; padding: 0.35em 0; }
#volume { display: flex; align-items: center; gap: 0.3rem; }
#mute-btn { width: 2.2em; padding: 0.35em 0; display: grid; place-items: center; }
#mute-btn svg { width: 1.1em; height: 1.1em; }
#volume-slider { width: 5.5rem; accent-color: var(--accent); cursor: pointer; }
#account-btn { max-width: 14rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar-end { justify-self: end; display: flex; align-items: center; gap: 0.4rem; }
/* Feed modes as segmented tabs, the middle of the bar. */
#mode-tabs {
display: flex;
gap: 0.2rem;
padding: 0.2rem;
border-radius: 999px;
background: var(--glass);
backdrop-filter: blur(12px);
}
#mode-tabs button {
border: none;
background: none;
padding: 0.35em 0.95em;
font-size: 0.85rem;
color: var(--muted);
white-space: nowrap;
transition: background var(--fast), color var(--fast);
}
#mode-tabs button:hover { color: var(--fg); }
#mode-tabs button[aria-pressed="true"] { background: var(--fg); color: #000; font-weight: 600; }
.icon-btn {
width: 2.3rem;
height: 2.3rem;
padding: 0;
display: grid;
place-items: center;
border: none;
background: var(--glass);
transition: background var(--fast);
}
.icon-btn:hover, .icon-btn[aria-expanded="true"] { background: var(--glass-strong); }
.icon-btn svg { width: 1.1rem; height: 1.1rem; }
#filters-btn { position: relative; }
#filters-btn.active::after {
content: "";
display: inline-block;
width: 0.45em;
height: 0.45em;
margin-left: 0.4em;
position: absolute;
top: 0.35rem;
right: 0.35rem;
width: 0.45rem;
height: 0.45rem;
border-radius: 50%;
background: var(--accent);
vertical-align: middle;
}
#bar button[aria-expanded="true"] { background: rgba(255, 255, 255, 0.22); }
.avatar-btn {
width: 2.3rem;
height: 2.3rem;
padding: 0;
border: 2px solid #fff3;
font-weight: 700;
color: #000;
}
#volume { display: flex; align-items: center; gap: 0.3rem; margin-right: 0.3rem; }
#volume-slider { width: 5.5rem; accent-color: var(--accent); cursor: pointer; }
#mode-chip {
max-width: 14rem;
max-width: 16rem;
display: inline-flex;
align-items: center;
gap: 0.45em;
padding-left: 0.3em;
white-space: nowrap;
border: none;
background: color-mix(in oklab, var(--accent) 40%, transparent);
}
#mode-chip .chip-label { overflow: hidden; text-overflow: ellipsis; }
@@ -112,71 +153,202 @@ button {
font-size: 0.8em;
background: #0006 center / cover no-repeat;
}
.chip-avatar svg { width: 0.9em; height: 0.9em; color: var(--accent); }
.panel {
/* Sheets (sheet.ts): a drawer on the right, a bottom sheet on phones. ------- */
.scrim {
position: fixed;
z-index: 11;
top: calc(3rem + env(safe-area-inset-top));
right: 1rem;
inset: 0;
z-index: 24;
background: #0008;
backdrop-filter: blur(2px);
animation: fade 0.2s ease;
}
.sheet {
position: fixed;
z-index: 25;
top: 0;
right: 0;
bottom: 0;
width: min(26rem, 100vw);
overflow-y: auto;
overscroll-behavior: contain;
padding: 1.2rem 1.3rem;
padding-top: max(1.2rem, env(safe-area-inset-top));
background: var(--panel);
border: 1px solid var(--line-strong);
border-radius: var(--radius-m);
padding: 0.8rem 1rem;
border-left: 1px solid var(--line-strong);
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
gap: 0.9rem;
animation: drawer 0.3s var(--ease-out);
}
.sheet:focus-visible { outline: none; }
@keyframes drawer { from { transform: translateX(100%); } }
.sheet-handle { display: none; }
.sheet h2 { margin: 0; font: 800 1.25rem/1.2 var(--font-display); }
.sheet fieldset { margin: 0; padding: 0; border: 0; display: flex; flex-direction: column; gap: 0.6rem; }
.sheet legend, .sheet h3 {
padding: 0;
margin-bottom: 0.4rem;
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--muted);
}
#sleep-left { text-transform: none; letter-spacing: 0; color: var(--accent); }
.sheet-actions { display: flex; align-items: center; gap: 1rem; }
.sheet-tools { display: flex; align-items: center; gap: 0.6rem; flex-wrap: wrap; }
.sheet-tools input[type=search] {
flex: 1 1 10rem;
min-width: 0;
padding: 0.55em 0.9em;
border-radius: 999px;
border: 1px solid var(--line-strong);
background: #111;
}
#filters { display: flex; gap: 0.8rem; align-items: center; flex-wrap: wrap; max-width: 24rem; }
.modes { display: flex; gap: 0.4rem; flex-wrap: wrap; flex-basis: 100%; margin: 0; padding: 0; border: 0; }
.modes legend { color: var(--muted); font-size: 0.8rem; padding: 0; margin-bottom: 0.3rem; }
.modes { flex-direction: row !important; flex-wrap: wrap; gap: 0.4rem !important; }
.modes legend { flex-basis: 100%; }
.modes label { cursor: pointer; }
.modes input { position: absolute; opacity: 0; }
.modes input { position: absolute; opacity: 0; pointer-events: none; }
.modes label:has(input) {
padding: 0.25em 0.8em;
padding: 0.3em 0.9em;
border-radius: 999px;
border: 1px solid #ffffff40;
font-size: 0.85rem;
transition: background var(--fast);
}
.modes label:has(input:checked) { background: var(--accent); border-color: transparent; color: #000; }
.modes label:has(input:checked) { background: var(--accent); border-color: transparent; color: #000; font-weight: 600; }
.modes label:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
#filters input[type=number] {
width: 4.5em;
background: #222;
border: 1px solid #444;
border-radius: 6px;
padding: 0.2em 0.4em;
}
#likes { width: min(26rem, calc(100vw - 2rem)); max-height: 70vh; overflow: auto; }
#likes h2 { margin: 0 0 0.5rem; font-size: 1rem; }
#likes ol { margin: 0; padding: 0; list-style: none; }
#likes li {
/* A checkbox drawn as a switch. */
.switch { display: flex; align-items: center; gap: 0.7rem; cursor: pointer; }
.switch input {
appearance: none;
flex: none;
width: 2.6rem;
height: 1.5rem;
margin: 0;
border-radius: 999px;
background: #ffffff26;
position: relative;
cursor: pointer;
transition: background var(--fast);
}
.switch input::after {
content: "";
position: absolute;
top: 0.2rem;
left: 0.2rem;
width: 1.1rem;
height: 1.1rem;
border-radius: 50%;
background: #fff;
transition: transform 0.2s var(--ease-out);
}
.switch input:checked { background: var(--accent); }
.switch input:checked::after { transform: translateX(1.1rem); }
.switch.small input { transform: scale(0.85); }
/* The BPM range: two sliders on one track; --lo and --hi come from main.ts. */
.bpm-head { display: flex; justify-content: space-between; font-size: 0.9rem; }
.bpm-head output { color: var(--accent); font-weight: 600; }
.range2 {
--lo: 0%;
--hi: 100%;
position: relative;
height: 1.6rem;
margin: 0.2rem 0;
}
.range2::before {
content: "";
position: absolute;
inset: 50% 0 auto;
height: 4px;
margin-top: -2px;
border-radius: 2px;
background: linear-gradient(90deg, #ffffff26 var(--lo), var(--accent) var(--lo) var(--hi), #ffffff26 var(--hi));
}
.range2 input {
position: absolute;
inset: 0;
width: 100%;
margin: 0;
appearance: none;
background: none;
pointer-events: none;
}
.range2 input::-webkit-slider-thumb {
appearance: none;
width: 1.2rem;
height: 1.2rem;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 0 4px color-mix(in oklab, var(--accent) 45%, transparent);
pointer-events: auto;
cursor: grab;
}
.range2 input::-moz-range-thumb {
width: 1.2rem;
height: 1.2rem;
border: none;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 0 4px color-mix(in oklab, var(--accent) 45%, transparent);
pointer-events: auto;
cursor: grab;
}
.presets { display: flex; gap: 0.4rem; }
.presets button { font-size: 0.8rem; padding: 0.25em 0.8em; }
.presets button[aria-pressed="true"] { background: var(--accent); border-color: transparent; color: #fff; }
/* Likes and history: artwork that plays, title, artist. */
.track-list { margin: 0; padding: 0; list-style: none; color: var(--muted); }
.track-row {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.35rem 0;
gap: 0.75rem;
padding: 0.45rem 0;
border-bottom: 1px solid #ffffff10;
animation: fade 0.3s ease;
}
#likes li:last-child { border-bottom: none; }
#likes li .meta { min-width: 0; flex: 1; }
#likes li .meta a { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-decoration: none; }
#likes li .meta a:hover { text-decoration: underline; }
#likes li .meta span { color: var(--muted); font-size: 0.8rem; }
#likes li .play-now {
.track-row:last-child { border-bottom: none; }
.track-row .meta { min-width: 0; flex: 1; }
.track-row .meta a { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-decoration: none; color: var(--fg); }
.track-row .meta a:hover { text-decoration: underline; }
.track-row .meta span { font-size: 0.8rem; }
.row-play {
flex: none;
width: 2rem;
height: 2rem;
position: relative;
width: 2.8rem;
height: 2.8rem;
padding: 0;
border: none;
border-radius: var(--radius-s);
background: #222 center / cover no-repeat;
display: grid;
place-items: center;
overflow: hidden;
}
#likes li .play-now svg { width: 0.9rem; height: 0.9rem; }
.row-play::before { content: ""; position: absolute; inset: 0; background: #0006; opacity: 0; transition: opacity var(--fast); }
.row-play svg { position: relative; width: 1rem; height: 1rem; opacity: 0; transition: opacity var(--fast); }
.row-play:hover::before, .row-play:focus-visible::before, .row-play:hover svg, .row-play:focus-visible svg { opacity: 1; }
@media not ((hover: hover) and (pointer: fine)) {
.row-play::before { opacity: 0.6; }
.row-play svg { opacity: 1; }
}
.row-unlike { flex: none; color: var(--accent); background: none; }
.row-unlike:hover { background: var(--glass); }
#account { width: min(20rem, calc(100vw - 2rem)); display: flex; flex-direction: column; align-items: flex-start; gap: 0.7rem; }
#account h2 { margin: 0; font-size: 1rem; }
#account { align-items: flex-start; }
#stats { margin: -0.5rem 0 0; color: var(--muted); font-size: 0.8rem; }
#account a { font-size: 0.85rem; color: var(--muted); }
#sync { width: 100%; display: flex; flex-direction: column; align-items: flex-start; gap: 0.5rem;
padding-bottom: 0.7rem; border-bottom: 1px solid #ffffff14; }
#sync h3 { margin: 0; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); }
padding-bottom: 0.9rem; border-bottom: 1px solid #ffffff14; }
#sync h3 { margin: 0; }
#sync-status { margin: 0; font-size: 0.85rem; color: var(--muted); }
#sync-status.on::before { content: "● "; color: #3ddc84; }
#delete-form { display: flex; flex-direction: column; gap: 0.5rem; width: 100%; }
@@ -361,17 +533,35 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
color: color-mix(in oklab, var(--card-accent) 70%, #fff);
}
.why:empty { display: none; }
.byline { display: flex; align-items: center; gap: 0.6rem; }
.artist { color: var(--muted); text-decoration: none; }
.artist:hover { text-decoration: underline; }
.follow, .radio {
.byline { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; justify-content: center; }
.artist-avatar {
flex: none;
width: 1.6rem;
height: 1.6rem;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 0.75rem;
padding: 0.15em 0.75em;
font-weight: 700;
background: var(--card-accent) center / cover no-repeat;
box-shadow: 0 0 0 2px #0008;
}
.artist { color: var(--fg); font-weight: 600; text-decoration: none; }
.artist:hover { text-decoration: underline; }
.pill {
display: inline-flex;
align-items: center;
gap: 0.3em;
font-size: 0.75rem;
padding: 0.2em 0.75em 0.2em 0.55em;
border-radius: 999px;
border: 1px solid #ffffff40;
background: transparent;
transition: background var(--fast), border-color var(--fast);
}
.follow.on { background: #ffffff1f; border-color: transparent; color: var(--muted); }
.pill svg { width: 0.95em; height: 0.95em; }
.pill:hover { background: var(--glass); }
.follow.on { background: color-mix(in oklab, var(--card-accent) 25%, transparent); border-color: transparent; }
.chips { display: flex; gap: 0.4rem; flex-wrap: wrap; justify-content: center; }
.chips span {
@@ -381,6 +571,7 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
background: rgba(255, 255, 255, 0.12);
}
.chips .free { background: #1f7a4d; }
.chips .new { background: var(--fg); color: #000; font-weight: 700; }
.chips span:first-child { background: color-mix(in oklab, var(--card-accent) 35%, transparent); }
.chips .preview { background: #6a4b16; }
.chips .tag { background: transparent; box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--card-accent) 60%, transparent); }
@@ -412,34 +603,49 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
transition: opacity 0.1s;
}
.wave-wrap.hover .wave-tip { opacity: 1; }
.time { width: 100%; display: flex; justify-content: space-between; color: var(--muted); font-size: 0.75rem; }
.counts { color: var(--muted); font-size: 0.8rem; }
.time { width: 100%; display: flex; justify-content: space-between; gap: 1rem; color: var(--muted); font-size: 0.75rem; font-variant-numeric: tabular-nums; }
.counts { opacity: 0.8; }
.actions {
position: absolute;
right: 0.8rem;
bottom: 18vh;
bottom: 16vh;
display: flex;
flex-direction: column;
gap: 0.9rem;
gap: 0.7rem;
}
.actions > * {
/* A round button with a small count or label under it. */
.act {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.2rem;
padding: 0;
border: none;
background: none;
border-radius: 0;
text-decoration: none;
font-size: 0.7rem;
color: var(--fg);
}
.act .ring {
width: 3rem;
height: 3rem;
display: grid;
place-items: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.12);
border: none;
text-decoration: none;
padding: 0;
transition: background 0.15s, transform 0.15s;
backdrop-filter: blur(8px);
transition: background var(--fast), transform var(--fast);
}
.actions > *:hover { background: rgba(255, 255, 255, 0.2); }
.actions > *:active { transform: scale(0.9); }
.actions svg { width: 1.3rem; height: 1.3rem; }
.actions .like.on { color: var(--card-accent); background: color-mix(in oklab, var(--card-accent) 22%, transparent); }
.actions .like.pop svg { animation: pop 0.35s ease; }
.act:hover .ring { background: rgba(255, 255, 255, 0.2); }
.act:active .ring { transform: scale(0.9); }
.act .n { text-shadow: 0 1px 4px #000; min-height: 1em; }
.act svg { width: 1.3rem; height: 1.3rem; }
.act.like.on .ring { color: var(--card-accent); background: color-mix(in oklab, var(--card-accent) 22%, transparent); }
.act.like.pop svg { animation: pop 0.35s ease; }
.act.like.pop .ring { animation: ring-out 0.5s ease-out; }
@keyframes ring-out { from { box-shadow: 0 0 0 0 color-mix(in oklab, var(--card-accent) 70%, transparent); } to { box-shadow: 0 0 0 1rem transparent; } }
@keyframes pop { 50% { transform: scale(1.4); } }
/* Feedback overlays ------------------------------------------------------ */
@@ -487,7 +693,8 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
position: fixed;
z-index: 40;
left: 50%;
bottom: max(2rem, env(safe-area-inset-bottom));
/* Above the up-next pill. */
bottom: calc(max(1rem, env(safe-area-inset-bottom)) + 3.4rem);
transform: translate(-50%, 1rem);
padding: 0.6em 1.1em;
border-radius: 999px;
@@ -502,6 +709,47 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
text-align: center;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }
#toast.has-action { pointer-events: auto; display: flex; align-items: center; gap: 0.8rem; }
#toast button { border: none; padding: 0.2em 0.7em; background: var(--fg); color: #000; font-weight: 700; font-size: 0.8rem; }
#toast:not(.show) button { pointer-events: none; }
/* What plays next, at the bottom; a tap skips to it. */
#up-next {
position: fixed;
z-index: 6;
left: 50%;
bottom: max(1rem, env(safe-area-inset-bottom));
transform: translateX(-50%);
max-width: min(24rem, calc(100vw - 2rem));
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.3rem 0.9rem 0.3rem 0.3rem;
border: none;
background: #0008;
backdrop-filter: blur(12px);
text-align: left;
animation: rise 0.35s var(--ease-out);
opacity: 0.85;
transition: opacity var(--fast);
}
#up-next:hover { opacity: 1; }
.up-next-avatar {
flex: none;
width: 2rem;
height: 2rem;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 0.8rem;
font-weight: 700;
background: #222 center / cover no-repeat;
}
.up-next-text { min-width: 0; display: flex; flex-direction: column; line-height: 1.2; }
.up-next-text small { font-size: 0.65rem; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); }
.up-next-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.85rem; }
#up-next > svg { flex: none; width: 1rem; height: 1rem; color: var(--muted); }
body.zen #up-next { display: none; }
#feed-status {
position: fixed;
@@ -529,7 +777,22 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
background: var(--scrim);
cursor: pointer;
}
#start button { font-size: 1.3rem; padding: 0.7em 1.6em; background: var(--accent); border: none; color: #fff; }
.start-play {
width: 6rem;
height: 6rem;
padding: 0;
display: grid;
place-items: center;
border: none;
background: var(--accent);
color: #000;
box-shadow: 0 0 0 0 color-mix(in oklab, var(--accent) 60%, transparent);
animation: beckon 1.8s ease-out infinite;
}
.start-play svg { width: 2.6rem; height: 2.6rem; margin-left: 0.3rem; }
@keyframes beckon { to { box-shadow: 0 0 0 2rem transparent; } }
.start-track { margin: 0.4rem 0 0; font-weight: 700; font-size: 1.1rem; text-align: center; padding: 0 1rem; }
.start-hint { margin: 0; color: var(--muted); font-size: 0.85rem; }
/* Radio sheet: a bottom sheet on phones, a centred box elsewhere. */
#station {
@@ -621,6 +884,7 @@ button.primary {
gap: 0.4em;
}
button.primary svg { width: 1em; height: 1em; }
button.primary:disabled { opacity: 0.35; cursor: default; }
/* The end of an artist radio, over its last card. */
#radio-end {
@@ -643,25 +907,8 @@ button.primary svg { width: 1em; height: 1em; }
}
#radio-end p { flex-basis: 100%; margin: 0 0 0.3rem; color: var(--muted); font-size: 0.9rem; }
#help {
position: fixed;
inset: 0;
z-index: 25;
display: grid;
place-items: center;
padding: 1rem;
background: var(--scrim);
animation: fade 0.2s ease;
}
@keyframes fade { from { opacity: 0; } }
.help-box {
width: min(22rem, 100%);
background: var(--panel);
border: 1px solid var(--line-strong);
border-radius: var(--radius-l);
padding: 1.2rem 1.4rem;
}
.help-box h2 { margin: 0 0 0.8rem; font-size: 1.1rem; }
.help-box h2 { margin: 0 0 0.8rem; }
.help-box dl { display: grid; grid-template-columns: auto 1fr; gap: 0.45rem 1rem; margin: 0; }
.help-box dt { font-family: ui-monospace, monospace; font-size: 0.85rem; color: var(--accent); }
.help-box dd { margin: 0; }
@@ -720,30 +967,58 @@ button.primary svg { width: 1em; height: 1em; }
/* Phones ----------------------------------------------------------------- */
@media (max-width: 640px) {
#stats { display: none; }
#bar { gap: 0.4rem; padding-left: 0.7rem; padding-right: 0.7rem; }
#bar button { padding: 0.3em 0.7em; font-size: 0.85rem; }
#help-btn { display: none; }
/* Logo and buttons on one row, the feed tabs on their own below. */
#bar { grid-template-columns: 1fr auto; gap: 0.5rem 0.4rem; padding-left: 0.7rem; padding-right: 0.7rem; }
#mode-tabs, #mode-chip { grid-column: 1 / -1; grid-row: 2; justify-self: center; max-width: 100%; overflow-x: auto; scrollbar-width: none; }
/* Phones have volume buttons; the bar has no room. */
#volume { display: none; }
#account-btn { max-width: 6.5rem; }
.panel { left: 0.7rem; right: 0.7rem; }
.logo-pl8 { display: none; }
#station { place-items: end stretch; padding: 0; }
.station-box { width: 100%; border-radius: var(--radius-l) var(--radius-l) 0 0; padding-bottom: max(1.4rem, env(safe-area-inset-bottom)); }
#mode-chip { max-width: 9rem; }
.logo-pl8 { display: none; }
/* A station chip says more than the logo; there is no room for both. */
#bar:has(#mode-chip:not([hidden])) .logo { display: none; }
#likes { width: auto; }
.content { width: calc(100vw - 2rem); margin-bottom: 4.5rem; }
.sheet {
top: auto;
left: 0;
width: 100%;
max-height: 85dvh;
border-left: none;
border-top: 1px solid var(--line-strong);
border-radius: var(--radius-l) var(--radius-l) 0 0;
padding-top: 0.4rem;
padding-bottom: max(1.2rem, env(safe-area-inset-bottom));
animation-name: sheet-up;
transition: transform 0.25s var(--ease-out);
}
.sheet.dragging { transition: none; }
@keyframes sheet-up { from { transform: translateY(100%); } }
.sheet-handle {
display: block;
flex: none;
align-self: stretch;
height: 1.6rem;
margin: 0 -1.3rem -0.4rem;
touch-action: none;
cursor: grab;
}
.sheet-handle::before {
content: "";
display: block;
width: 2.6rem;
height: 0.3rem;
margin: 0.55rem auto 0;
border-radius: 999px;
background: #fff5;
}
.content { width: calc(100vw - 2rem); margin-bottom: 5.5rem; }
.actions {
right: auto;
left: 50%;
bottom: max(1.2rem, env(safe-area-inset-bottom));
bottom: max(0.8rem, env(safe-area-inset-bottom));
transform: translateX(-50%);
flex-direction: row;
gap: 0.9rem;
gap: 0.7rem;
}
#up-next { bottom: calc(max(0.8rem, env(safe-area-inset-bottom)) + 4.6rem); }
#toast { bottom: calc(max(0.8rem, env(safe-area-inset-bottom)) + 8rem); }
}
/* Zen: nothing but the drop, bigger, and the music. */
+16 -1
View File
@@ -82,6 +82,12 @@ export class Visualizer {
return this.blob?.lost ? null : this.blob;
}
/// Spin the drop backwards, hard: the rewind.
wheelUp(): void {
this.blob?.spin.fling([0, -26, 0]);
this.start();
}
/// A play/pause from a tap was taken back by the second tap of a double-tap.
cancelFlash(): void {
this.blob?.settleIcon();
@@ -227,7 +233,7 @@ export class Visualizer {
if (!card) return;
const a = this.player.audio;
const progress = a.duration ? a.currentTime / a.duration : 0;
card.drawWave(progress);
card.drawWave(progress, false, a.duration ? bufferedTo(a) / a.duration : 0);
const playing = !a.paused;
const an = this.player.analyser;
const mixed = !!an && this.player.mixing;
@@ -260,3 +266,12 @@ export class Visualizer {
}
};
}
/// How far the audio is loaded from where it plays now, in seconds.
function bufferedTo(a: HTMLMediaElement): number {
const b = a.buffered;
for (let i = 0; i < b.length; i++) {
if (b.start(i) <= a.currentTime + 0.5 && b.end(i) >= a.currentTime) return b.end(i);
}
return a.currentTime;
}