Timed comments on the waveform

Each comment sits as a dot under the moment it was left at. When the music
gets there the dot pings and a bubble grows out of it on a spark, then drifts
up and fades; a mouse over a dot peeks at it. The server fetches the newest
60 comments from pl8list on demand and keeps them for 15 minutes. A setting
turns them off.
This commit is contained in:
nvrl committed 2026-11-02 23:18:44 +01:00
1 parent b290cd49e3
commit b42780d24b
12 files changed
+579 -2

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
//! Timed comments of a track, for the waveform. pl8list pins every comment to a
//! moment of the track (`timestampSeconds`) and serves them newest first, 20 to a
//! page. We fetch a few pages on demand and keep them in memory for a while, so a
//! track that comes round again costs pl8list nothing.
use std::{
collections::HashMap,
sync::{Arc, Mutex},
time::Duration,
};
use serde::Serialize;
use serde_json::Value;
use tokio::time::Instant;
use crate::pl8::Pl8;
/// Pages fetched per track: the newest 60 comments.
const PAGES: i64 = 3;
const TTL: Duration = Duration::from_secs(15 * 60);
/// Tracks kept; the oldest entry goes when a new one comes in.
const KEEP: usize = 512;
/// Longest comment body shown, in characters.
const MAX_BODY: usize = 200;
#[derive(Clone, Serialize, Debug, PartialEq)]
pub struct Comment {
pub id: i64,
/// Seconds into the track.
pub at: f64,
pub body: String,
pub handle: String,
pub name: String,
pub img: Option<String>,
pub verified: bool,
}
/// When a track's comments were fetched, and the comments.
type Entry = (Instant, Arc<Vec<Comment>>);
#[derive(Default)]
pub struct Comments {
map: Mutex<HashMap<i64, Entry>>,
}
impl Comments {
pub fn cached(&self, track_id: i64) -> Option<Arc<Vec<Comment>>> {
let map = self.map.lock().unwrap();
map.get(&track_id).filter(|(at, _)| at.elapsed() < TTL).map(|(_, c)| c.clone())
}
/// Fetch the comments from pl8list and keep them. A failed page ends the
/// fetch with what came before it; a failed first page is an error.
pub async fn fetch(&self, pl8: &Pl8, track_id: i64, handle: &str, slug: &str) -> anyhow::Result<Arc<Vec<Comment>>> {
let mut out = vec![];
for page in 1..=PAGES {
let res = pl8.comments(handle, slug, page).await;
let data = match res {
Ok(Some(d)) => d,
Ok(None) => break,
Err(e) if page == 1 => return Err(e),
Err(_) => break,
};
out.extend(parse(&data));
let total = data.get("totalPages").and_then(Value::as_i64).unwrap_or(1);
if page >= total {
break;
}
}
out.sort_by(|a, b| a.at.total_cmp(&b.at));
let out = Arc::new(out);
let mut map = self.map.lock().unwrap();
if map.len() >= KEEP && !map.contains_key(&track_id) {
map.retain(|_, (at, _)| at.elapsed() < TTL);
if map.len() >= KEEP
&& let Some(oldest) = map.iter().min_by_key(|(_, (at, _))| *at).map(|(k, _)| *k)
{
map.remove(&oldest);
}
}
map.insert(track_id, (Instant::now(), out.clone()));
Ok(out)
}
}
/// Comments from one page of `/api/{handle}/{slug}/comments`. Deleted, hidden,
/// untimed and empty ones are left out.
pub fn parse(data: &Value) -> Vec<Comment> {
let Some(list) = data.get("comments").and_then(Value::as_array) else { return vec![] };
list.iter()
.filter_map(|c| {
let flag = |k: &str| c.get(k).and_then(Value::as_bool).unwrap_or(false);
if flag("isDeleted") || flag("isHiddenByOwner") {
return None;
}
let at = c.get("timestampSeconds")?.as_f64().filter(|t| t.is_finite() && *t >= 0.0)?;
let body = clean(c.get("body")?.as_str()?);
if body.is_empty() {
return None;
}
let user = c.get("user")?;
let handle = user.get("handle")?.as_str()?.to_string();
let name = user.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).unwrap_or(&handle).trim().to_string();
Some(Comment {
id: c.get("id")?.as_i64()?,
at,
body,
name,
img: user.get("img").and_then(Value::as_str).filter(|s| !s.is_empty()).map(String::from),
verified: user.get("isVerified").and_then(Value::as_bool).unwrap_or(false),
handle,
})
})
.collect()
}
/// One line, at most `MAX_BODY` characters.
fn clean(body: &str) -> String {
let one_line = body.split_whitespace().collect::<Vec<_>>().join(" ");
match one_line.char_indices().nth(MAX_BODY) {
Some((cut, _)) => format!("{}…", one_line[..cut].trim_end()),
None => one_line,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn parse_keeps_timed_visible_comments() {
let d = json!({"comments": [
{"id": 1, "body": " gass\n\nat 145 ", "timestampSeconds": 37.5, "isDeleted": false,
"user": {"handle": "a", "name": "", "img": "x-1", "isVerified": true}},
{"id": 2, "body": "gone", "timestampSeconds": 3.0, "isDeleted": true, "user": {"handle": "b"}},
{"id": 3, "body": "hidden", "timestampSeconds": 3.0, "isHiddenByOwner": true, "user": {"handle": "b"}},
{"id": 4, "body": "untimed", "timestampSeconds": null, "user": {"handle": "b"}},
{"id": 5, "body": " ", "timestampSeconds": 1.0, "user": {"handle": "b"}},
]});
let c = parse(&d);
assert_eq!(c.len(), 1);
assert_eq!((c[0].id, c[0].at, c[0].body.as_str()), (1, 37.5, "gass at 145"));
assert_eq!((c[0].name.as_str(), c[0].img.as_deref(), c[0].verified), ("a", Some("x-1"), true));
}
#[test]
fn long_bodies_are_cut() {
let long = "ä".repeat(MAX_BODY + 10);
let cut = clean(&long);
assert_eq!(cut.chars().count(), MAX_BODY + 1);
assert!(cut.ends_with('…'));
}
}
+32
View File
@@ -183,6 +183,38 @@ pub async fn track(State(app): St, Extension(current): Extension<CurrentUser>, Q
Ok((no_store(), Json(json!({ "track": track }))).into_response()) Ok((no_store(), Json(json!({ "track": track }))).into_response())
} }
/// The timed comments of a catalogue track (`?id=`), oldest moment first.
pub async fn comments(State(app): St, Extension(current): Extension<CurrentUser>, Query(q): Query<HashMap<String, String>>) -> Res {
let uid = match reader(&app, &current) {
Ok(u) => u.id,
Err(r) => return Ok(r),
};
let Some(id) = q.get("id").and_then(|v| v.parse::<i64>().ok()) else {
return Ok(StatusCode::BAD_REQUEST.into_response());
};
// Kept a minute in the browser too: scrolling back to a track asks again.
let ok = |c: &[crate::comments::Comment]| {
([(axum::http::header::CACHE_CONTROL, "private, max-age=60")], Json(json!({ "comments": c }))).into_response()
};
if let Some(c) = app.comments.cached(id) {
return Ok(ok(&c));
}
// Only tracks in the catalogue: anything else would have us ask pl8list for nothing.
let Some((handle, slug)) = app.db.read(move |c| db::track_path(c, id)).await? else {
return Ok(StatusCode::NOT_FOUND.into_response());
};
if !app.limits.comments.allow(&uid.to_string()) {
return Ok(json_error(StatusCode::TOO_MANY_REQUESTS, "slow down a little"));
}
match app.comments.fetch(&app.pl8, id, &handle, &slug).await {
Ok(c) => Ok(ok(&c)),
Err(e) => {
tracing::warn!("comments of {handle}/{slug}: {e:#}");
Ok(StatusCode::BAD_GATEWAY.into_response())
}
}
}
/// How many neighbours the radio sheet shows, and how few count as still exploring. /// How many neighbours the radio sheet shows, and how few count as still exploring.
const SHEET_NEIGHBOURS: usize = 12; const SHEET_NEIGHBOURS: usize = 12;
const FEW_NEIGHBOURS: usize = 3; const FEW_NEIGHBOURS: usize = 3;
+8 -1
View File
@@ -28,6 +28,7 @@ use secrecy::SecretString;
use crate::{ use crate::{
cache::Cache, cache::Cache,
comments::Comments,
config::Config, config::Config,
crawler::Crawler, crawler::Crawler,
db::{self, Db, User}, db::{self, Db, User},
@@ -61,6 +62,8 @@ pub struct Limits {
pub resync: RateLimiter, pub resync: RateLimiter,
/// Guests made per IP: each is a row in the database. /// Guests made per IP: each is a row in the database.
pub guests: RateLimiter, pub guests: RateLimiter,
/// Comment fetches from pl8list, per user: only misses of the comment cache count.
pub comments: RateLimiter,
} }
pub struct App { pub struct App {
@@ -75,6 +78,7 @@ pub struct App {
pub cookies: Cookies, pub cookies: Cookies,
pub segments: proxy::SegmentKeys, pub segments: proxy::SegmentKeys,
pub legal: legal::Pages, pub legal: legal::Pages,
pub comments: Comments,
} }
pub type St = State<Arc<App>>; pub type St = State<Arc<App>>;
@@ -97,7 +101,9 @@ impl App {
pl8_writes: RateLimiter::new(60, 600), pl8_writes: RateLimiter::new(60, 600),
resync: RateLimiter::new(1, 120), resync: RateLimiter::new(1, 120),
guests: RateLimiter::new(10, 3600), guests: RateLimiter::new(10, 3600),
comments: RateLimiter::new(30, 300),
}, },
comments: Comments::default(),
logins: auth::PendingLogins::default(), logins: auth::PendingLogins::default(),
segments: proxy::SegmentKeys::default(), segments: proxy::SegmentKeys::default(),
sync, sync,
@@ -119,7 +125,7 @@ impl App {
} }
self.logins.prune(); self.logins.prune();
self.segments.prune(); self.segments.prune();
for l in [&self.limits.guests, &self.limits.reads, &self.limits.proxy, &self.limits.proxy_ip, &self.limits.events] { for l in [&self.limits.guests, &self.limits.reads, &self.limits.proxy, &self.limits.proxy_ip, &self.limits.events, &self.limits.comments] {
l.prune(); l.prune();
} }
} }
@@ -349,6 +355,7 @@ pub fn router(app: Arc<App>) -> Router {
.route("/local/likes", get(app::likes)) .route("/local/likes", get(app::likes))
.route("/local/track", get(app::track)) .route("/local/track", get(app::track))
.route("/local/artist", get(app::artist)) .route("/local/artist", get(app::artist))
.route("/local/comments", get(app::comments))
.route("/local/event", post(app::event)) .route("/local/event", post(app::event))
.route("/local/follow", post(app::follow)) .route("/local/follow", post(app::follow))
.route("/account/export", get(account::export)) .route("/account/export", get(account::export))
+30
View File
@@ -619,3 +619,33 @@ async fn radio_of_an_unknown_artist_is_not_found() {
let res = r.clone().oneshot(req("GET", "/local/artist?handle=made-up-handle", None, Some(&guest), "203.0.113.23")).await.unwrap(); let res = r.clone().oneshot(req("GET", "/local/artist?handle=made-up-handle", None, Some(&guest), "203.0.113.23")).await.unwrap();
assert_eq!(res.status(), StatusCode::NOT_FOUND); assert_eq!(res.status(), StatusCode::NOT_FOUND);
} }
#[tokio::test]
async fn comments_come_sorted_by_moment_and_cached() {
let pl8 = MockServer::start().await;
let page = |n: i64, at: f64| {
serde_json::json!({ "totalPages": 2, "comments": [
{ "id": n, "body": format!("c{n}"), "timestampSeconds": at, "user": { "handle": "h", "name": "H" } }
]})
};
for (n, at) in [(1, 30.0), (2, 10.0)] {
Mock::given(method("GET")).and(path("/api/a/track-1/comments")).and(query_param("page", n.to_string()))
.respond_with(ResponseTemplate::new(200).set_body_json(page(n, at)))
.expect(1)
.mount(&pl8).await;
}
let (r, app, _) = setup("comments", &pl8.uri()).await;
known_track(&app, 1, "a").await;
let token = app.db.call(|c| { crate::db::upsert_user(c, 5, "tester", None, None)?; crate::db::create_session(c, 5) }).await.unwrap();
let cookie = format!("__Host-pl8inf={token}");
let get = |uri: &str| r.clone().oneshot(req("GET", uri, None, Some(&cookie), "203.0.113.1"));
for _ in 0..2 {
let res = get("/local/comments?id=1").await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let body = json_body(res).await;
let ids: Vec<i64> = body["comments"].as_array().unwrap().iter().map(|c| c["id"].as_i64().unwrap()).collect();
assert_eq!(ids, [2, 1]);
}
assert_eq!(get("/local/comments?id=99").await.unwrap().status(), StatusCode::NOT_FOUND);
assert_eq!(get("/local/comments?id=x").await.unwrap().status(), StatusCode::BAD_REQUEST);
}
+1
View File
@@ -14,6 +14,7 @@
#![allow(clippy::result_large_err)] // handlers return axum `Response` as their error #![allow(clippy::result_large_err)] // handlers return axum `Response` as their error
mod cache; mod cache;
mod comments;
mod config; mod config;
mod crawler; mod crawler;
mod db; mod db;
+5
View File
@@ -156,6 +156,11 @@ impl Pl8 {
self.get_json(&[handle, slug, "related"], &[], Some("routes/$handle_.$slug.related"), None).await self.get_json(&[handle, slug, "related"], &[], Some("routes/$handle_.$slug.related"), None).await
} }
/// One page of a track's comments, newest first (`comments`, `totalPages`).
pub async fn comments(&self, handle: &str, slug: &str, page: i64) -> anyhow::Result<Option<Value>> {
self.get_json(&["api", handle, slug, "comments"], &[("page", page.to_string())], None, None).await
}
pub async fn best_selling_artists(&self) -> anyhow::Result<Option<Value>> { pub async fn best_selling_artists(&self) -> anyhow::Result<Option<Value>> {
self.get_json(&["best-selling-artists"], &[], Some("routes/best-selling-artists"), None).await self.get_json(&["best-selling-artists"], &[], Some("routes/best-selling-artists"), None).await
} }
+1
View File
@@ -144,6 +144,7 @@
<label><input type="radio" name="crossfade" value="8"> dj mix</label> <label><input type="radio" name="crossfade" value="8"> dj mix</label>
</fieldset> </fieldset>
<label class="switch"><input type="checkbox" name="bass"> <span>bass boost</span></label> <label class="switch"><input type="checkbox" name="bass"> <span>bass boost</span></label>
<label class="switch"><input type="checkbox" name="comments"> <span>comments on the waveform</span></label>
<fieldset class="modes"> <fieldset class="modes">
<legend>sleep timer <span id="sleep-left"></span></legend> <legend>sleep timer <span id="sleep-left"></span></legend>
<label><input type="radio" name="sleep" value="off"> off</label> <label><input type="radio" name="sleep" value="off"> off</label>
+14
View File
@@ -130,6 +130,20 @@ export const artist = (handle: string) => getJSON<ArtistInfo>("/local/artist?" +
export const track = (handle: string, slug: string) => export const track = (handle: string, slug: string) =>
getJSON<{ track: Track }>("/local/track?" + new URLSearchParams({ handle, slug })); getJSON<{ track: Track }>("/local/track?" + new URLSearchParams({ handle, slug }));
/// A comment left at a moment of the track (`at`, seconds in).
export interface Comment {
id: number;
at: number;
body: string;
handle: string;
name: string;
img: string | null;
verified: boolean;
}
export const comments = (trackId: number) =>
getJSON<{ comments: Comment[] }>("/local/comments?" + new URLSearchParams({ id: String(trackId) }));
export const likes = () => getJSON<{ tracks: Track[] }>("/local/likes"); export const likes = () => getJSON<{ tracks: Track[] }>("/local/likes");
export const me = () => getJSON<Me>("/local/me"); export const me = () => getJSON<Me>("/local/me");
+30 -1
View File
@@ -1,8 +1,9 @@
// One card per track. Elements are built when a card first comes near the screen // One card per track. Elements are built when a card first comes near the screen
// and dropped again once it is far behind, so a long session stays light. // and dropped again once it is far behind, so a long session stays light.
import { type Track, artistImg, artistUrl, trackUrl } from "./api"; import { type Track, artistImg, artistUrl, comments, trackUrl } from "./api";
import { accentFor, accentForName, backdrop } from "./color"; import { accentFor, accentForName, backdrop } from "./color";
import { WaveComments } from "./comments";
export interface CardActions { export interface CardActions {
like(card: Card): void; like(card: Card): void;
@@ -88,6 +89,27 @@ export class Card {
private station: string | undefined; private station: string | undefined;
/// Drops in the waveform, 0..1 of the track. /// Drops in the waveform, 0..1 of the track.
readonly drops: number[]; readonly drops: number[];
/// Its timed comments, once asked for.
private comments: WaveComments | null = null;
private commentsAsked = false;
/// Fetch the timed comments, once. Previews have none: their moments are those
/// of the full track.
loadComments(): void {
if (this.commentsAsked || this.track.preview || !this.track.comments) return;
this.commentsAsked = true;
comments(this.track.id).then(({ comments: list }) => {
if (!list.length) return;
this.comments = new WaveComments(list, () => this.actions.duration(this));
const wrap = this.canvas?.parentElement;
if (wrap) this.comments.mount(wrap);
}, () => { this.commentsAsked = false; });
}
/// Playback of this card is at `seconds`.
commentsAt(seconds: number): void {
this.comments?.tick(seconds);
}
element(): HTMLElement { element(): HTMLElement {
return this.el ?? this.build(); return this.el ?? this.build();
@@ -96,6 +118,7 @@ export class Card {
/// Forget the element; it is built again if the card comes back. /// Forget the element; it is built again if the card comes back.
release(): void { release(): void {
this.el?.remove(); this.el?.remove();
this.comments?.unmount();
this.el = this.canvas = null; this.el = this.canvas = null;
this.drawn = ""; this.drawn = "";
} }
@@ -176,6 +199,7 @@ export class Card {
this.el = el; this.el = el;
this.canvas = $<HTMLCanvasElement>(".wave"); this.canvas = $<HTMLCanvasElement>(".wave");
this.bindWaveform(); this.bindWaveform();
this.comments?.mount(this.canvas.parentElement!);
this.showLike(); this.showLike();
this.showFollow(); this.showFollow();
requestAnimationFrame(() => this.drawWave(this.lastProgress, true)); requestAnimationFrame(() => this.drawWave(this.lastProgress, true));
@@ -321,7 +345,10 @@ export class Card {
tip.textContent = fmtTime(f * this.actions.duration(this)); tip.textContent = fmtTime(f * this.actions.duration(this));
tip.style.left = `${f * 100}%`; tip.style.left = `${f * 100}%`;
}; };
const peek = (e: PointerEvent | null) =>
this.comments?.peek(e && !this.dragging && e.pointerType === "mouse" ? fraction(e) : null, canvas.clientWidth);
canvas.addEventListener("pointerdown", (e) => { canvas.addEventListener("pointerdown", (e) => {
peek(null);
if (!this.actions.canSeek(this)) return; if (!this.actions.canSeek(this)) return;
e.preventDefault(); e.preventDefault();
canvas.setPointerCapture(e.pointerId); canvas.setPointerCapture(e.pointerId);
@@ -331,6 +358,7 @@ export class Card {
this.drawWave(fraction(e), true); this.drawWave(fraction(e), true);
}); });
canvas.addEventListener("pointermove", (e) => { canvas.addEventListener("pointermove", (e) => {
peek(e);
if (this.dragging) this.drawWave(fraction(e), true); if (this.dragging) this.drawWave(fraction(e), true);
if (this.dragging || e.pointerType === "mouse") { if (this.dragging || e.pointerType === "mouse") {
wrap.classList.add("hover"); wrap.classList.add("hover");
@@ -346,6 +374,7 @@ export class Card {
canvas.addEventListener("pointerup", finish); canvas.addEventListener("pointerup", finish);
canvas.addEventListener("pointercancel", finish); canvas.addEventListener("pointercancel", finish);
canvas.addEventListener("pointerleave", () => { canvas.addEventListener("pointerleave", () => {
peek(null);
if (!this.dragging) wrap.classList.remove("hover"); if (!this.dragging) wrap.classList.remove("hover");
}); });
} }
+159
View File
@@ -0,0 +1,159 @@
// Timed comments on the waveform: a dot under the moment each one was left at,
// and a bubble that grows out of the dot when the music gets there, then drifts
// up and fades. A mouse over the waveform peeks at the comment under it.
import { type Comment, imgUrl } from "./api";
import { accentForName } from "./color";
const LIFE = 4600; // ms a bubble shows; the length of its CSS animation
const GAP = 900; // ms at least between two bubbles; dots in between only ping
const MAX_SHOWN = 2; // bubbles on screen at once, the older pushed up
const STACK = 6; // px between stacked bubbles
const PEEK_PX = 8; // how close the mouse has to be to a dot to peek
const GAP_ABOVE = 8; // px between the waveform and a bubble (.wc-bubble's bottom)
const DOTS_ROW = 0.28; // share of the waveform's height the dots' row takes (.wave-comments)
const SEEK = 1.5; // s; a longer step between two ticks is a seek, which fires nothing
export class WaveComments {
private wrap: HTMLElement | null = null;
private layer: HTMLElement | null = null;
private dots: HTMLElement[] = [];
private shown: HTMLElement[] = [];
private peeked: { el: HTMLElement; id: number } | null = null;
private last = -1;
private lastBubble = 0;
constructor(readonly list: Comment[], private duration: () => number) {}
/// Put the dots under the waveform in `wrap`; they sprout from left to right.
mount(wrap: HTMLElement): void {
this.unmount();
const d = this.duration();
if (!d || !this.list.length) return;
this.wrap = wrap;
const layer = document.createElement("div");
layer.className = "wave-comments";
layer.setAttribute("aria-hidden", "true");
this.dots = this.list.map((c) => {
const dot = document.createElement("i");
dot.className = "wc-dot";
const x = Math.min(1, c.at / d);
dot.style.left = `${x * 100}%`;
dot.style.setProperty("--x", x.toFixed(3));
if (c.at <= this.last) dot.classList.add("past");
layer.append(dot);
return dot;
});
wrap.append(layer);
this.layer = layer;
}
unmount(): void {
this.layer?.remove();
for (const b of this.shown) b.remove();
this.peeked?.el.remove();
this.layer = this.wrap = this.peeked = null;
this.dots = [];
this.shown = [];
}
/// Playback is at `t` seconds. Comments passed since the last tick fire, unless
/// the step was a seek; dots behind the playhead stay lit.
tick(t: number): void {
const from = this.last;
this.last = t;
const played = t > from && t - from < SEEK;
let fire: Comment | null = null;
for (let i = 0; i < this.list.length; i++) {
const c = this.list[i], dot = this.dots[i];
dot?.classList.toggle("past", c.at <= t);
if (played && c.at > from && c.at <= t) {
if (dot) ping(dot);
fire = c;
}
}
const now = performance.now();
if (fire && this.layer && now - this.lastBubble >= GAP) {
this.lastBubble = now;
this.bubble(fire);
}
}
/// The mouse is at `f` (0..1) of the waveform, `width` px wide; null when it left.
peek(f: number | null, width: number): void {
const d = this.duration();
let near: Comment | null = null;
if (f !== null && d && this.layer) {
let best = PEEK_PX;
for (const c of this.list) {
const px = Math.abs(c.at / d - f) * width;
if (px <= best) [best, near] = [px, c];
}
}
if (near?.id === this.peeked?.id) return;
this.peeked?.el.remove();
this.peeked = null;
if (near) this.peeked = { el: this.place(near, "peek"), id: near.id };
}
private bubble(c: Comment): void {
const el = this.place(c, "");
const h = el.offsetHeight + STACK;
// The ones already up make room, the oldest leaves early.
for (const b of this.shown) b.style.setProperty("--lift", `${(parseFloat(b.style.getPropertyValue("--lift")) || 0) + h}px`);
this.shown.push(el);
while (this.shown.length > MAX_SHOWN) leave(this.shown.shift()!);
setTimeout(() => {
el.remove();
this.shown = this.shown.filter((b) => b !== el);
}, LIFE);
}
/// A bubble for `c` over its dot, kept inside the waveform's width, its tail
/// pointing at the dot.
private place(c: Comment, kind: string): HTMLElement {
const wrap = this.wrap!;
const el = document.createElement("div");
el.className = `wc-bubble ${kind}`.trim();
const inner = document.createElement("div");
inner.className = "wc-in";
const avatar = document.createElement("span");
avatar.className = "wc-avatar";
const img = imgUrl(c.img);
if (img) avatar.style.backgroundImage = `url("${img}")`;
else {
avatar.textContent = (c.name || "?")[0].toUpperCase();
avatar.style.background = accentForName(c.name || "?");
}
const text = document.createElement("span");
text.className = "wc-text";
const name = document.createElement("b");
name.textContent = c.name + (c.verified ? " ✓" : "");
const body = document.createElement("span");
body.textContent = c.body;
text.append(name, body);
inner.append(avatar, text);
el.append(inner);
wrap.append(el);
const w = wrap.clientWidth;
const x = Math.min(1, c.at / (this.duration() || 1)) * w;
const left = Math.max(0, Math.min(w - el.offsetWidth, x - el.offsetWidth / 2));
el.style.left = `${left}px`;
el.style.setProperty("--tail", `${Math.round(x - left)}px`);
// From the bubble down to the middle of the dots' row (see .wave-comments).
el.style.setProperty("--reach", `${Math.round(GAP_ABOVE + wrap.clientHeight * (1 - DOTS_ROW / 2))}px`);
return el;
}
}
/// Restart the dot's ping.
function ping(dot: HTMLElement): void {
dot.classList.remove("hit");
void dot.offsetWidth;
dot.classList.add("hit");
}
function leave(el: HTMLElement): void {
el.classList.add("out");
setTimeout(() => el.remove(), 300);
}
+15
View File
@@ -25,7 +25,11 @@ const FILTERS_KEY = "pl8inf.filters";
const MODE_KEY = "pl8inf.mode"; const MODE_KEY = "pl8inf.mode";
const HINT_KEY = "pl8inf.hintShown"; const HINT_KEY = "pl8inf.hintShown";
const NUDGE_KEY = "pl8inf.signInNudged"; const NUDGE_KEY = "pl8inf.signInNudged";
const COMMENTS_KEY = "pl8inf.waveComments";
const NUDGE_LIKES = 5; // a guest is asked to sign in after this many likes, or a first follow const NUDGE_LIKES = 5; // a guest is asked to sign in after this many likes, or a first follow
/// Timed comments on the waveform, on unless turned off.
let waveComments = localStorage.getItem(COMMENTS_KEY) !== "0";
document.body.classList.toggle("no-wave-comments", !waveComments);
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T; const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
@@ -199,6 +203,7 @@ function activate(idx: number): void {
if (pager.index !== idx) pager.go(idx, { instant: true }); if (pager.index !== idx) pager.go(idx, { instant: true });
card.element().classList.add("current"); card.element().classList.add("current");
visual.attach(card); visual.attach(card);
if (waveComments) card.loadComments();
if (started) play(card.track); if (started) play(card.track);
else showStart(card); else showStart(card);
clearTimeout(preloadTimer); clearTimeout(preloadTimer);
@@ -361,6 +366,7 @@ player.on("timeupdate", () => {
lastTime = t; lastTime = t;
const card = current(); const card = current();
card?.setTime(t); card?.setTime(t);
card?.commentsAt(t);
updatePosition(); updatePosition();
if (card && !remembered && listened >= HISTORY_AFTER) { if (card && !remembered && listened >= HISTORY_AFTER) {
remembered = true; remembered = true;
@@ -842,6 +848,13 @@ function showSetting(name: string, value: string): void {
for (const input of filtersForm.querySelectorAll<HTMLInputElement>(`input[name=${name}]`)) input.checked = input.value === value; for (const input of filtersForm.querySelectorAll<HTMLInputElement>(`input[name=${name}]`)) input.checked = input.value === value;
} }
function setWaveComments(on: boolean): void {
waveComments = on;
localStorage.setItem(COMMENTS_KEY, on ? "1" : "0");
document.body.classList.toggle("no-wave-comments", !on);
if (on) current()?.loadComments();
}
function setVisuals(v: VisualsSetting): void { function setVisuals(v: VisualsSetting): void {
visual.visuals = v; visual.visuals = v;
showSetting("visuals", v); showSetting("visuals", v);
@@ -854,6 +867,7 @@ filtersForm.addEventListener("change", (e) => {
else if (input.name === "spikes") visual.spikes = input.value as SpikeSetting; else if (input.name === "spikes") visual.spikes = input.value as SpikeSetting;
else if (input.name === "crossfade") player.crossfade = Number(input.value); else if (input.name === "crossfade") player.crossfade = Number(input.value);
else if (input.name === "bass") player.bassBoost = input.checked; else if (input.name === "bass") player.bassBoost = input.checked;
else if (input.name === "comments") setWaveComments(input.checked);
else if (input.name === "sleep") setSleep(input.value); else if (input.name === "sleep") setSleep(input.value);
}); });
filtersForm.addEventListener("submit", (e) => { e.preventDefault(); applyFilters(); }); filtersForm.addEventListener("submit", (e) => { e.preventDefault(); applyFilters(); });
@@ -874,6 +888,7 @@ function showSettings(): void {
const bass = filtersForm.elements.namedItem("bass") as HTMLInputElement; const bass = filtersForm.elements.namedItem("bass") as HTMLInputElement;
bass.checked = player.bassBoost; bass.checked = player.bassBoost;
bass.closest("label")!.hidden = !player.canMix; bass.closest("label")!.hidden = !player.canMix;
(filtersForm.elements.namedItem("comments") as HTMLInputElement).checked = waveComments;
showSleep(); showSleep();
} }
sheets.filters.onOpen = showSettings; sheets.filters.onOpen = showSettings;
+130
View File
@@ -645,6 +645,133 @@ button.danger:not(.link) { background: var(--accent); border: none; color: #fff;
transition: opacity 0.1s; transition: opacity 0.1s;
} }
.wave-wrap.hover .wave-tip { opacity: 1; } .wave-wrap.hover .wave-tip { opacity: 1; }
/* Timed comments: dots in the reflection under the waveform, lit once played,
and bubbles that grow out of a dot when the music gets there. */
.wave-comments { position: absolute; inset: auto 0 0; height: 28%; pointer-events: none; }
.wc-dot {
position: absolute;
top: 50%;
width: 5px;
height: 5px;
margin: -2.5px 0 0 -2.5px;
border-radius: 50%;
background: #ffffffa0;
transition: background 0.3s, box-shadow 0.3s;
animation: wc-sprout 0.5s calc(var(--x) * 0.7s) cubic-bezier(.2, .9, .3, 1.5) both;
}
.wc-dot.past { background: var(--card-accent); box-shadow: 0 0 6px var(--card-accent); }
.wc-dot.hit { animation: wc-ping 0.7s ease-out; }
@keyframes wc-sprout { from { transform: scale(0); opacity: 0; } }
@keyframes wc-ping {
0% { transform: scale(1); box-shadow: 0 0 0 0 color-mix(in oklab, var(--card-accent) 80%, transparent); }
25% { transform: scale(2.2); }
100% { transform: scale(1); box-shadow: 0 0 0 10px transparent; }
}
.wc-bubble {
position: absolute;
z-index: 3;
bottom: calc(100% + 8px);
width: max-content;
max-width: min(17rem, 100%);
pointer-events: none;
translate: 0 calc(-1 * var(--lift, 0px));
transition: translate 0.4s cubic-bezier(.2, .9, .3, 1.2), opacity 0.2s;
}
/* A spark running up from the dot to the bubble as it opens. */
.wc-bubble::before {
content: "";
position: absolute;
top: 100%;
left: calc(var(--tail) - 1px);
width: 2px;
height: var(--reach, 3rem);
border-radius: 1px;
background: linear-gradient(to top, var(--card-accent), transparent);
filter: drop-shadow(0 0 4px var(--card-accent));
transform-origin: bottom;
animation: wc-spark 0.9s ease-out both;
}
.wc-in {
position: relative;
display: flex;
gap: 0.45rem;
align-items: flex-start;
padding: 0.35rem 0.7rem 0.4rem 0.35rem;
border-radius: 14px;
background: #000000a8;
backdrop-filter: blur(12px);
box-shadow:
inset 0 0 0 1px color-mix(in oklab, var(--card-accent) 45%, transparent),
0 6px 22px #0008,
0 0 18px color-mix(in oklab, var(--card-accent) 22%, transparent);
font-size: 0.78rem;
line-height: 1.25;
text-align: left;
transform-origin: var(--tail) 100%;
animation: wc-rise 4.6s cubic-bezier(.2, .8, .3, 1) both;
}
/* The tail, pointing down at the dot. */
.wc-in::after {
content: "";
position: absolute;
top: 100%;
left: calc(var(--tail) - 6px);
width: 12px;
height: 6px;
background: #000000a8;
clip-path: polygon(0 0, 100% 0, 50% 100%);
}
.wc-avatar {
flex: none;
width: 1.6rem;
height: 1.6rem;
display: grid;
place-items: center;
border-radius: 50%;
background: center / cover #333;
color: #000;
font-size: 0.75rem;
font-weight: 700;
}
.wc-text { display: flex; flex-direction: column; min-width: 0; }
.wc-text b {
overflow: hidden;
color: var(--card-accent);
font-size: 0.7rem;
font-weight: 600;
white-space: nowrap;
text-overflow: ellipsis;
}
.wc-text span {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
line-clamp: 3;
overflow: hidden;
overflow-wrap: anywhere;
}
@keyframes wc-rise {
0% { opacity: 0; transform: translateY(14px) scale(0.3); filter: blur(4px); }
12% { opacity: 1; transform: translateY(-3px) scale(1.06); filter: blur(0); }
20% { transform: translateY(0) scale(1); }
82% { opacity: 1; transform: translateY(-4px); }
100% { opacity: 0; transform: translateY(-18px) scale(0.96); filter: blur(3px); }
}
@keyframes wc-spark {
0% { transform: scaleY(0); opacity: 1; }
40% { transform: scaleY(1); opacity: 1; }
100% { transform: scaleY(1); opacity: 0; }
}
.wc-bubble.out { opacity: 0; }
/* Peeking with the mouse: above the time tip, no spark, no fading out. */
.wc-bubble.peek { bottom: calc(100% + 1.9rem); }
.wc-bubble.peek::before { display: none; }
.wc-bubble.peek .wc-in { animation: wc-peek 0.2s cubic-bezier(.2, .9, .3, 1.3) both; }
@keyframes wc-peek { from { opacity: 0; transform: translateY(6px) scale(0.8); } }
.wave-wrap:has(.wc-bubble.peek) .wc-bubble:not(.peek) { opacity: 0; }
body.no-wave-comments :is(.wave-comments, .wc-bubble), body.zen :is(.wave-comments, .wc-bubble) { display: none; }
.time { width: 100%; display: flex; justify-content: space-between; gap: 1rem; color: var(--muted); font-size: 0.75rem; font-variant-numeric: tabular-nums; } .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; } .counts { opacity: 0.8; }
.to-drop { .to-drop {
@@ -1183,4 +1310,7 @@ body.zen .content { gap: 0.3rem; }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
/* Comment bubbles stay for their time instead of flashing past. */
.wc-in { animation: none; }
.wc-bubble::before { display: none; }
} }