feat(frontend): add HeroPlayer interactive island

This commit is contained in:
devilreef 2026-04-30 09:41:07 +06:00
parent 7ab3c850bf
commit 65d88be032
Signed by: devilreef
SSH key fingerprint: SHA256:UZisRr4iuXx+IhkbZnR655L2RWAT6o2rgbGv5F/6m3Y
3 changed files with 525 additions and 0 deletions

View file

@ -0,0 +1,324 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import type { Station, NowPlaying, IcecastStatusJson } from '@lib/types';
import { Tape } from './Tape';
import { Spectrum } from './Spectrum';
import { playerStore } from '@lib/store';
import { fmtMs, fmtJpDate, fmtJpTime } from '@lib/format';
const PUBLIC_ORIGIN = 'https://denpa.femboy.page';
const POLL_NOW_MS = 5_000;
const POLL_LISTENERS_MS = 30_000;
interface Props {
initialStations: Station[];
}
type Format = 'mp3' | 'opus';
const lsGet = (k: string): string | null => {
try { return localStorage.getItem(k); } catch { return null; }
};
const lsSet = (k: string, v: string) => {
try { localStorage.setItem(k, v); } catch { /* ignore */ }
};
export function HeroPlayer({ initialStations }: Props) {
const [stations, setStations] = useState<Station[]>(initialStations);
const [selectedId, setSelectedId] = useState<string>(() => {
const saved = lsGet('denpa:station');
if (saved && initialStations.some((s) => s.id === saved)) return saved;
return initialStations[0]?.id ?? '';
});
const [format, setFormat] = useState<Format>(() => (lsGet('denpa:format') === 'opus' ? 'opus' : 'mp3'));
const [vol, setVol] = useState<number>(() => {
const v = parseFloat(lsGet('denpa:vol') ?? '0.72');
return isNaN(v) ? 0.72 : Math.max(0, Math.min(1, v));
});
const [muted, setMuted] = useState(false);
const [playing, setPlaying] = useState(false);
const [now, setNow] = useState<NowPlaying | null>(null);
const [listeners, setListeners] = useState<number | null>(null);
const [elapsed, setElapsed] = useState(0);
const [copyState, setCopyState] = useState<'idle' | 'ok'>('idle');
const [clockNow, setClockNow] = useState(() => new Date());
const audioRef = useRef<HTMLAudioElement | null>(null);
const station = stations.find((s) => s.id === selectedId);
const streamUrl = station ? `${PUBLIC_ORIGIN}${station.mounts[format]}` : '';
// refresh stations periodically (cheap; backend caches)
useEffect(() => {
let aborted = false;
const refresh = async () => {
try {
const r = await fetch('/api/stations.json');
if (!r.ok) return;
const ss = await r.json() as Station[];
if (!aborted && ss.length) {
setStations(ss);
if (!ss.some((s) => s.id === selectedId)) {
const first = ss[0];
if (first) setSelectedId(first.id);
}
}
} catch { /* ignore */ }
};
const id = setInterval(refresh, 60_000);
return () => { aborted = true; clearInterval(id); };
}, [selectedId]);
// share audio element with Spectrum
useEffect(() => {
playerStore.setAudio(audioRef.current);
return () => playerStore.setAudio(null);
}, []);
// wire <audio> events
useEffect(() => {
const a = audioRef.current;
if (!a) return;
const onPlay = () => setPlaying(true);
const onPause = () => setPlaying(false);
const onError = () => setPlaying(false);
a.addEventListener('play', onPlay);
a.addEventListener('pause', onPause);
a.addEventListener('error', onError);
return () => {
a.removeEventListener('play', onPlay);
a.removeEventListener('pause', onPause);
a.removeEventListener('error', onError);
};
}, []);
// volume sync
useEffect(() => {
const a = audioRef.current;
if (a) a.volume = muted ? 0 : vol;
lsSet('denpa:vol', String(vol));
}, [vol, muted]);
// persist selections
useEffect(() => { lsSet('denpa:station', selectedId); }, [selectedId]);
useEffect(() => { lsSet('denpa:format', format); }, [format]);
// poll now-playing
useEffect(() => {
if (!selectedId) return;
const ctrl = new AbortController();
let timer: ReturnType<typeof setInterval> | null = null;
const fetchNow = async () => {
try {
const r = await fetch(`/now-playing/${selectedId}.json`, { signal: ctrl.signal });
if (!r.ok) { setNow(null); return; }
const np = await r.json() as NowPlaying;
setNow(np);
} catch (err) {
if ((err as Error).name !== 'AbortError') setNow(null);
}
};
void fetchNow();
timer = setInterval(fetchNow, POLL_NOW_MS);
return () => { ctrl.abort(); if (timer) clearInterval(timer); };
}, [selectedId]);
// poll listeners
useEffect(() => {
if (!selectedId) return;
const ctrl = new AbortController();
let timer: ReturnType<typeof setInterval> | null = null;
const fetchListeners = async () => {
try {
const r = await fetch('/status-json.xsl', { signal: ctrl.signal });
if (!r.ok) return;
const j = await r.json() as IcecastStatusJson;
const sources = j?.icestats?.source;
const arr = Array.isArray(sources) ? sources : sources ? [sources] : [];
const want = `/${selectedId}.${format}`;
const m = arr.find((s) => s.listenurl?.endsWith(want));
if (m && typeof m.listeners === 'number') setListeners(m.listeners);
} catch (err) {
if ((err as Error).name !== 'AbortError') setListeners(null);
}
};
void fetchListeners();
timer = setInterval(fetchListeners, POLL_LISTENERS_MS);
return () => { ctrl.abort(); if (timer) clearInterval(timer); };
}, [selectedId, format]);
// elapsed ticker
useEffect(() => {
if (!now?.started_at) { setElapsed(0); return; }
const start = parseInt(now.started_at, 10) * 1000;
const update = () => setElapsed(Math.max(0, Math.floor((Date.now() - start) / 1000)));
update();
const id = setInterval(update, 1000);
return () => clearInterval(id);
}, [now?.started_at]);
// wall clock for header
useEffect(() => {
const id = setInterval(() => setClockNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
// keyboard shortcuts
const togglePlay = useCallback(() => {
const a = audioRef.current;
if (!a) return;
if (a.paused) a.play().catch(() => { /* ignore — autoplay etc. */ });
else a.pause();
}, []);
const cycleStation = useCallback((dir: 1 | -1) => {
if (!stations.length) return;
const i = stations.findIndex((s) => s.id === selectedId);
const next = stations[(i + dir + stations.length) % stations.length];
if (next) setSelectedId(next.id);
}, [stations, selectedId]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const tgt = e.target as HTMLElement | null;
if (tgt && /^(INPUT|TEXTAREA|SELECT)$/.test(tgt.tagName)) return;
switch (e.key) {
case ' ': e.preventDefault(); togglePlay(); break;
case 'ArrowUp': e.preventDefault(); setVol((v) => Math.min(1, v + 0.05)); break;
case 'ArrowDown': e.preventDefault(); setVol((v) => Math.max(0, v - 0.05)); break;
case 'ArrowLeft': e.preventDefault(); cycleStation(-1); break;
case 'ArrowRight': e.preventDefault(); cycleStation(1); break;
case 'm': case 'M': e.preventDefault(); setMuted((m) => !m); break;
}
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [togglePlay, cycleStation]);
// copy URL
const copyUrl = async () => {
try {
await navigator.clipboard.writeText(streamUrl);
setCopyState('ok');
} catch {
const ta = document.createElement('textarea');
ta.value = streamUrl;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
setCopyState('ok');
}
setTimeout(() => setCopyState('idle'), 1500);
};
// when station/format changes, reload + maybe play
useEffect(() => {
const a = audioRef.current;
if (!a || !station) return;
const wasPlaying = !a.paused;
a.src = `${station.mounts[format]}`;
a.load();
if (wasPlaying) a.play().catch(() => { /* ignore */ });
}, [selectedId, format]);
if (!station) {
return <section className="hero"><p>no stations available add a station folder under <code>library/</code> on the storage box.</p></section>;
}
const dur = parseInt(now?.duration ?? '', 10);
const hasDur = !isNaN(dur) && dur > 0;
const pct = hasDur ? Math.min(100, (elapsed / dur) * 100) : 0;
return (
<section className="hero">
<div className="hero-header">
<div className="hero-wordmark">
<div className="eyebrow"> TRANSMISSION</div>
<div className="big">denpa.fm</div>
</div>
<div className="hero-tagline">
tune in.<br/>tune out.<br/>melt yr brain {'<3'}
</div>
<div className="hero-status">
<div>{fmtJpDate(clockNow)}</div>
<div>{fmtJpTime(clockNow)}</div>
<div className="live">[<span className="blink">{playing ? 'REC' : 'OFF'}</span>] {playing ? 'LIVE' : 'PAUSED'} · {listeners ?? '—'} listening</div>
</div>
</div>
<div className="hero-body">
<aside className="hero-stations">
<div className="hero-stations-label">&gt;&gt; / STATIONS</div>
{stations.map((s, i) => (
<Tape
key={s.id}
station={s}
index={i}
active={s.id === selectedId}
onSelect={setSelectedId}
listeners={s.id === selectedId ? listeners : null}
/>
))}
</aside>
<div className="hero-deck-wrap">
<audio ref={audioRef} crossOrigin="anonymous" preload="none" />
<div className="hero-deck">
<div className="deck-screen">
<div className="deck-screen-row">
<span>&gt;&gt; NOW PLAYING</span>
<span>{format === 'mp3' ? '192k MP3' : '96k OPUS'}</span>
</div>
<div className="deck-now">{now?.title || '—'}</div>
<div className="deck-artist">{now?.artist || '—'}</div>
<div className="deck-screen-row">
<span>album · {now?.album || '—'}</span>
<span>{station.tags.join(' · ')}</span>
</div>
<div className="deck-progress-row">
<span className="deck-time">{fmtMs(elapsed)}</span>
<div className="deck-progress">
{hasDur ? <div className="deck-progress-fill" style={{ width: pct + '%' }} /> : null}
</div>
<span className="deck-time">{hasDur ? fmtMs(dur) : '—'}</span>
</div>
</div>
<div className="deck-reels">
<div className={`reel ${playing ? 'spinning' : ''}`} />
<div className="reel-strip" />
<div className={`reel ${playing ? 'spinning' : ''}`} />
</div>
<Spectrum />
<div className="deck-controls">
<button className="deck-btn play" onClick={togglePlay} type="button">
{playing ? '|| PAUSE' : '>> PLAY'}
</button>
<button className="deck-btn format" data-active={format === 'mp3'} onClick={() => setFormat('mp3')} type="button">MP3</button>
<button className="deck-btn format" data-active={format === 'opus'} onClick={() => setFormat('opus')} type="button">OPUS</button>
<div className="deck-vol">
<label>VOL</label>
<input
type="range" min={0} max={1} step={0.01} value={muted ? 0 : vol}
onChange={(e) => { setVol(parseFloat(e.target.value)); setMuted(false); }}
/>
<span className="deck-vol-pct">{Math.round((muted ? 0 : vol) * 100)}%</span>
</div>
</div>
</div>
<div className="hero-footer">
<button className="share-btn" onClick={copyUrl} type="button">
{copyState === 'ok' ? '[ok] copied!' : '[ ] copy stream URL'}
</button>
<div className="ticker">
<div className="ticker-inner">
no ads · no algorithms · just signal adding a station = mkdir on storage box space=play =switch =vol m=mute
</div>
</div>
</div>
</div>
</div>
</section>
);
}

View file

@ -0,0 +1,95 @@
.hero-deck {
background: linear-gradient(180deg, var(--cream) 0%, #f5e0c4 100%);
color: var(--ink);
padding: 24px;
border: 3px solid var(--ink);
box-shadow: 8px 8px 0 var(--pink), 16px 16px 0 var(--cyan);
position: relative;
}
.hero-deck::before {
content: ""; position: absolute; inset: 5px;
border: 1px dashed #0a041044; pointer-events: none;
}
.deck-screen {
background: var(--ink); color: var(--green);
font-family: var(--f-mono); font-size: 14px;
padding: 14px 18px;
border: 2px inset var(--ink);
position: relative; overflow: hidden;
}
.deck-screen::after {
content: ""; position: absolute; inset: 0; pointer-events: none;
background: repeating-linear-gradient(0deg, rgba(94,255,155,0.08) 0 1px, transparent 1px 3px);
}
.deck-screen-row { display: flex; justify-content: space-between; opacity: 0.75; font-size: 12px; }
.deck-now {
font-family: var(--f-pixel); font-size: 28px; color: var(--cream);
line-height: 1.1; margin: 6px 0 2px;
text-shadow: 0 0 10px #5eff9b80;
}
.deck-artist { font-size: 16px; color: var(--cyan); margin-bottom: 8px; }
.deck-progress-row {
display: flex; align-items: center; gap: 10px;
margin-top: 12px;
}
.deck-time { font-size: 12px; color: var(--cyan); min-width: 36px; }
.deck-progress { flex: 1; height: 4px; background: #5eff9b22; border: 1px solid #5eff9b55; }
.deck-progress-fill { height: 100%; background: var(--green); transition: width 200ms linear; }
.deck-reels {
display: flex; align-items: center; justify-content: space-around;
gap: 14px; margin-top: 18px;
padding: 14px; background: var(--ink); border: 2px solid var(--ink);
}
.reel {
width: 110px; height: 110px; border-radius: 50%;
background:
radial-gradient(circle, var(--cream) 0 16px, transparent 16px),
conic-gradient(from 0deg, var(--plum-2) 0 25%, var(--plum) 25% 50%, var(--plum-2) 50% 75%, var(--plum) 75%);
border: 2px solid var(--cream);
position: relative;
}
.reel::before {
content: ""; position: absolute; inset: 7px; border-radius: 50%;
border: 1px dashed #fff4e833;
}
.reel.spinning { animation: spin 1.6s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.reel-strip {
flex: 1; height: 7px;
background: linear-gradient(90deg, var(--cream) 0%, #d4a578 50%, var(--cream) 100%);
border-top: 1px solid var(--ink); border-bottom: 1px solid var(--ink);
}
.deck-controls {
display: flex; align-items: center; gap: 10px; margin-top: 18px;
flex-wrap: wrap;
}
.deck-btn {
font-family: var(--f-pixel); font-size: 16px;
background: var(--pink); color: var(--cream);
border: 2px solid var(--ink); padding: 10px 14px;
cursor: pointer; box-shadow: 3px 3px 0 var(--ink);
letter-spacing: 1px;
transition: transform 100ms, box-shadow 100ms;
}
.deck-btn:hover { transform: translate(-1px,-1px); box-shadow: 4px 4px 0 var(--ink); }
.deck-btn:active { transform: translate(2px,2px); box-shadow: 1px 1px 0 var(--ink); }
.deck-btn.play { font-size: 20px; padding: 16px 24px; background: var(--cyan); color: var(--ink); }
.deck-btn.format { background: var(--cream); color: var(--ink); }
.deck-btn.format[data-active=true] { background: var(--lemon); }
.deck-vol {
flex: 1; min-width: 200px;
display: flex; align-items: center; gap: 10px;
background: var(--ink); padding: 10px 14px; border: 2px solid var(--ink);
}
.deck-vol label { font-family: var(--f-pixel); font-size: 13px; color: var(--lemon); letter-spacing: 1.5px; }
.deck-vol input { flex: 1; accent-color: var(--pink); }
.deck-vol-pct { font-family: var(--f-mono); font-size: 13px; color: var(--cyan); min-width: 38px; text-align: right; }
@media (max-width: 640px) {
.reel { width: 80px; height: 80px; }
.deck-vol { min-width: 100%; }
}

View file

@ -0,0 +1,106 @@
.topnav {
display: flex; justify-content: space-between; align-items: center;
font-family: var(--f-pixel); font-size: 13px; letter-spacing: 2px;
padding: 6px 0 18px; border-bottom: 1px dashed #ff3ea533;
margin-bottom: 24px;
flex-wrap: wrap; gap: 10px;
}
.topnav-brand { color: var(--pink); }
.topnav-links { display: flex; gap: 18px; }
.topnav-links a { color: var(--cream); }
.topnav-links a:hover { color: var(--lemon); }
.hero {
position: relative;
padding: 30px 32px 36px;
background:
radial-gradient(ellipse at 30% 0%, #ff3ea522 0%, transparent 55%),
radial-gradient(ellipse at 80% 100%, #5ef7ff1a 0%, transparent 55%),
var(--plum);
border: 2px solid var(--ink);
margin-bottom: 36px;
overflow: hidden;
}
.hero-header {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: end;
gap: 24px; margin-bottom: 22px;
}
.hero-wordmark .eyebrow {
font-family: var(--f-pixel); font-size: 16px; letter-spacing: 4px; color: var(--pink);
}
.hero-wordmark .big {
font-family: var(--f-pixel);
font-size: clamp(48px, 7vw, 88px);
line-height: 0.9; letter-spacing: 0; margin-top: 6px;
display: inline-block;
padding-right: 0.12em;
color: transparent;
background: linear-gradient(180deg, var(--cream) 0%, var(--cream) 50%, var(--pink) 50%, var(--pink) 100%);
-webkit-background-clip: text; background-clip: text;
filter: drop-shadow(0 0 8px #ff3ea580);
}
.hero-tagline {
font-family: var(--f-hand); font-size: 26px;
color: var(--cream); transform: rotate(-2deg); line-height: 1.05;
text-align: center;
}
.hero-status {
font-family: var(--f-mono); font-size: 13px;
color: var(--cyan); text-align: right; line-height: 1.55;
}
.hero-status .live { color: var(--pink); }
.hero-status .blink { animation: blink 1s steps(2) infinite; }
@keyframes blink { 50% { opacity: 0.15; } }
.hero-body {
display: grid;
grid-template-columns: 260px 1fr;
gap: 24px;
position: relative;
}
.hero-stations { display: flex; flex-direction: column; gap: 10px; }
.hero-stations-label {
font-family: var(--f-pixel); color: var(--lemon);
font-size: 14px; letter-spacing: 2px;
padding: 5px 10px;
background: var(--ink); border: 2px solid var(--lemon);
align-self: flex-start; transform: rotate(-2deg);
margin-bottom: 4px;
}
.hero-deck-wrap { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
.hero-footer { display: flex; gap: 12px; align-items: stretch; }
.share-btn {
font-family: var(--f-mono); font-size: 13px;
background: var(--ink); color: var(--cyan);
padding: 10px 14px; border: 1.5px dashed #5ef7ff66;
cursor: pointer; white-space: nowrap;
}
.share-btn:hover { border-style: solid; border-color: var(--cyan); }
.ticker {
flex: 1; overflow: hidden; white-space: nowrap;
background: var(--ink); padding: 10px 0;
border-top: 1px dashed #ff3ea566; border-bottom: 1px dashed #ff3ea566;
display: flex; align-items: center;
}
.ticker-inner {
display: inline-block; padding-left: 100%;
animation: marq 30s linear infinite;
color: var(--pink); font-family: var(--f-mono); font-size: 13px; letter-spacing: 1px;
}
@keyframes marq { to { transform: translateX(-100%); } }
@media (max-width: 1000px) {
.hero-body { grid-template-columns: 1fr; }
.hero-stations { display: grid; grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 640px) {
.page { padding: 14px; }
.hero { padding: 20px 16px 24px; }
.hero-header { grid-template-columns: 1fr; gap: 14px; }
.hero-tagline { text-align: left; }
.hero-status { text-align: left; }
.hero-stations { grid-template-columns: 1fr; }
}