Commit 33c7b755 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Radio tuner restyle + granular snapping dial; Rooms create-as-popup;…

Radio tuner restyle + granular snapping dial; Rooms create-as-popup; live-broadcast playback semantics

- RadioTuner.tsx restyled as a lit console instead of a flat control strip.
- Rooms' always-visible create form is now a button opening CreateRoomModal,
  matching every other modal's chrome in this app.
- PlayableSong gained isLive: seek() is a no-op and resuming from pause
  re-fetches live instead of replaying stale audio frozen at the pause point.
  FullPlayer shows a LIVE badge instead of a scrub bar and disables
  Shuffle/Previous/Repeat for live content.
- Replaced the native tuning <input type="range"> with a custom pointer- and
  keyboard-driven dial: native range sensitivity is fixed to
  element-width/(max-min) with no way to slow it down, so dragging now reads
  raw pixel deltas against a fixed step instead. The dial snaps onto any
  station within the backend's own 0.3 tuning epsilon, with tick marks
  showing where each station sits.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 0908e9d2
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'
import { X } from 'lucide-react'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { LocationPicker } from './LocationPicker'
import { createRoom, type LiveRoom } from '../api/social'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
import { useMountTransition } from '../hooks/useMountTransition'
const ANIMATION_MS = 300
interface CreateRoomModalProps {
onCreated: (room: LiveRoom) => void
onClose: () => void
}
/** Popup for starting a new room - pulled out of Rooms.tsx's always-visible inline form
* (2026-10-12) behind a single "Create a room" button, so the room list reads as the primary
* view and creating one is a deliberate action. Same modal chrome as AddToPlaylistModal/
* SongPicker (mobile bottom sheet, desktop centered card, Escape/backdrop/system-back all
* close it) rather than inventing a new pattern. */
export function CreateRoomModal({ onCreated, onClose }: CreateRoomModalProps) {
const [name, setName] = useState('')
const [pin, setPin] = useState('')
const [tieToLocation, setTieToLocation] = useState(false)
const [latitude, setLatitude] = useState<number | null>(null)
const [longitude, setLongitude] = useState<number | null>(null)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
// The caller owns whether this exists in the tree at all, so calling the real onClose prop
// immediately would unmount it before its own exit transition could play - same requestClose
// indirection as every other modal in this app (see AddToPlaylistModal for the full reasoning).
const [closing, setClosing] = useState(false)
const { mounted, visible } = useMountTransition(!closing, ANIMATION_MS)
const closedRef = useRef(false)
const requestClose = useCallback(() => setClosing(true), [])
useEffect(() => {
if (!mounted && !closedRef.current) {
closedRef.current = true
onClose()
}
}, [mounted, onClose])
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') requestClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [requestClose])
useBackButtonClose(true, requestClose)
async function handleSubmit(e: FormEvent) {
e.preventDefault()
if (!name.trim()) return
setSubmitting(true)
setError(null)
try {
const room = await createRoom(name.trim(), {
pin: pin || undefined,
latitude: tieToLocation && latitude !== null ? latitude : undefined,
longitude: tieToLocation && longitude !== null ? longitude : undefined,
})
// Jumping straight into the new room replaces this whole page's content anyway, so the
// modal is dropped immediately rather than playing its own exit animation first.
onCreated(room)
} catch {
setError('Could not create this room. Please try again.')
setSubmitting(false)
}
}
if (!mounted) return null
return (
<div
role="dialog"
aria-modal="true"
aria-label="Create a room"
className={`fixed inset-0 z-40 flex items-end justify-center bg-black/60 transition-opacity duration-300 ease-out motion-reduce:transition-none sm:items-center ${
visible ? 'opacity-100' : 'opacity-0'
}`}
onClick={requestClose}
>
<div
className={`flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-t-2xl bg-surface-container will-change-transform transition-all duration-300 ease-out motion-reduce:transition-none sm:rounded-2xl ${
visible ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0 sm:translate-y-4'
}`}
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-outline-variant px-4 py-3">
<p className="text-sm font-semibold text-white">Create a room</p>
<button
onClick={requestClose}
aria-label="Close"
className="shrink-0 rounded-full p-1.5 text-on-surface-variant transition-colors hover:bg-surface-container-high hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<X size={18} strokeWidth={2} />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-3 overflow-y-auto px-4 py-4">
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Room name" autoFocus />
<Input
value={pin}
onChange={(e) => setPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
placeholder="PIN (optional)"
inputMode="numeric"
/>
<label className="flex items-center gap-2 text-sm text-on-surface-variant">
<input type="checkbox" checked={tieToLocation} onChange={(e) => setTieToLocation(e.target.checked)} />
Tie to a real-world location (lets others find it on the map)
</label>
{tieToLocation && (
<LocationPicker
latitude={latitude}
longitude={longitude}
onChange={(lat, lon) => {
setLatitude(lat)
setLongitude(lon)
}}
/>
)}
{error && <p className="text-sm text-error">{error}</p>}
<Button type="submit" disabled={submitting || !name.trim()} className="w-full">
{submitting ? 'Starting…' : 'Start'}
</Button>
</form>
</div>
</div>
)
}
......@@ -391,6 +391,20 @@ export function FullPlayer() {
</p>
</div>
{currentSong.isLive ? (
// Live content (Radio) has no stable timeline - the position behind the stream
// keeps moving in real time whether or not anyone's listening, so a scrub bar
// would only ever be able to lie about "where" playback is. A plain indicator
// replaces it instead of a disabled-looking range input.
<div className="flex items-center justify-center gap-1.5 py-[7px]">
<span className="relative flex h-2 w-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />
</span>
<span className="text-xs font-bold uppercase tracking-widest text-primary">Live</span>
</div>
) : (
<>
<input
type="range"
min={0}
......@@ -417,14 +431,17 @@ export function FullPlayer() {
</>
)}
</div>
</>
)}
<div className="mt-5 flex items-center justify-between">
<button
onClick={toggleShuffle}
disabled={currentSong.isLive}
tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label="Shuffle"
aria-pressed={isShuffled}
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30 ${
isShuffled ? 'text-primary' : 'text-on-surface-variant hover:text-on-surface'
}`}
>
......@@ -434,9 +451,10 @@ export function FullPlayer() {
<div className="flex items-center gap-8">
<button
onClick={previous}
disabled={currentSong.isLive}
tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label="Previous"
className="rounded-full p-1 text-on-surface transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
className="rounded-full p-1 text-on-surface transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30"
>
<SkipBack size={26} strokeWidth={2} fill="currentColor" />
</button>
......@@ -468,10 +486,11 @@ export function FullPlayer() {
<button
onClick={cycleRepeat}
disabled={currentSong.isLive}
tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label={`Repeat: ${repeatMode}`}
aria-pressed={repeatMode !== 'off'}
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30 ${
repeatMode !== 'off' ? 'text-primary' : 'text-on-surface-variant hover:text-on-surface'
}`}
>
......@@ -591,6 +610,16 @@ export function FullPlayer() {
className="relative mx-auto w-full max-w-md shrink-0 px-6 pb-4 pt-2"
style={{ paddingBottom: 'calc(env(safe-area-inset-bottom) + 1rem)' }}
>
{currentSong.isLive ? (
<div className="mb-2 flex items-center justify-center gap-1.5">
<span className="relative flex h-2 w-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />
</span>
<span className="text-xs font-bold uppercase tracking-widest text-primary">Live</span>
</div>
) : (
<>
<input
type="range"
min={0}
......@@ -611,12 +640,15 @@ export function FullPlayer() {
<span>{formatTime(progress)}</span>
<span>{formatTime(duration)}</span>
</div>
</>
)}
<div className="flex items-center justify-center gap-8">
<button
onClick={previous}
disabled={currentSong.isLive}
tabIndex={lyricsOpen ? 0 : -1}
aria-label="Previous"
className="rounded-full p-1 text-on-surface transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
className="rounded-full p-1 text-on-surface transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-30"
>
<SkipBack size={22} strokeWidth={2} fill="currentColor" />
</button>
......
import { render, screen, waitFor } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RadioTuner } from './RadioTuner'
......@@ -79,7 +79,7 @@ describe('RadioTuner', () => {
renderTuner()
// The default dial (100.0) is already within epsilon of the fixture station's 100.0.
expect(await screen.findByText('Night Drive FM')).toBeInTheDocument()
expect(await screen.findByText(/Night Drive FM/)).toBeInTheDocument()
expect(await screen.findByText('Midnight Run')).toBeInTheDocument()
expect(screen.getByText('The Band')).toBeInTheDocument()
})
......@@ -96,7 +96,7 @@ describe('RadioTuner', () => {
const browse = vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
renderTuner()
await screen.findByText('Night Drive FM')
await screen.findByText(/Night Drive FM/)
browse.mockResolvedValue([])
await userEvent.click(screen.getByRole('button', { name: 'SF' }))
......@@ -131,6 +131,40 @@ describe('RadioTuner', () => {
await waitFor(() => expect(favorite).toHaveBeenCalledWith(999))
})
it('steps the frequency with arrow keys without overshooting granularity', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([])
renderTuner()
const dial = await screen.findByLabelText('Tuning dial')
dial.focus()
fireEvent.keyDown(dial, { key: 'ArrowRight' })
expect(dial).toHaveAttribute('aria-valuenow', '100.1')
fireEvent.keyDown(dial, { key: 'ArrowLeft' })
fireEvent.keyDown(dial, { key: 'ArrowLeft' })
expect(dial).toHaveAttribute('aria-valuenow', '99.9')
fireEvent.keyDown(dial, { key: 'ArrowRight', shiftKey: true })
expect(dial).toHaveAttribute('aria-valuenow', '100.9')
})
it('snaps onto a nearby station once a drag lands within the tuning epsilon', async () => {
const otherBandStation: Radio = { ...STATION, id: 11, frequency: 120.0 }
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([otherBandStation])
renderTuner()
const dial = await screen.findByLabelText('Tuning dial')
// Starts at the default 100.0 - not within epsilon of the 120.0 station yet.
expect(dial).toHaveAttribute('aria-valuenow', '100')
fireEvent.pointerDown(dial, { pointerId: 1, clientX: 0 })
// 20.2 frequency units of drag at DIAL_PIXELS_PER_UNIT=14 - lands at 120.2, within the
// 0.3 epsilon of the fixture station's 120.0 but not exactly on it.
fireEvent.pointerMove(dial, { pointerId: 1, clientX: 20.2 * 14 })
fireEvent.pointerUp(dial, { pointerId: 1 })
expect(dial).toHaveAttribute('aria-valuenow', '120')
})
it('opens the add-to-playlist flow for the now-playing song', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
......
import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'
import { Heart, ListPlus, Music2, Pause, Play, RadioTower } from 'lucide-react'
import { Button } from './ui/Button'
import { EmptyState } from './ui/EmptyState'
import { browseRadios, fetchRadioStreamUrl, getNowPlaying, type NowPlaying, type Radio, type RadioBand } from '../api/radio'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useClaimThenAct, type ClaimableSong } from '../hooks/useClaimThenAct'
......@@ -9,6 +8,22 @@ import { useClaimThenAct, type ClaimableSong } from '../hooks/useClaimThenAct'
const BANDS: RadioBand[] = ['SM', 'SF', 'SR']
const FREQUENCY_MIN = 50.0
const FREQUENCY_MAX = 200.0
// Pixels of horizontal drag needed per 1.0 frequency unit. A plain native range input maps
// its full rendered width to the whole 150-unit span - on a ~400px-wide card that's roughly
// 0.4 units per pixel, so overshooting a station by a hair on a real touch drag was nearly
// unavoidable. This custom dial reads raw pointer-movement pixels instead of relying on the
// browser's width-based mapping, so sensitivity is independent of layout and can be tuned
// directly - deliberately coarser (dragging the full visible width now only covers a few
// units, not the whole band) in exchange for being able to nudge onto a specific frequency.
const DIAL_PIXELS_PER_UNIT = 14
// One accent hue per band, so the console actually reads as "tuned to something" rather than
// every band looking identical - reuses the same accent hues mapTheme.ts already established
// for soundmark tiers (indigo/amber), plus a new emerald for the third band.
const BAND_COLORS: Record<RadioBand, string> = {
SM: '#818cf8',
SF: '#fbbf24',
SR: '#34d399',
}
// Mirrors the backend's own TUNING_LOCK_EPSILON (radio.py) exactly - this is the client-side
// half of the same "close enough to count as tuned in" tolerance, not an independent choice.
const TUNING_LOCK_EPSILON = 0.3
......@@ -34,8 +49,10 @@ export function RadioTuner({ onAddToPlaylist }: RadioTunerProps) {
const [stations, setStations] = useState<Radio[]>([])
const [coords, setCoords] = useState<{ lat: number; lon: number } | null>(null)
const [nowPlaying, setNowPlaying] = useState<NowPlaying | null>(null)
const { currentSong, isPlaying, duration, toggle, seek } = usePlayer()
const seekedForIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, toggle } = usePlayer()
// Not state, same reasoning as useSwipeAction - only exists to reject a second simultaneous
// pointer and to remember where this particular drag started.
const dragRef = useRef<{ pointerId: number; startX: number; startFrequency: number } | null>(null)
// Best-effort geolocation so local-scope stations show up in browse - silently skipped if
// denied/unavailable/insecure, same posture as every other optional-location feature here.
......@@ -106,6 +123,10 @@ export function RadioTuner({ onAddToPlaylist }: RadioTunerProps) {
title: np.song?.title ?? station.name,
artist: np.song?.artist ?? 'Live radio',
coverart: np.artwork_url,
// The stream itself already starts at the live position (radio.py computes it fresh
// per request and seeks there server-side) - isLive just tells the player there's no
// timeline here to expose scrubbing on or to resume stale paused audio from.
isLive: true,
streamUrl: () => fetchRadioStreamUrl(station.id),
}
}
......@@ -115,79 +136,200 @@ export function RadioTuner({ onAddToPlaylist }: RadioTunerProps) {
toggle(toPlayable(lockedStation, nowPlaying))
}
// Join mid-song: once this exact station's stream has loaded (duration known), seek once to
// the server-computed offset - otherwise every listener who tunes in would start the current
// track from 0 regardless of how far into the loop it actually is.
useEffect(() => {
if (stationPlayableId === null || !nowPlaying?.on_air || !nowPlaying.offset_seconds) return
if (currentSong?.id !== stationPlayableId || !duration) return
if (seekedForIdRef.current === stationPlayableId) return
seek(nowPlaying.offset_seconds)
seekedForIdRef.current = stationPlayableId
}, [currentSong?.id, duration, stationPlayableId, nowPlaying, seek])
function clampFrequency(value: number): number {
return Math.min(FREQUENCY_MAX, Math.max(FREQUENCY_MIN, value))
}
/** Once a dragged or keyboard-stepped value lands within TUNING_LOCK_EPSILON of a station
* actually on this band, snaps exactly onto that station's frequency - the "index that snaps
* to places" the dial's tick marks (below) visually promise, so landing precisely on a
* station doesn't require a pixel-perfect drag. */
function snapToStation(value: number): number {
const nearby = stations.find((s) => Math.abs(s.frequency - value) < TUNING_LOCK_EPSILON)
return nearby ? nearby.frequency : Math.round(value * 10) / 10
}
function handleDialPointerDown(e: ReactPointerEvent<HTMLDivElement>) {
if (e.pointerType === 'mouse' && e.button !== 0) return
dragRef.current = { pointerId: e.pointerId, startX: e.clientX, startFrequency: frequency }
}
function handleDialPointerMove(e: ReactPointerEvent<HTMLDivElement>) {
const drag = dragRef.current
if (!drag || drag.pointerId !== e.pointerId) return
const deltaX = e.clientX - drag.startX
// Same "only capture once a real drag is detected" guard as useSwipeAction - capturing on
// pointerdown unconditionally would redirect the browser's synthesized click away from
// whatever's actually under the finger for a plain tap.
if (Math.abs(deltaX) > 4 && !e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.setPointerCapture(e.pointerId)
}
const raw = clampFrequency(drag.startFrequency + deltaX / DIAL_PIXELS_PER_UNIT)
setFrequency(snapToStation(raw))
}
function handleDialPointerUp(e: ReactPointerEvent<HTMLDivElement>) {
if (dragRef.current?.pointerId !== e.pointerId) return
dragRef.current = null
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
}
function handleDialKeyDown(e: ReactKeyboardEvent<HTMLDivElement>) {
const step = e.shiftKey ? 1.0 : 0.1
if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
e.preventDefault()
setFrequency((f) => snapToStation(clampFrequency(f + step)))
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
e.preventDefault()
setFrequency((f) => snapToStation(clampFrequency(f - step)))
} else if (e.key === 'Home') {
e.preventDefault()
setFrequency(FREQUENCY_MIN)
} else if (e.key === 'End') {
e.preventDefault()
setFrequency(FREQUENCY_MAX)
}
}
const accent = BAND_COLORS[band]
const dialPercent = ((frequency - FREQUENCY_MIN) / (FREQUENCY_MAX - FREQUENCY_MIN)) * 100
return (
<div>
{/* The console: band selector + LED-style frequency readout + dial, all tinted by the
selected band's accent so switching bands actually reads as switching something,
not just relabeling the same flat control. */}
<div className="relative overflow-hidden rounded-2xl border border-outline-variant bg-surface-container p-5">
<div
className="pointer-events-none absolute -top-20 left-1/2 h-40 w-64 -translate-x-1/2 rounded-full opacity-25 blur-3xl transition-colors duration-500"
style={{ backgroundColor: accent }}
/>
<div className="relative">
<div className="mb-4 flex gap-2">
{BANDS.map((b) => (
{BANDS.map((b) => {
const isActive = band === b
return (
<button
key={b}
onClick={() => setBand(b)}
aria-pressed={band === b}
className={`flex-1 rounded-full py-2 text-sm font-semibold transition-colors duration-150 ${
band === b
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
aria-pressed={isActive}
className={`flex-1 rounded-full py-2 text-sm font-bold tracking-wide transition-all duration-150 ${
isActive
? 'text-[#0a0a0a]'
: 'border border-outline-variant bg-surface-container-high text-on-surface-variant hover:text-on-surface'
}`}
style={isActive ? { backgroundColor: BAND_COLORS[b], boxShadow: `0 0 18px ${BAND_COLORS[b]}66` } : undefined}
>
{b}
</button>
))}
)
})}
</div>
<div className="mb-4 flex items-center justify-center gap-3 rounded-xl bg-black/30 py-5">
<span
className="rounded-md px-2 py-0.5 text-xs font-bold tracking-widest transition-colors duration-500"
style={{ backgroundColor: `${accent}33`, color: accent }}
>
{band}
</span>
<span
className="font-mono text-4xl font-bold tabular-nums tracking-tight text-on-surface transition-[text-shadow] duration-500"
style={{ textShadow: `0 0 18px ${accent}66` }}
>
{frequency.toFixed(1)}
</span>
<span className="text-xs font-medium text-on-surface-variant">MHz</span>
</div>
<input
type="range"
min={FREQUENCY_MIN}
max={FREQUENCY_MAX}
step={0.1}
value={frequency}
onChange={(e) => setFrequency(Number(e.target.value))}
<div
role="slider"
tabIndex={0}
aria-label="Tuning dial"
className="seek-range w-full"
aria-valuemin={FREQUENCY_MIN}
aria-valuemax={FREQUENCY_MAX}
aria-valuenow={frequency}
aria-valuetext={`${band} ${frequency.toFixed(1)} MHz`}
onPointerDown={handleDialPointerDown}
onPointerMove={handleDialPointerMove}
onPointerUp={handleDialPointerUp}
onPointerCancel={handleDialPointerUp}
onKeyDown={handleDialKeyDown}
className="relative h-7 w-full cursor-grab touch-none select-none rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary active:cursor-grabbing"
>
<div
className="pointer-events-none absolute left-0 top-1/2 h-1.5 w-full -translate-y-1/2 rounded-full bg-surface-container-high"
style={{
background: `linear-gradient(to right, var(--color-primary) ${((frequency - FREQUENCY_MIN) / (FREQUENCY_MAX - FREQUENCY_MIN)) * 100}%, var(--color-surface-container-high) ${((frequency - FREQUENCY_MIN) / (FREQUENCY_MAX - FREQUENCY_MIN)) * 100}%)`,
backgroundImage: `linear-gradient(to right, ${accent}aa ${dialPercent}%, transparent ${dialPercent}%), repeating-linear-gradient(to right, color-mix(in srgb, white 20%, transparent) 0 1px, transparent 1px 10px)`,
}}
/>
<p className="mt-1 text-center text-2xl font-semibold tabular-nums text-on-surface">
{band} {frequency.toFixed(1)}
</p>
{/* Station tick marks - shows exactly where a station sits on the dial, and is
what dragging/keyboard-stepping above snaps onto once close enough. */}
{stations.map((s) => (
<div
key={s.id}
className="pointer-events-none absolute top-1/2 h-3 w-0.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-white/70"
style={{ left: `${((s.frequency - FREQUENCY_MIN) / (FREQUENCY_MAX - FREQUENCY_MIN)) * 100}%` }}
/>
))}
<div
className="pointer-events-none absolute top-1/2 h-6 w-6 -translate-x-1/2 -translate-y-1/2 rounded-full border-[3px] bg-white shadow-md"
style={{ left: `${dialPercent}%`, borderColor: accent }}
/>
</div>
<div className="mt-1.5 flex justify-between text-[10px] font-medium text-outline">
<span>{FREQUENCY_MIN.toFixed(0)}</span>
<span>{FREQUENCY_MAX.toFixed(0)}</span>
</div>
</div>
</div>
<div className="mt-6">
{!lockedStation && <EmptyState icon={RadioTower} message="No station here - keep tuning the dial." />}
<div className="mt-5">
{!lockedStation && (
<div className="flex flex-col items-center gap-2 rounded-xl border border-dashed border-outline-variant py-12 text-center">
<RadioTower size={26} strokeWidth={1.5} className="text-outline" />
<p className="max-w-xs text-sm text-outline">No station here - keep tuning the dial.</p>
</div>
)}
{lockedStation && (
<div className="rounded-xl border border-outline-variant bg-surface-container p-4">
<p className="mb-3 truncate text-sm font-semibold text-on-surface">{lockedStation.name}</p>
<div className="overflow-hidden rounded-xl border border-outline-variant bg-surface-container">
<div className="flex items-center gap-2 border-b border-outline-variant/60 px-4 py-2.5">
{nowPlayingSong && (
<span className="relative flex h-2 w-2 shrink-0">
<span
className="absolute inline-flex h-full w-full animate-ping rounded-full opacity-75"
style={{ backgroundColor: accent }}
/>
<span className="relative inline-flex h-2 w-2 rounded-full" style={{ backgroundColor: accent }} />
</span>
)}
<p className="truncate text-xs font-semibold uppercase tracking-wide text-on-surface-variant">
{nowPlayingSong ? 'On air' : 'Off air'} · {lockedStation.name}
</p>
</div>
{nowPlayingSong ? (
<div className="flex items-center gap-3">
<div className="h-14 w-14 shrink-0 overflow-hidden rounded-lg bg-surface-container-high">
<div className="flex items-center gap-4 p-4">
<div
className="h-20 w-20 shrink-0 overflow-hidden rounded-lg bg-surface-container-high"
style={{ boxShadow: `0 6px 20px -4px ${accent}55` }}
>
{nowPlaying?.artwork_url ? (
<img src={nowPlaying.artwork_url} alt="" className="h-full w-full object-cover" />
) : (
<div className="flex h-full w-full items-center justify-center text-on-surface-variant">
<Music2 size={20} strokeWidth={1.75} />
<Music2 size={24} strokeWidth={1.75} />
</div>
)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-on-surface">{nowPlayingSong.title}</p>
<p className="truncate text-lg font-semibold text-on-surface">{nowPlayingSong.title}</p>
<p className="truncate text-sm text-on-surface-variant">{nowPlayingSong.artist}</p>
{error && <p className="mt-0.5 truncate text-xs text-error">{error}</p>}
</div>
<Button variant="primary" size="icon" onClick={handlePlay} aria-label={isThisPlaying ? 'Pause' : 'Play'}>
{isThisPlaying ? <Pause size={18} strokeWidth={2} fill="currentColor" /> : <Play size={18} strokeWidth={2} fill="currentColor" />}
</Button>
<div className="flex shrink-0 items-center gap-1">
<button
onClick={handleToggleFavorite}
disabled={claiming !== null}
......@@ -207,9 +349,13 @@ export function RadioTuner({ onAddToPlaylist }: RadioTunerProps) {
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
<Button variant="primary" size="icon" onClick={handlePlay} aria-label={isThisPlaying ? 'Pause' : 'Play'}>
{isThisPlaying ? <Pause size={18} strokeWidth={2} fill="currentColor" /> : <Play size={18} strokeWidth={2} fill="currentColor" />}
</Button>
</div>
</div>
) : (
<p className="text-sm text-on-surface-variant">This station isn't broadcasting right now.</p>
<p className="px-4 py-8 text-center text-sm text-on-surface-variant">This station isn't broadcasting right now.</p>
)}
</div>
)}
......
......@@ -22,6 +22,13 @@ export interface PlayableSong {
* browser can start playing before the whole file downloads and can seek via Range
* requests. */
streamUrl?: () => Promise<string>
/** Marks a song as a live broadcast (currently Radio only) rather than an on-demand track -
* there's no stable timeline to rewind to or pause-and-resume-later on, since the position
* behind the same URL keeps moving in real time whether or not anyone is listening. FullPlayer
* hides the seek bar for these, seek() becomes a no-op, and resuming after pause re-fetches a
* fresh stream (rejoining wherever the broadcast actually is now) instead of continuing
* stale, already-played-out audio from the moment it was paused. */
isLive?: boolean
}
export type RepeatMode = 'off' | 'all' | 'one'
......@@ -217,10 +224,13 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const seek = useCallback((time: number) => {
const audio = audioRef.current
if (!audio) return
// Live content (see PlayableSong.isLive) has no stable timeline to scrub - the position
// behind the URL keeps moving in real time regardless, so seeking would just land on
// whatever happens to be buffered rather than anything meaningful.
if (!audio || currentSong?.isLive) return
audio.currentTime = time
setProgress(time)
}, [])
}, [currentSong])
const setVolume = useCallback((next: number) => {
const clamped = Math.min(1, Math.max(0, next))
......@@ -263,6 +273,11 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
if (currentSong?.id === song.id) {
if (isPlaying) {
pause()
} else if (song.isLive) {
// Resuming live content must rejoin wherever the broadcast actually is *now*, not
// continue the stale audio frozen at the moment it was paused - that position has
// already played out in reality whether anyone was listening or not.
playSong(song)
} else {
audio.play()
setIsPlaying(true)
......
......@@ -273,6 +273,59 @@
display: none;
}
/* Radio's tuning dial (RadioTuner/RadioCreateForm) - unlike .seek-range above (a scrubber
where the thumb only appears on hover/focus), this is a literal knob the listener drags
continuously, so the thumb stays visible at all times and reads as more tactile: bigger,
with a ringed border rather than a plain dot. The track gets tick marks to read as a real
frequency dial rather than a generic slider. Thumb border color comes from --tuner-accent
(set inline per-band in RadioTuner.tsx) so it changes with the selected band; custom
properties set on the host element are visible to its own ::-webkit-slider-thumb/
::-moz-range-thumb pseudo-elements in every current browser. */
.tuner-dial {
-webkit-appearance: none;
appearance: none;
height: 6px;
border-radius: 9999px;
background-color: transparent;
}
.tuner-dial::-webkit-slider-runnable-track {
height: 6px;
border-radius: 9999px;
background-image: repeating-linear-gradient(to right, color-mix(in srgb, white 20%, transparent) 0 1px, transparent 1px 10px);
}
.tuner-dial::-moz-range-track {
height: 6px;
border-radius: 9999px;
background-color: transparent;
background-image: repeating-linear-gradient(to right, color-mix(in srgb, white 20%, transparent) 0 1px, transparent 1px 10px);
}
.tuner-dial::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 22px;
height: 22px;
margin-top: -8px;
border-radius: 9999px;
background: white;
border: 3px solid var(--tuner-accent, var(--color-primary));
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.45);
cursor: pointer;
}
.tuner-dial::-moz-range-thumb {
width: 22px;
height: 22px;
border: 3px solid var(--tuner-accent, var(--color-primary));
border-radius: 9999px;
background: white;
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.45);
cursor: pointer;
}
.tuner-dial:focus-visible {
outline: 2px solid var(--tuner-accent, var(--color-primary));
outline-offset: 4px;
border-radius: 9999px;
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.148 0.004 228.8);
......
......@@ -83,6 +83,9 @@ const BACKEND_DONE: DoneGroup[] = [
'Radio (2026-10-12): creator-run stations tuned via a literal band (SM/SF/SR) + frequency (50.0-200.0, 0.1 precision) dial, broadcasting worldwide or to a local radius, looping a queue forever. New Radio/RadioTrack tables; LibrarySong gained duration_seconds (populated at tag/upload/claim/remix time via probe_duration_seconds, pydub - lazily backfilled on first read for pre-existing rows). New /radio router: CRUD with band+frequency validation (rejects two active stations on the same band within 0.6 of each other\'s frequency - floating-point noise in that comparison was a real bug caught by a test expecting two stations exactly 0.6 apart to coexist, fixed by rounding the diff before comparing), /browse (active+on-air+geo-visible, no now-playing info so dialing through it client-side never hits the backend), /queue (owner-only add/remove/reorder), /artwork (new image upload - storage.store_image + /images static mount, the first image-upload precedent in this app).',
'The core design problem: no scheduler, no background job, no stored "current song" - compute_now_playing() is fully stateless, mapping elapsed_seconds-since-creation modulo the queue\'s total duration to a (song, offset) pair via cumulative-sum arithmetic. Verified live: two now-playing calls 2 real seconds apart advanced the reported offset by ~2s on the same track - any listener, whenever they tune in, lands on the mathematically correct position, no polling job required. Schedule ("on air" 24/7 vs a fixed daily window, including windows that wrap past midnight) is the same kind of stateless check against the current UTC minute-of-day.',
'/soundmarks/geocode and /reverse-geocode relaxed from business-admin-only to any authenticated user - RadioLocationPicker\'s address search needed them too, and there was nothing business-admin-specific about a stateless geocoder proxy in the first place.',
'Tuner restyle + Rooms create-as-popup (2026-10-12): RadioTuner.tsx redesigned as a lit console (band-colored glow, LED-style station readout) instead of its original flat layout. Rooms\' always-visible inline create form replaced with a "Create a room" button opening a new CreateRoomModal, matching every other modal\'s chrome (useMountTransition, back-button + Escape + backdrop close) rather than inventing a new pattern.',
'Radio is live broadcast, not a seekable track (2026-10-12): the backend now starts the actual MP3 stream at the live offset itself (stream_audio_from_offset, ffmpeg -ss before -i so it seeks pre-decode and -acodec copy so it never re-encodes) instead of serving from byte 0 and relying on a client-side seek() afterward - that second round trip was the real cause of the reported slow start, confirmed fixed by a regression test asserting the returned stream\'s actual duration matches the expected remaining offset, and by a live check against the running server (10s test track, stream fetched ~4s in, returned ~6-7s of audio). PlayableSong gained isLive: seek() is now a no-op for it and resuming from pause re-fetches live instead of replaying stale paused audio; FullPlayer shows a pulsing LIVE badge instead of a scrub bar, with Shuffle/Previous/Repeat disabled, consistent with there being no stable timeline to control.',
'Tuning dial: granular drag + station snapping (2026-10-12): the native <input type="range"> was replaced with a custom pointer- and keyboard-driven dial (same pointer-capture-after-movement pattern as useSwipeAction) because a native range\'s drag sensitivity is fixed to element-width/(max-min) with no way to slow it down - dragging now reads raw pixel deltas against a fixed DIAL_PIXELS_PER_UNIT instead. The dial also snaps exactly onto any station within the same 0.3 tuning epsilon the backend already locks onto, with tick marks on the track showing where each station sits.',
],
},
{
......
......@@ -117,6 +117,7 @@ describe('Rooms', () => {
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Create a room' }))
await userEvent.type(screen.getByPlaceholderText('Room name'), 'New Room')
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
......@@ -130,6 +131,7 @@ describe('Rooms', () => {
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Create a room' }))
await userEvent.type(screen.getByPlaceholderText('Room name'), 'Secret Room')
await userEvent.type(screen.getByPlaceholderText('PIN (optional)'), '1234')
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
......@@ -143,6 +145,7 @@ describe('Rooms', () => {
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Create a room' }))
await userEvent.type(screen.getByPlaceholderText('Room name'), 'Pinned Room')
await userEvent.click(screen.getByText(/Tie to a real-world location/))
await userEvent.click(screen.getByText('Set location (mock)'))
......@@ -157,8 +160,26 @@ describe('Rooms', () => {
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
await userEvent.click(screen.getByRole('button', { name: 'Create a room' }))
expect(screen.getByRole('button', { name: 'Start' })).toBeDisabled()
expect(create).not.toHaveBeenCalled()
})
it('closes the create-room popup without creating anything', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom')
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Create a room' }))
await screen.findByPlaceholderText('Room name')
await userEvent.click(screen.getByLabelText('Close'))
// The modal un-mounts a beat after its exit transition finishes (see useMountTransition),
// not synchronously on click.
await waitFor(() => expect(screen.queryByPlaceholderText('Room name')).not.toBeInTheDocument())
expect(create).not.toHaveBeenCalled()
})
......
import { useEffect, useState } from 'react'
import { ChevronRight, Lock, MapPin, Radio } from 'lucide-react'
import { ChevronRight, Lock, MapPin, Plus, Radio } from 'lucide-react'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { EmptyState } from '../components/ui/EmptyState'
import { LocationPicker } from '../components/LocationPicker'
import { CreateRoomModal } from '../components/CreateRoomModal'
import { RoomsNearbyMap } from '../components/RoomsNearbyMap'
import { ApiError } from '../api/client'
import { createRoom, getActiveRooms, getNearbyRooms, joinRoom, type LiveRoom } from '../api/social'
import { getActiveRooms, getNearbyRooms, joinRoom, type LiveRoom } from '../api/social'
import { RoomView } from '../components/RoomView'
/** Which room (by id or invite code) a PIN prompt is currently being collected for - set
......@@ -21,11 +21,7 @@ interface PendingJoin {
export function Rooms() {
const [rooms, setRooms] = useState<LiveRoom[]>([])
const [loading, setLoading] = useState(true)
const [newRoomName, setNewRoomName] = useState('')
const [newRoomPin, setNewRoomPin] = useState('')
const [tieToLocation, setTieToLocation] = useState(false)
const [newLat, setNewLat] = useState<number | null>(null)
const [newLon, setNewLon] = useState<number | null>(null)
const [creatingRoom, setCreatingRoom] = useState(false)
const [joinCode, setJoinCode] = useState('')
const [pendingJoin, setPendingJoin] = useState<PendingJoin | null>(null)
......@@ -47,19 +43,8 @@ export function Rooms() {
useEffect(refresh, [])
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newRoomName.trim()) return
const room = await createRoom(newRoomName.trim(), {
pin: newRoomPin || undefined,
latitude: tieToLocation && newLat !== null ? newLat : undefined,
longitude: tieToLocation && newLon !== null ? newLon : undefined,
})
setNewRoomName('')
setNewRoomPin('')
setTieToLocation(false)
setNewLat(null)
setNewLon(null)
function handleRoomCreated(room: LiveRoom) {
setCreatingRoom(false)
setRooms((r) => [room, ...r])
// The creator's own invite code/PIN status is shown in RoomView's header once inside -
// no separate banner needed here.
......@@ -190,26 +175,10 @@ export function Rooms() {
return (
<>
<form onSubmit={handleCreate} className="mb-4 space-y-2">
<div className="flex gap-2">
<Input value={newRoomName} onChange={(e) => setNewRoomName(e.target.value)} placeholder="Room name" />
<Input
value={newRoomPin}
onChange={(e) => setNewRoomPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
placeholder="PIN (optional)"
inputMode="numeric"
className="w-32"
/>
</div>
<label className="flex items-center gap-2 text-sm text-on-surface-variant">
<input type="checkbox" checked={tieToLocation} onChange={(e) => setTieToLocation(e.target.checked)} />
Tie to a real-world location (lets others find it on the map)
</label>
{tieToLocation && <LocationPicker latitude={newLat} longitude={newLon} onChange={(lat, lon) => { setNewLat(lat); setNewLon(lon) }} />}
<Button type="submit" className="w-full">
Start
<Button onClick={() => setCreatingRoom(true)} className="mb-4 w-full gap-1.5">
<Plus size={16} strokeWidth={2} />
Create a room
</Button>
</form>
<form onSubmit={handleJoinByCode} className="mb-4 flex gap-2">
<Input
......@@ -277,6 +246,8 @@ export function Rooms() {
</li>
))}
</ul>
{creatingRoom && <CreateRoomModal onCreated={handleRoomCreated} onClose={() => setCreatingRoom(false)} />}
</>
)
}
......@@ -38,22 +38,22 @@ describe('Social', () => {
it('shows the Rooms panel by default', async () => {
renderSocial()
expect(await screen.findByPlaceholderText('Room name')).toBeInTheDocument()
expect(await screen.findByPlaceholderText('Join by invite code')).toBeInTheDocument()
})
it('switches to the Radio panel when tapped', async () => {
renderSocial()
await screen.findByPlaceholderText('Room name')
await screen.findByPlaceholderText('Join by invite code')
await userEvent.click(screen.getByRole('button', { name: 'Radio' }))
expect(await screen.findByLabelText('Tuning dial')).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Room name')).not.toBeInTheDocument()
expect(screen.queryByPlaceholderText('Join by invite code')).not.toBeInTheDocument()
})
it('switches to the Posts panel when tapped', async () => {
renderSocial()
await screen.findByPlaceholderText('Room name')
await screen.findByPlaceholderText('Join by invite code')
await userEvent.click(screen.getByRole('button', { name: 'Posts' }))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment