Repository Public
1"use client";2import { useEffect, useMemo, useRef, useState } from "react";3import { api } from "@/lib/client-api";4import type { LyricLine, Lyrics, Track } from "@/lib/types";5import { useT } from "@/i18n";6import { usePlayer, usePlayerActions } from "./player";7import { ISpinner } from "./icons";89/**10 * Karaoke view: the line being sung is brought to the centre and its words light up one by one.11 * Timing is read straight from the <audio> clock on every animation frame (the 4 Hz timeupdate event is too coarse12 * for word-level highlighting). Tapping a line seeks to it.13 */14function activeIndex(lines: LyricLine[], ms: number): number {15 let lo = 0, hi = lines.length - 1, ans = -1;16 while (lo <= hi) { const mid = (lo + hi) >> 1; if (lines[mid].t <= ms + 120) { ans = mid; lo = mid + 1; } else hi = mid - 1; }17 return ans;18}1920export function LyricsView({ track }: { track: Track }) {21 const t = useT();22 const player = usePlayer(); const actions = usePlayerActions();23 const [data, setData] = useState<{ id: string; lyrics: Lyrics } | null>(null);24 const [failed, setFailed] = useState(false);25 const [now, setNow] = useState(0);26 const box = useRef<HTMLDivElement>(null);27 const userScrollAt = useRef(0);28 const lyrics = data?.id === track.id ? data.lyrics : null;2930 // Load, and keep polling while a transcription is on its way.31 useEffect(() => {32 let alive = true, timer: ReturnType<typeof setTimeout> | undefined;33 setFailed(false);34 const load = () => api<Lyrics>(`/api/v1/library/tracks/${track.id}/lyrics`).then((l) => {35 if (!alive) return;36 setData({ id: track.id, lyrics: l });37 if (l.state === "queued" || l.state === "working") timer = setTimeout(load, 3000);38 }).catch(() => { if (alive) setFailed(true); });39 load();40 return () => { alive = false; if (timer) clearTimeout(timer); };41 }, [track.id]);4243 // Animation clock.44 const ready = lyrics?.state === "ready";45 useEffect(() => {46 if (!ready) return;47 let raf = 0;48 const tick = () => { setNow(actions.positionMs()); if (player.playing) raf = requestAnimationFrame(tick); };49 tick();50 return () => cancelAnimationFrame(raf);51 }, [ready, player.playing, actions, track.id]);5253 const lines = useMemo(() => lyrics?.lines ?? [], [lyrics]);54 const idx = ready ? activeIndex(lines, now) : -1;5556 // Follow the song, unless the listener scrolled by hand a moment ago.57 useEffect(() => {58 if (idx < 0 || Date.now() - userScrollAt.current < 4000) return;59 box.current?.querySelector<HTMLElement>(`[data-line="${idx}"]`)?.scrollIntoView({ block: "center", behavior: "smooth" });60 }, [idx]);6162 if (failed) return <p className="py-10 text-center text-sm text-danger" role="alert">{t("lyrics.loadFailed")}</p>;63 if (!lyrics) return <div className="flex justify-center py-10 text-muted"><ISpinner /></div>;64 if (lyrics.state === "queued" || lyrics.state === "working") return <p className="flex items-center justify-center gap-2 py-10 text-sm text-muted" role="status"><ISpinner size={16} />{t("lyrics.working")}</p>;65 if (lyrics.state !== "ready") return (66 <div className="mx-auto max-w-sm py-10 text-center">67 <p className="text-base font-bold">{t(lyrics.state === "empty" ? "lyrics.emptyTitle" : lyrics.state === "error" ? "lyrics.errorTitle" : "lyrics.noneTitle")}</p>68 <p className="mt-1.5 text-sm leading-relaxed text-muted">{t(lyrics.state === "empty" ? "lyrics.emptyBody" : lyrics.enabled ? "lyrics.noneBody" : "lyrics.disabledBody")}</p>69 </div>70 );71 return (72 <div ref={box} className="h-full overflow-y-auto px-1 pb-[40vh] pt-[18vh]" onWheel={() => { userScrollAt.current = Date.now(); }} onTouchMove={() => { userScrollAt.current = Date.now(); }}>73 <ol aria-label={t("lyrics.title")}>74 {lines.map((l, i) => {75 const state = i === idx ? "now" : i < idx ? "past" : "next";76 return (77 <li key={`${l.t}-${i}`} data-line={i}>78 <button onClick={() => { userScrollAt.current = 0; actions.seek(l.t); if (!player.playing) actions.toggle(); }} aria-current={state === "now" ? "true" : undefined}79 className={`block w-full rounded-xl px-3 py-2 text-left text-[1.45rem] font-extrabold leading-snug tracking-tight transition-[color,opacity,transform] duration-300 sm:text-[1.7rem] ${state === "now" ? "origin-left scale-[1.03] text-ink" : state === "past" ? "text-ink/35" : "text-ink/55"}`}>80 {state === "now" && l.w ? l.w.map((w, k) => {81 // The word being sung fills from left to right; sung words are fully lit.82 const p = now >= w[1] ? 1 : now <= w[0] ? 0 : (now - w[0]) / Math.max(1, w[1] - w[0]);83 return <span key={k} style={{ backgroundImage: `linear-gradient(90deg, var(--accent) ${p * 100}%, color-mix(in srgb, var(--color-ink) 45%, transparent) ${p * 100}%)`, WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent" }}>{w[2]}</span>;84 }) : l.text}85 </button>86 </li>87 );88 })}89 </ol>90 <p className="mt-8 px-3 text-xs leading-relaxed text-faint">{t(lyrics.edited ? "lyrics.noteEdited" : "lyrics.noteAuto")}</p>91 </div>92 );93}94