"use client";import * as React from "react";import { Pause, Play, SkipBack, SkipForward } from "lucide-react";import { LACQUER, lacquer, mixTone, type LacquerTone } from "./lacquer";import { LightSurface, type LightPaletteName, type LightSurfaceHandle } from "./light-surface";import { TextMorph } from "./text-morph";import { interactionIcon, useInteractionReducedMotion } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * TRACK PLAYER: a small lacquered player for music or a show * * play the disc turns, the waveform ripples gently along * its length and fills white as the track plays * scrub drag along the waveform (or use the arrow keys); * the fill and the times follow, and it carries on * from there * change previous and next drift a soft veil of light across * the player; under it the track, its lacquer colour * and its disc change over * * Plays your audio when a track has a src; without one it keeps * its own clock, for previews. An object with its own dark finish: * the same on a light page or a dark one. * * Reduced motion: no ripple, no spin and no veil. * ───────────────────────────────────────────────────────── */export interface PlayerTrack { id: string; title: string; artist: string; /** Seconds; the audio's own length replaces it once known. */ duration: number; src?: string; /** Loudness, 0 to 1 (or 0 to 100), any length; drawn as 48 bars. */ peaks?: number[]; /** This track's lacquer: a named tone or any CSS colour. */ tone?: LacquerTone | (string & {}); /** Top right: where it's playing. */ output?: string; /** Cover art for the disc; a disc in the track's colour without one. */ art?: string;}export interface TrackPlayerProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> { tracks: PlayerTrack[]; index?: number; defaultIndex?: number; onIndexChange?: (index: number) => void; playing?: boolean; defaultPlaying?: boolean; onPlayingChange?: (playing: boolean) => void; playingLabel?: string; pausedLabel?: string; /** Names the player for screen readers. */ label?: string;}const BARS = 48;const VEIL: Record<LacquerTone, LightPaletteName> = { ember: "solar", cobalt: "azure", rose: "prism", emerald: "azure", midnight: "azure", violet: "dusk" };const time = (s: number) => { const t = Math.max(0, Math.round(s)); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;};/** Peaks as 48 bar heights; without peaks, a steady made-up shape from the track's id so each track looks its own. */function barsFor(track: PlayerTrack) { let src = track.peaks; if (!src?.length) { let h = 2166136261; for (const ch of track.id) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); const rnd = () => ((h = Math.imul(h ^ (h >>> 15), 2246822507)) >>> 0) / 4294967296; src = Array.from({ length: BARS }, (_, i) => 0.3 + 0.55 * Math.abs(Math.sin(i * 0.42 + rnd() * 2)) * (0.6 + 0.4 * rnd())); } const max = Math.max(...src, 1e-6); return Array.from({ length: BARS }, (_, i) => { const a = Math.floor((i * src.length) / BARS); const b = Math.max(a + 1, Math.floor(((i + 1) * src.length) / BARS)); let sum = 0; for (let j = a; j < b; j++) sum += src[j] ?? 0; return Math.max(0.16, Math.min(1, sum / (b - a) / max)); });}function Wave({ heights, played, rippling, reduced }: { heights: number[]; played: boolean; rippling: boolean; reduced: boolean }) { return ( <span className="flex h-full w-full items-center justify-between gap-[2px]"> {heights.map((h, i) => ( <span key={i} className="block flex-1 rounded-full" style={{ height: `${h * 100}%`, background: played ? "#fff" : "rgb(255 255 255 / 0.28)", animation: reduced ? undefined : `ui-track-pulse 900ms ease-in-out ${-(i * 55)}ms infinite alternate`, animationPlayState: rippling ? "running" : "paused", }} /> ))} </span> );}export function TrackPlayer({ tracks, index, defaultIndex = 0, onIndexChange, playing, defaultPlaying = false, onPlayingChange, playingLabel = "Now playing", pausedLabel = "Paused", label = "Player", className = "", style, ...props}: TrackPlayerProps) { const reduced = useInteractionReducedMotion(); const surface = React.useRef<LightSurfaceHandle>(null); const audio = React.useRef<HTMLAudioElement>(null); const wave = React.useRef<HTMLDivElement>(null); const playedLayer = React.useRef<HTMLSpanElement>(null); const [ownIndex, setOwnIndex] = React.useState(defaultIndex); const [ownPlaying, setOwnPlaying] = React.useState(defaultPlaying); const at = Math.max(0, Math.min(tracks.length - 1, index ?? ownIndex)); const isPlaying = playing ?? ownPlaying; const track = tracks[at]; const [known, setKnown] = React.useState<Record<string, number>>({}); const duration = known[track.id] ?? track.duration; const heights = React.useMemo(() => barsFor(track), [track]); const [second, setSecond] = React.useState(0); const [scrubbing, setScrubbing] = React.useState(false); const clock = React.useRef({ t: 0, second: 0 }); const tone = track.tone ?? "ember"; const setPlaying = (p: boolean) => { if (playing === undefined) setOwnPlaying(p); onPlayingChange?.(p); }; const setIndex = (i: number) => { if (index === undefined) setOwnIndex(i); onIndexChange?.(i); }; /** Writes the fill straight to the clipped layer; the times re-render only when the whole second changes. */ const paint = React.useCallback( (t: number) => { clock.current.t = t; const pct = duration > 0 ? Math.max(0, Math.min(1, t / duration)) : 0; if (playedLayer.current) playedLayer.current.style.clipPath = `inset(0 ${(100 - pct * 100).toFixed(3)}% 0 0)`; const s = Math.floor(t); if (s !== clock.current.second) { clock.current.second = s; setSecond(s); } }, [duration], ); React.useLayoutEffect(() => { paint(clock.current.t); }, [paint]); // Playing: the audio's own clock when there is a src, otherwise one of our own. React.useEffect(() => { const el = audio.current; if (track.src && el) { if (isPlaying) void el.play().catch(() => setPlaying(false)); else el.pause(); } if (!isPlaying || scrubbing) return; let raf = 0; let last = 0; const tick = (now: number) => { const dt = last ? (now - last) / 1000 : 0; last = now; let t = track.src && el ? el.currentTime : clock.current.t + dt; if (t >= duration) { t = 0; if (el && track.src) el.currentTime = 0; paint(0); setPlaying(false); return; } paint(t); raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); // eslint-disable-next-line react-hooks/exhaustive-deps }, [isPlaying, scrubbing, track.id, track.src, duration, paint]); const go = (delta: number) => { const next = (at + delta + tracks.length) % tracks.length; const land = () => { setIndex(next); clock.current.second = -1; paint(0); if (audio.current) audio.current.currentTime = 0; }; const s = surface.current; if (!s || reduced) return land(); const t = tracks[next].tone ?? "ember"; s.wave({ direction: "diagonal", palette: t in LACQUER ? VEIL[t as LacquerTone] : "prism", duration: 1020, onMidpoint: land }); }; const seekFrom = (clientX: number) => { const r = wave.current?.getBoundingClientRect(); if (!r) return; paint(Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * duration); }; const commitSeek = () => { if (audio.current && track.src) audio.current.currentTime = clock.current.t; }; const disc = track.art ? undefined : `conic-gradient(from 40deg, ${mixTone(tone, 1, "#000000")}, ${mixTone(tone, 0.55, "#ffffff")}, ${mixTone(tone, 0.7, "#000000")}, ${mixTone(tone, 0.75, "#ffd36b")}, ${mixTone(tone, 0.6, "#6be4ff")}, ${mixTone(tone, 1, "#000000")})`; return ( <LightSurface ref={surface} direction="diagonal" veil="#05050a" role="group" aria-label={`${label}: ${track.title} by ${track.artist}`} className={`w-full rounded-[22px] select-none ${className}`} style={{ ...lacquer(tone), ...style }} {...props} > {track.src && ( <audio ref={audio} src={track.src} preload="metadata" onLoadedMetadata={(e) => { const d = e.currentTarget.duration; if (Number.isFinite(d) && d > 0) setKnown((k) => (k[track.id] === d ? k : { ...k, [track.id]: d })); }} /> )} <div className="@container flex flex-col gap-4 px-5 py-4"> <div className="flex items-center justify-between gap-2 text-[11px] font-medium text-white/75"> <TextMorph>{isPlaying ? playingLabel : pausedLabel}</TextMorph> {track.output && <span className="truncate font-mono text-[10.5px] text-white/65">{track.output}</span>} </div> <div className="flex flex-col items-stretch gap-3 @[18rem]:flex-row @[18rem]:items-center @[18rem]:justify-between @[18rem]:gap-2.5"> <div className="flex min-w-0 items-center gap-3"> <span aria-hidden className="relative grid size-11 shrink-0 animate-spin place-items-center overflow-clip rounded-full" style={{ background: disc, boxShadow: "inset 0 0 0 1px rgb(255 255 255 / 0.25)", animationDuration: "6s", animationPlayState: isPlaying && !reduced ? "running" : "paused", }} > {track.art && <img src={track.art} alt="" className="absolute inset-0 size-full object-cover" />} <span className="absolute inset-0 rounded-full" style={{ background: "linear-gradient(135deg, rgb(255 255 255 / 0.42) 0%, transparent 45%, rgb(0 0 0 / 0.24) 100%)" }} /> <span className="relative size-3 rounded-full bg-[#0d0707]" style={{ boxShadow: "inset 0 0 0 1px rgb(255 255 255 / 0.35)" }} /> </span> <div className="min-w-0"> <div className="truncate text-[14.5px] font-semibold leading-snug tracking-[-0.015em] text-white">{track.title}</div> <div className="truncate text-[12px] text-white/65">{track.artist}</div> </div> </div> <div className="flex shrink-0 items-center justify-center gap-1.5 @[18rem]:justify-end"> <button type="button" onClick={() => go(-1)} aria-label="Previous track" className="grid size-7 cursor-pointer place-items-center rounded-full bg-white/12 text-white/90 outline-none transition-[background-color,scale] duration-150 hover:bg-white/22 focus-visible:ring-2 focus-visible:ring-white/70 active:scale-[0.92]" > <SkipBack className="size-3 fill-current" aria-hidden /> </button> <button type="button" onClick={() => setPlaying(!isPlaying)} aria-label={isPlaying ? "Pause" : "Play"} className="grid size-8 cursor-pointer place-items-center rounded-full bg-white text-[#12090a] outline-none transition-[scale] duration-150 focus-visible:ring-2 focus-visible:ring-white/85 active:scale-[0.93]" > <span className="grid place-items-center [grid-area:1/1]" style={interactionIcon(isPlaying, reduced)}> <Pause className="size-3.5 fill-current" aria-hidden /> </span> <span className="grid place-items-center [grid-area:1/1]" style={interactionIcon(!isPlaying, reduced)}> <Play className="size-3.5 translate-x-px fill-current" aria-hidden /> </span> </button> <button type="button" onClick={() => go(1)} aria-label="Next track" className="grid size-7 cursor-pointer place-items-center rounded-full bg-white/12 text-white/90 outline-none transition-[background-color,scale] duration-150 hover:bg-white/22 focus-visible:ring-2 focus-visible:ring-white/70 active:scale-[0.92]" > <SkipForward className="size-3 fill-current" aria-hidden /> </button> </div> </div> <div> <div ref={wave} role="slider" tabIndex={0} aria-label="Position" aria-valuemin={0} aria-valuemax={Math.round(duration)} aria-valuenow={second} aria-valuetext={`${time(second)} of ${time(duration)}`} onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); setScrubbing(true); seekFrom(e.clientX); }} onPointerMove={(e) => scrubbing && seekFrom(e.clientX)} onPointerUp={() => { commitSeek(); setScrubbing(false); }} onPointerCancel={() => setScrubbing(false)} onKeyDown={(e) => { const by = { ArrowRight: 5, ArrowUp: 5, ArrowLeft: -5, ArrowDown: -5, PageUp: 15, PageDown: -15 }[e.key]; const to = by !== undefined ? clock.current.t + by : e.key === "Home" ? 0 : e.key === "End" ? duration - 0.5 : null; if (to === null) return; e.preventDefault(); paint(Math.max(0, Math.min(duration, to))); commitSeek(); }} className="relative h-9 w-full cursor-pointer touch-none rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-white/60" > <Wave heights={heights} played={false} rippling={isPlaying && !scrubbing} reduced={reduced} /> <span ref={playedLayer} aria-hidden className="pointer-events-none absolute inset-0" style={{ clipPath: "inset(0 100% 0 0)" }}> <Wave heights={heights} played rippling={isPlaying && !scrubbing} reduced={reduced} /> </span> </div> <div className="mt-1 flex items-center justify-between font-mono text-[10.5px] tabular-nums text-white/65"> <span>{time(second)}</span> <span>-{time(Math.max(0, duration - second))}</span> </div> </div> </div> <span className="sr-only" aria-live="polite"> {`${track.title} by ${track.artist}`} </span> </LightSurface> );}