Commit 0908e9d2 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Replace Channels with Radio: band+dial tuner, creator station management

Channels tab removed (zero frontend ever built for vibe sets/stories/
showcase); replaced with Radio - band pills + a real 50-200.0 tuning dial
(RadioTuner) that locks onto a station client-side using the same epsilon
as the backend, so dragging the slider never itself hits the network.
Favoriting/playlisting the now-playing song reuses useClaimThenAct,
extracted from Home's own useHomeSongPlayback since Radio's now-playing
song is always someone else's by construction - the exact case that hook
already handled. New RadioLocationPicker draws a broadcast-radius circle
sized live from the map's current zoom/pan rather than a manual number
input. Also closes the long-standing "volume control in the player" gap
(PlayerContext.volume/setVolume, persisted) - a lever Radio's live-voice
ducking will need in Phase 2.
parent b3b12fe9
import { apiFetch } from './client'
export interface Channel {
id: number
owner_id: number
name: string
description: string | null
avatar_url: string | null
created_at: string
}
export function listChannels() {
return apiFetch<Channel[]>('/channels')
}
export function createChannel(name: string, description?: string) {
return apiFetch<Channel>('/channels', {
method: 'POST',
json: { name, description: description ?? null },
})
}
export function getChannel(channelId: number) {
return apiFetch<{ channel: Channel; follower_count: number }>(`/channels/${channelId}`)
}
export function followChannel(channelId: number) {
return apiFetch(`/channels/${channelId}/follow`, { method: 'POST' })
}
export function unfollowChannel(channelId: number) {
return apiFetch(`/channels/${channelId}/unfollow`, { method: 'POST' })
}
export interface VibeSet {
id: number
channel_id: number
title: string
description: string | null
created_at: string
}
export function listVibeSets(channelId: number) {
return apiFetch<VibeSet[]>(`/channels/${channelId}/vibe-sets`)
}
export function createVibeSet(channelId: number, title: string, songIds: number[]) {
return apiFetch<VibeSet>(`/channels/${channelId}/vibe-sets`, {
method: 'POST',
json: { title, song_ids: songIds },
})
}
export interface AudioStory {
id: number
channel_id: number
song_id: number
caption: string | null
created_at: string
expires_at: string
}
export function listStories(channelId: number) {
return apiFetch<AudioStory[]>(`/channels/${channelId}/stories`)
}
export function createStory(channelId: number, songId: number, caption?: string) {
return apiFetch<AudioStory>(`/channels/${channelId}/stories`, {
method: 'POST',
json: { song_id: songId, caption: caption ?? null },
})
}
import { API_BASE_URL, apiFetch, buildStreamUrl, getAccessToken } from './client'
export type RadioBand = 'SM' | 'SF' | 'SR'
export type RadioScope = 'worldwide' | 'local'
export interface Radio {
id: number
owner_id: number
name: string
description: string | null
artwork_url: string | null
band: RadioBand
frequency: number
scope: RadioScope
latitude: number | null
longitude: number | null
radius_meters: number | null
schedule_start_minute: number | null
schedule_end_minute: number | null
is_active: boolean
created_at: string
}
/** Shape of a radio's current track - carries user_id specifically so useClaimThenAct can
* tell whether the listener already owns a copy (see radio.py's _serialize_song). */
export interface RadioSong {
id: number
user_id: number
title: string
artist: string
album: string | null
coverart: string | null
duration_seconds: number | null
}
export interface NowPlaying {
on_air: boolean
song: RadioSong | null
offset_seconds: number | null
artwork_url: string | null
}
export interface RadioQueueTrack {
track_id: number
position: number
song: RadioSong
}
export interface RadioCreateInput {
name: string
description?: string
band: RadioBand
frequency: number
scope: RadioScope
latitude?: number
longitude?: number
radius_meters?: number
schedule_start_minute?: number
schedule_end_minute?: number
}
export type RadioUpdateInput = Partial<RadioCreateInput>
export function createRadio(body: RadioCreateInput) {
return apiFetch<{ status: string; radio: Radio }>('/radio', { method: 'POST', json: body })
}
export function getMyRadios() {
return apiFetch<Radio[]>('/radio/mine')
}
export function browseRadios(params: { band?: RadioBand; lat?: number; lon?: number } = {}) {
const search = new URLSearchParams()
if (params.band) search.set('band', params.band)
if (params.lat !== undefined) search.set('lat', String(params.lat))
if (params.lon !== undefined) search.set('lon', String(params.lon))
const query = search.toString()
return apiFetch<Radio[]>(`/radio/browse${query ? `?${query}` : ''}`)
}
export function getRadio(radioId: number) {
return apiFetch<{ status: string; radio: Radio }>(`/radio/${radioId}`)
}
export function updateRadio(radioId: number, body: RadioUpdateInput) {
return apiFetch<{ status: string; radio: Radio }>(`/radio/${radioId}`, { method: 'PATCH', json: body })
}
export function deleteRadio(radioId: number) {
return apiFetch<{ status: string }>(`/radio/${radioId}`, { method: 'DELETE' })
}
export function getNowPlaying(radioId: number) {
return apiFetch<NowPlaying>(`/radio/${radioId}/now-playing`)
}
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL that always
* re-resolves to whatever's actually on now (see buildStreamUrl for why this is a direct URL
* rather than a blob fetch). */
export async function fetchRadioStreamUrl(radioId: number): Promise<string> {
return buildStreamUrl(`/radio/${radioId}/stream`)
}
export function getQueue(radioId: number) {
return apiFetch<RadioQueueTrack[]>(`/radio/${radioId}/queue`)
}
export function addToQueue(radioId: number, songId: number) {
return apiFetch<{ status: string; track_id: number; position: number }>(`/radio/${radioId}/queue`, {
method: 'POST',
json: { song_id: songId },
})
}
export function removeFromQueue(radioId: number, trackId: number) {
return apiFetch<{ status: string }>(`/radio/${radioId}/queue/${trackId}`, { method: 'DELETE' })
}
export function reorderQueue(radioId: number, trackIds: number[]) {
return apiFetch<{ status: string }>(`/radio/${radioId}/queue/reorder`, { method: 'PUT', json: { track_ids: trackIds } })
}
/** Same XHR-for-upload-progress pattern as music.ts's uploadDirect - fetch() has no
* onUploadProgress equivalent, so byte-level progress needs XMLHttpRequest. */
export function uploadRadioArtwork(radioId: number, file: File, onProgress?: (percent: number) => void): Promise<{ status: string; radio: Radio }> {
return new Promise((resolve, reject) => {
const token = getAccessToken()
const body = new FormData()
body.append('file', file)
const xhr = new XMLHttpRequest()
xhr.open('POST', `${API_BASE_URL}/radio/${radioId}/artwork`)
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && onProgress) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () => {
let parsed: unknown = null
try {
parsed = JSON.parse(xhr.responseText)
} catch {
// non-JSON response body, parsed stays null
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(parsed as { status: string; radio: Radio })
} else {
const detail = (parsed as { detail?: string } | null)?.detail
reject(new Error(detail ?? `Upload failed (${xhr.status})`))
}
}
xhr.onerror = () => reject(new Error('Network error during upload'))
xhr.send(body)
})
}
......@@ -14,6 +14,9 @@ import {
Shuffle,
SkipBack,
SkipForward,
Volume1,
Volume2,
VolumeX,
} from 'lucide-react'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { getLyrics } from '../api/library'
......@@ -53,6 +56,8 @@ export function FullPlayer() {
hasNext,
isShuffled,
repeatMode,
volume,
setVolume,
toggle,
next,
previous,
......@@ -221,6 +226,7 @@ export function FullPlayer() {
const pct = duration > 0 ? Math.min(100, (progress / duration) * 100) : 0
const RepeatIcon = repeatMode === 'one' ? Repeat1 : Repeat
const VolumeIcon = volume === 0 ? VolumeX : volume < 0.5 ? Volume1 : Volume2
// The live synced line (once one is active) is what makes this feel like Spotify's actual
// current pattern - a snippet that plays with no tap needed, not a static first line behind a
// toggle. Before the first synced timestamp, or for a song with only plain (unsynced) lyrics,
......@@ -472,6 +478,31 @@ export function FullPlayer() {
<RepeatIcon size={18} strokeWidth={2} />
</button>
</div>
<div className="mt-5 flex items-center gap-3">
<button
onClick={() => setVolume(volume > 0 ? 0 : 1)}
tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label={volume > 0 ? 'Mute' : 'Unmute'}
className="shrink-0 rounded-full p-1 text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<VolumeIcon size={18} strokeWidth={2} />
</button>
<input
type="range"
min={0}
max={1}
step={0.01}
value={volume}
onChange={(e) => setVolume(Number(e.target.value))}
tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label="Volume"
className="seek-range w-full"
style={{
background: `linear-gradient(to right, var(--color-primary) ${volume * 100}%, var(--color-surface-container-high) ${volume * 100}%)`,
}}
/>
</div>
</div>
</div>
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RadioCreateForm } from './RadioCreateForm'
import * as radioApi from '../api/radio'
import type { Radio } from '../api/radio'
// RadioLocationPicker renders a real Leaflet map, covered directly by its own test file - here
// it's stubbed to its essential contract, same pattern Rooms.test.tsx uses for LocationPicker.
vi.mock('./RadioLocationPicker', () => ({
RadioLocationPicker: ({ onChange, onRadiusChange }: { onChange: (lat: number, lon: number) => void; onRadiusChange: (m: number) => void }) => (
<button type="button" onClick={() => { onChange(12.5, 45.5); onRadiusChange(5000) }}>
Place station (mock)
</button>
),
}))
const CREATED: Radio = {
id: 9,
owner_id: 1,
name: 'Night Drive FM',
description: null,
artwork_url: null,
band: 'SM',
frequency: 100.0,
scope: 'worldwide',
latitude: null,
longitude: null,
radius_meters: null,
schedule_start_minute: null,
schedule_end_minute: null,
is_active: true,
created_at: '2026-01-01T00:00:00Z',
}
describe('RadioCreateForm', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('disables submit until a name is entered', async () => {
render(<RadioCreateForm onCreated={vi.fn()} />)
expect(screen.getByRole('button', { name: 'Start broadcasting' })).toBeDisabled()
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Night Drive FM')
expect(screen.getByRole('button', { name: 'Start broadcasting' })).toBeEnabled()
})
it('creates a worldwide station with the selected band and frequency', async () => {
const create = vi.spyOn(radioApi, 'createRadio').mockResolvedValue({ status: 'success', radio: CREATED })
const onCreated = vi.fn()
render(<RadioCreateForm onCreated={onCreated} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Night Drive FM')
await userEvent.click(screen.getByRole('button', { name: 'SF' }))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
await waitFor(() =>
expect(create).toHaveBeenCalledWith(
expect.objectContaining({ name: 'Night Drive FM', band: 'SF', scope: 'worldwide', schedule_start_minute: undefined, schedule_end_minute: undefined }),
),
)
expect(onCreated).toHaveBeenCalledWith(CREATED)
})
it('requires a placed pin before creating a local station', async () => {
const create = vi.spyOn(radioApi, 'createRadio')
render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station')
await userEvent.click(screen.getByRole('button', { name: 'Local' }))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
expect(await screen.findByText(/Place your station on the map/)).toBeInTheDocument()
expect(create).not.toHaveBeenCalled()
})
it('creates a local station once the map pin and radius are set', async () => {
const create = vi.spyOn(radioApi, 'createRadio').mockResolvedValue({ status: 'success', radio: CREATED })
render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station')
await userEvent.click(screen.getByRole('button', { name: 'Local' }))
await userEvent.click(screen.getByText('Place station (mock)'))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
await waitFor(() =>
expect(create).toHaveBeenCalledWith(
expect.objectContaining({ scope: 'local', latitude: 12.5, longitude: 45.5, radius_meters: 5000 }),
),
)
})
it('sends a fixed schedule window only when 24/7 is unchecked', async () => {
const create = vi.spyOn(radioApi, 'createRadio').mockResolvedValue({ status: 'success', radio: CREATED })
render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Scheduled Station')
await userEvent.click(screen.getByText('Broadcast 24/7'))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
await waitFor(() => expect(create).toHaveBeenCalled())
const body = create.mock.calls[0][0]
expect(body.schedule_start_minute).not.toBeUndefined()
expect(body.schedule_end_minute).not.toBeUndefined()
})
it('shows an error message when creation fails', async () => {
vi.spyOn(radioApi, 'createRadio').mockRejectedValue(new Error('nope'))
render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Night Drive FM')
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
expect(await screen.findByText('Could not create this station.')).toBeInTheDocument()
})
})
import { useState, type FormEvent } from 'react'
import { Button } from './ui/Button'
import { Input, Textarea } from './ui/Input'
import { RadioLocationPicker } from './RadioLocationPicker'
import { createRadio, type Radio, type RadioBand, type RadioScope } from '../api/radio'
import { ApiError } from '../api/client'
import { localTimeToUtcMinute } from '../lib/radioSchedule'
const BANDS: RadioBand[] = ['SM', 'SF', 'SR']
const FREQUENCY_MIN = 50.0
const FREQUENCY_MAX = 200.0
interface RadioCreateFormProps {
onCreated: (radio: Radio) => void
}
export function RadioCreateForm({ onCreated }: RadioCreateFormProps) {
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [band, setBand] = useState<RadioBand>('SM')
const [frequency, setFrequency] = useState(100.0)
const [scope, setScope] = useState<RadioScope>('worldwide')
const [latitude, setLatitude] = useState<number | null>(null)
const [longitude, setLongitude] = useState<number | null>(null)
const [radiusMeters, setRadiusMeters] = useState<number | null>(null)
const [alwaysOn, setAlwaysOn] = useState(true)
const [startTime, setStartTime] = useState('09:00')
const [endTime, setEndTime] = useState('17:00')
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSubmit(e: FormEvent) {
e.preventDefault()
if (!name.trim()) return
if (scope === 'local' && (latitude === null || longitude === null || radiusMeters === null)) {
setError('Place your station on the map to set its broadcast area.')
return
}
setSubmitting(true)
setError(null)
try {
const { radio } = await createRadio({
name: name.trim(),
description: description.trim() || undefined,
band,
frequency,
scope,
latitude: scope === 'local' ? latitude! : undefined,
longitude: scope === 'local' ? longitude! : undefined,
radius_meters: scope === 'local' ? radiusMeters! : undefined,
schedule_start_minute: alwaysOn ? undefined : localTimeToUtcMinute(startTime),
schedule_end_minute: alwaysOn ? undefined : localTimeToUtcMinute(endTime),
})
onCreated(radio)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Could not create this station.')
} finally {
setSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Station name" />
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description (optional)" rows={2} />
<div>
<p className="mb-1.5 text-xs font-medium text-on-surface-variant">Band</p>
<div className="flex gap-2">
{BANDS.map((b) => (
<button
key={b}
type="button"
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'
}`}
>
{b}
</button>
))}
</div>
</div>
<div>
<p className="mb-1.5 text-xs font-medium text-on-surface-variant">Frequency</p>
<input
type="range"
min={FREQUENCY_MIN}
max={FREQUENCY_MAX}
step={0.1}
value={frequency}
onChange={(e) => setFrequency(Number(e.target.value))}
aria-label="Frequency"
className="seek-range w-full"
/>
<p className="text-center text-sm tabular-nums text-on-surface-variant">
{band} {frequency.toFixed(1)}
</p>
</div>
<div>
<p className="mb-1.5 text-xs font-medium text-on-surface-variant">Reach</p>
<div className="flex gap-2">
<button
type="button"
onClick={() => setScope('worldwide')}
aria-pressed={scope === 'worldwide'}
className={`flex-1 rounded-full py-2 text-sm font-semibold transition-colors duration-150 ${
scope === 'worldwide'
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
}`}
>
Worldwide
</button>
<button
type="button"
onClick={() => setScope('local')}
aria-pressed={scope === 'local'}
className={`flex-1 rounded-full py-2 text-sm font-semibold transition-colors duration-150 ${
scope === 'local'
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
}`}
>
Local
</button>
</div>
</div>
{scope === 'local' && (
<RadioLocationPicker
latitude={latitude}
longitude={longitude}
radiusMeters={radiusMeters}
onChange={(lat, lon) => {
setLatitude(lat)
setLongitude(lon)
}}
onRadiusChange={setRadiusMeters}
/>
)}
<label className="flex items-center gap-2 text-sm text-on-surface-variant">
<input type="checkbox" checked={alwaysOn} onChange={(e) => setAlwaysOn(e.target.checked)} />
Broadcast 24/7
</label>
{!alwaysOn && (
<div className="flex items-center gap-2">
<Input type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} aria-label="Start time" />
<span className="text-sm text-on-surface-variant">to</span>
<Input type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} aria-label="End time" />
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
<Button type="submit" disabled={submitting || !name.trim()} className="w-full">
Start broadcasting
</Button>
</form>
)
}
import { useState } from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RadioLocationPicker } from './RadioLocationPicker'
import * as soundmarksApi from '../api/soundmarks'
function Controlled({ initialLat = null, initialLon = null }: { initialLat?: number | null; initialLon?: number | null }) {
const [lat, setLat] = useState(initialLat)
const [lon, setLon] = useState(initialLon)
const [radius, setRadius] = useState<number | null>(null)
return (
<div>
<RadioLocationPicker
latitude={lat}
longitude={lon}
radiusMeters={radius}
onChange={(newLat, newLon) => {
setLat(newLat)
setLon(newLon)
}}
onRadiusChange={setRadius}
/>
<p data-testid="coords">{lat !== null && lon !== null ? `${lat},${lon}` : 'none'}</p>
<p data-testid="radius">{radius === null ? 'none' : radius}</p>
</div>
)
}
describe('RadioLocationPicker', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('shows no radius hint until a location is picked', () => {
render(<Controlled />)
expect(screen.queryByText(/radius/)).not.toBeInTheDocument()
})
it('searches for an address and selecting a result sets the coordinates', async () => {
vi.spyOn(soundmarksApi, 'geocodeAddress').mockResolvedValue({
status: 'success',
results: [{ display_name: 'Eiffel Tower, Paris, France', latitude: 48.8584, longitude: 2.2945 }],
})
render(<Controlled />)
await userEvent.type(screen.getByPlaceholderText('Search for an address or place'), 'Eiffel')
const result = await screen.findByText('Eiffel Tower, Paris, France')
await userEvent.click(result)
await waitFor(() => {
expect(screen.getByTestId('coords')).toHaveTextContent('48.8584,2.2945')
})
})
it('reports a radius once a location is picked, without a separate manual input', async () => {
vi.spyOn(soundmarksApi, 'geocodeAddress').mockResolvedValue({
status: 'success',
results: [{ display_name: 'Eiffel Tower, Paris, France', latitude: 48.8584, longitude: 2.2945 }],
})
render(<Controlled />)
expect(screen.queryByRole('spinbutton', { name: /radius/i })).not.toBeInTheDocument()
await userEvent.type(screen.getByPlaceholderText('Search for an address or place'), 'Eiffel')
await userEvent.click(await screen.findByText('Eiffel Tower, Paris, France'))
await waitFor(() => {
expect(screen.getByTestId('radius')).not.toHaveTextContent('none')
})
})
it('places the pin on map click via the onChange handler', async () => {
render(<Controlled />)
// RadioLocationPicker renders without a pin initially - confirms the map mounts cleanly
// with hasPin=false (no Circle/Marker), which is the only click-driven path not already
// exercised by the address-search test above.
expect(screen.getByPlaceholderText('Search for an address or place')).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { Circle, MapContainer, Marker, TileLayer, useMap, useMapEvents } from 'react-leaflet'
import type { LeafletMouseEvent } from 'leaflet'
import { LocateFixed, MapPin, Search } from 'lucide-react'
import { Input } from './ui/Input'
import { geocodeAddress, reverseGeocode, type GeocodeResult } from '../api/soundmarks'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, soundmarkIcon } from '../lib/mapTheme'
const DEFAULT_CENTER: [number, number] = [20, 0] // low zoom, whole-world view when nothing is set yet
const ZOOM_NO_PIN = 2
const ZOOM_ON_JUMP = 12
// The broadcast circle covers this fraction of the visible viewport's east-west span - leaves
// breathing room on both sides rather than touching the map edges exactly.
const VIEWPORT_RADIUS_FRACTION = 0.35
interface RadioLocationPickerProps {
latitude: number | null
longitude: number | null
radiusMeters: number | null
onChange: (lat: number, lon: number) => void
onRadiusChange: (radiusMeters: number) => void
}
/** Same jump-on-address-pick behavior as LocationPicker - see its own docstring for why this
* is deliberately not tied to latitude/longitude directly. */
function FlyToOnJump({ jumpTo }: { jumpTo: { lat: number; lon: number } | null }) {
const map = useMap()
useEffect(() => {
if (jumpTo) map.setView([jumpTo.lat, jumpTo.lon], ZOOM_ON_JUMP)
}, [jumpTo, map])
return null
}
function ClickToPlacePin({ onClick }: { onClick: (lat: number, lon: number) => void }) {
useMapEvents({
click(e: LeafletMouseEvent) {
onClick(e.latlng.lat, e.latlng.lng)
},
})
return null
}
/** Recomputes the broadcast circle's real-world radius from the map's current visible
* viewport on every zoom or pan - rather than a separate manual numeric input, the circle
* always covers a fixed fraction of whatever's currently on screen (the user picks "how big"
* by zooming in or out, same as framing a photo). Radius is computed at the circle's own
* center latitude, not the map's - east-west distance per degree of longitude shrinks toward
* the poles, so using the wrong latitude would size the circle inconsistently as it's dragged
* north or south. Leaflet's own map.distance() (a standard great-circle formula) measures it,
* rather than hand-rolling a second haversine implementation on the frontend. */
function RadiusFromViewport({ centerLat, onRadiusChange }: { centerLat: number; onRadiusChange: (meters: number) => void }) {
const map = useMapEvents({
zoomend: recompute,
moveend: recompute,
})
function recompute() {
const bounds = map.getBounds()
const widthMeters = map.distance([centerLat, bounds.getWest()], [centerLat, bounds.getEast()])
onRadiusChange(Math.round((widthMeters / 2) * VIEWPORT_RADIUS_FRACTION))
}
useEffect(recompute, [centerLat]) // eslint-disable-line react-hooks/exhaustive-deps
return null
}
/** Sibling to LocationPicker, not a modification of it - the zoom-reactive circle below is a
* different, continuously-recomputed behavior that LocationPicker's one existing consumer
* (Soundmarks, a fixed-point pin with a separate plain numeric radius field) has no reason to
* grow. Used for a local-scope Radio station: search, click, or drag the pin to place the
* station, then zoom/pan the map to size its broadcast radius. */
export function RadioLocationPicker({ latitude, longitude, radiusMeters, onChange, onRadiusChange }: RadioLocationPickerProps) {
const [query, setQuery] = useState('')
const [results, setResults] = useState<GeocodeResult[]>([])
const [showResults, setShowResults] = useState(false)
const [jumpTo, setJumpTo] = useState<{ lat: number; lon: number } | null>(null)
const [locating, setLocating] = useState(false)
const [locateError, setLocateError] = useState<string | null>(null)
useEffect(() => {
if (!query.trim()) {
setResults([])
return
}
const handle = setTimeout(() => {
geocodeAddress(query)
.then((res) => {
setResults(res.results)
setShowResults(true)
})
.catch(() => setResults([]))
}, 400)
return () => clearTimeout(handle)
}, [query])
function selectResult(result: GeocodeResult) {
onChange(result.latitude, result.longitude)
setJumpTo({ lat: result.latitude, lon: result.longitude })
setQuery(result.display_name)
setShowResults(false)
}
function handleLocateMe() {
setLocateError(null)
if (!navigator.geolocation) {
setLocateError("Your browser doesn't support location services.")
return
}
if (!window.isSecureContext) {
setLocateError('Location access requires a secure (https://) connection.')
return
}
setLocating(true)
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude: lat, longitude: lon } = pos.coords
onChange(lat, lon)
setJumpTo({ lat, lon })
reverseGeocode(lat, lon)
.then((res) => {
if (res.display_name) setQuery(res.display_name)
})
.catch(() => {
// Best-effort - the pin is already correctly placed either way.
})
.finally(() => setLocating(false))
},
(err) => {
setLocating(false)
setLocateError(
err.code === err.PERMISSION_DENIED
? 'Location access was denied - search or tap the map instead.'
: "Couldn't determine your location. Please try again.",
)
},
{ enableHighAccuracy: true, timeout: 15000 },
)
}
const hasPin = latitude !== null && longitude !== null
const initialCenter: [number, number] = hasPin ? [latitude, longitude] : DEFAULT_CENTER
const initialZoom = hasPin ? ZOOM_ON_JUMP : ZOOM_NO_PIN
return (
<div>
<div className="relative">
<Search
size={16}
strokeWidth={2}
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-outline"
/>
<Input
placeholder="Search for an address or place"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => results.length > 0 && setShowResults(true)}
className="pl-9"
/>
{showResults && results.length > 0 && (
<ul className="absolute z-[1000] mt-1 max-h-56 w-full overflow-y-auto rounded-lg border border-outline-variant bg-surface-container-high shadow-xl">
{results.map((r, i) => (
<li key={i}>
<button
type="button"
onClick={() => selectResult(r)}
className="flex w-full items-start gap-2 px-3 py-2 text-left text-sm text-on-surface hover:bg-surface-container-high"
>
<MapPin size={14} strokeWidth={2} className="mt-0.5 shrink-0 text-outline" />
<span className="line-clamp-2">{r.display_name}</span>
</button>
</li>
))}
</ul>
)}
</div>
<div className="relative z-0 mt-3 h-56 overflow-hidden rounded-lg border border-outline-variant">
<MapContainer center={initialCenter} zoom={initialZoom} className="h-full w-full" scrollWheelZoom>
<TileLayer attribution={DARK_TILE_ATTRIBUTION} url={DARK_TILE_URL} />
<FlyToOnJump jumpTo={jumpTo} />
<ClickToPlacePin onClick={onChange} />
{hasPin && (
<>
<RadiusFromViewport centerLat={latitude} onRadiusChange={onRadiusChange} />
<Circle
center={[latitude, longitude]}
radius={radiusMeters ?? 0}
pathOptions={{ color: '#2e5bff', fillColor: '#2e5bff', fillOpacity: 0.12, weight: 2 }}
/>
<Marker
position={[latitude, longitude]}
icon={soundmarkIcon('generic')}
draggable
eventHandlers={{
dragend: (e) => {
const pos = e.target.getLatLng()
onChange(pos.lat, pos.lng)
},
}}
/>
</>
)}
</MapContainer>
<button
type="button"
onClick={handleLocateMe}
disabled={locating}
aria-label="Use my current location"
title="Use my current location"
className="absolute bottom-2.5 right-2.5 z-[1000] flex h-9 w-9 items-center justify-center rounded-full border border-outline-variant bg-surface-container/90 text-on-surface shadow-lg backdrop-blur transition-colors duration-150 hover:bg-surface-container-high disabled:opacity-50"
>
<LocateFixed size={17} strokeWidth={2} className={locating ? 'animate-pulse' : ''} />
</button>
</div>
{locateError && <p className="mt-1 text-xs text-error">{locateError}</p>}
<p className="mt-1 text-xs text-outline">
Search an address, tap <LocateFixed size={11} strokeWidth={2} className="inline -translate-y-px" />, or click the map to place your
station - zoom and pan to size the broadcast circle.
{hasPin && radiusMeters != null && ` Covering ~${(radiusMeters / 1000).toFixed(1)}km radius.`}
</p>
</div>
)
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RadioManageTab } from './RadioManageTab'
import * as radioApi from '../api/radio'
import type { Radio, RadioQueueTrack } from '../api/radio'
vi.mock('./SongPicker', () => ({
SongPicker: ({ onSelect }: { onSelect: (song: { id: number }) => void }) => (
<button onClick={() => onSelect({ id: 77 })}>Pick song (mock)</button>
),
}))
const STATION: Radio = {
id: 9,
owner_id: 1,
name: 'Night Drive FM',
description: null,
artwork_url: null,
band: 'SM',
frequency: 100.0,
scope: 'worldwide',
latitude: null,
longitude: null,
radius_meters: null,
schedule_start_minute: null,
schedule_end_minute: null,
is_active: true,
created_at: '2026-01-01T00:00:00Z',
}
const TRACK: RadioQueueTrack = {
track_id: 1,
position: 0,
song: { id: 50, user_id: 1, title: 'First Song', artist: 'Some Artist', album: null, coverart: null, duration_seconds: 180 },
}
function renderTab(onDeleted = vi.fn(), onUpdated = vi.fn(), radio: Radio = STATION) {
return render(<RadioManageTab radio={radio} onDeleted={onDeleted} onUpdated={onUpdated} />)
}
describe('RadioManageTab', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('shows station info and an empty queue message', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
renderTab()
expect(screen.getByText('Night Drive FM')).toBeInTheDocument()
expect(await screen.findByText(/No songs queued yet/)).toBeInTheDocument()
})
it('lists queued tracks', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([TRACK])
renderTab()
expect(await screen.findByText('First Song')).toBeInTheDocument()
expect(screen.getByText('Some Artist')).toBeInTheDocument()
})
it('adds a picked song to the queue and refreshes it', async () => {
const getQueue = vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const addToQueue = vi.spyOn(radioApi, 'addToQueue').mockResolvedValue({ status: 'success', track_id: 2, position: 0 })
renderTab()
await screen.findByText(/No songs queued yet/)
getQueue.mockResolvedValue([TRACK])
await userEvent.click(screen.getByRole('button', { name: 'Add song' }))
await userEvent.click(screen.getByText('Pick song (mock)'))
await waitFor(() => expect(addToQueue).toHaveBeenCalledWith(9, 77))
expect(await screen.findByText('First Song')).toBeInTheDocument()
})
it('removes a track from the queue', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([TRACK])
const removeFromQueue = vi.spyOn(radioApi, 'removeFromQueue').mockResolvedValue({ status: 'success' })
renderTab()
await screen.findByText('First Song')
await userEvent.click(screen.getByRole('button', { name: 'Remove First Song from the queue' }))
await waitFor(() => expect(removeFromQueue).toHaveBeenCalledWith(9, 1))
expect(screen.queryByText('First Song')).not.toBeInTheDocument()
})
it('uploads artwork and reports the updated station', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const upload = vi.spyOn(radioApi, 'uploadRadioArtwork').mockResolvedValue({ status: 'success', radio: { ...STATION, artwork_url: '/images/1/a.png' } })
const onUpdated = vi.fn()
renderTab(vi.fn(), onUpdated)
await screen.findByText(/No songs queued yet/)
const file = new File(['fake'], 'art.png', { type: 'image/png' })
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, file)
await waitFor(() => expect(upload).toHaveBeenCalledWith(9, file))
expect(onUpdated).toHaveBeenCalledWith(expect.objectContaining({ artwork_url: '/images/1/a.png' }))
})
it('saves a fixed schedule window when 24/7 is unchecked', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const update = vi.spyOn(radioApi, 'updateRadio').mockResolvedValue({ status: 'success', radio: STATION })
renderTab()
await screen.findByText(/No songs queued yet/)
await userEvent.click(screen.getByText('Broadcast 24/7'))
await userEvent.click(screen.getByRole('button', { name: 'Save schedule' }))
await waitFor(() => expect(update).toHaveBeenCalled())
const body = update.mock.calls[0][1]
expect(body.schedule_start_minute).not.toBeUndefined()
expect(body.schedule_end_minute).not.toBeUndefined()
})
it('deletes the station after confirming', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const del = vi.spyOn(radioApi, 'deleteRadio').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
const onDeleted = vi.fn()
renderTab(onDeleted)
await screen.findByText(/No songs queued yet/)
await userEvent.click(screen.getByRole('button', { name: /Delete station/ }))
await waitFor(() => expect(del).toHaveBeenCalledWith(9))
expect(onDeleted).toHaveBeenCalled()
})
it('does not delete the station when the confirm dialog is declined', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const del = vi.spyOn(radioApi, 'deleteRadio')
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderTab()
await screen.findByText(/No songs queued yet/)
await userEvent.click(screen.getByRole('button', { name: /Delete station/ }))
expect(del).not.toHaveBeenCalled()
})
})
import { useEffect, useState, type ChangeEvent } from 'react'
import { Music2, Trash2, Upload, X } from 'lucide-react'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { SongPicker } from './SongPicker'
import { addToQueue, deleteRadio, getQueue, removeFromQueue, updateRadio, uploadRadioArtwork, type Radio, type RadioQueueTrack } from '../api/radio'
import { localTimeToUtcMinute, utcMinuteToLocalTime } from '../lib/radioSchedule'
interface RadioManageTabProps {
radio: Radio
onDeleted: () => void
onUpdated: (radio: Radio) => void
}
/** The creator's side of a station - queue management (reusing the existing SongPicker, same
* modal the business/admin panels already use for picking a song), artwork, schedule, and
* delete. Listening is RadioTuner's job, a different screen entirely. */
export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabProps) {
const [queue, setQueue] = useState<RadioQueueTrack[]>([])
const [loadingQueue, setLoadingQueue] = useState(true)
const [pickerOpen, setPickerOpen] = useState(false)
const [uploading, setUploading] = useState(false)
const [alwaysOn, setAlwaysOn] = useState(radio.schedule_start_minute === null)
const [startTime, setStartTime] = useState(radio.schedule_start_minute !== null ? utcMinuteToLocalTime(radio.schedule_start_minute) : '09:00')
const [endTime, setEndTime] = useState(radio.schedule_end_minute !== null ? utcMinuteToLocalTime(radio.schedule_end_minute) : '17:00')
const [savingSchedule, setSavingSchedule] = useState(false)
const [error, setError] = useState<string | null>(null)
function refreshQueue() {
setLoadingQueue(true)
getQueue(radio.id)
.then(setQueue)
.catch(() => setQueue([]))
.finally(() => setLoadingQueue(false))
}
useEffect(refreshQueue, [radio.id])
async function handleAddSong(song: { id: number }) {
setPickerOpen(false)
try {
await addToQueue(radio.id, song.id)
refreshQueue()
} catch {
setError('Could not add that song to the queue.')
}
}
async function handleRemoveTrack(trackId: number) {
try {
await removeFromQueue(radio.id, trackId)
setQueue((q) => q.filter((t) => t.track_id !== trackId))
} catch {
setError('Could not remove that song.')
}
}
async function handleArtworkChange(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file) return
setUploading(true)
setError(null)
try {
const { radio: updated } = await uploadRadioArtwork(radio.id, file)
onUpdated(updated)
} catch {
setError('Could not upload artwork.')
} finally {
setUploading(false)
e.target.value = ''
}
}
async function handleSaveSchedule() {
setSavingSchedule(true)
setError(null)
try {
const { radio: updated } = await updateRadio(radio.id, {
schedule_start_minute: alwaysOn ? undefined : localTimeToUtcMinute(startTime),
schedule_end_minute: alwaysOn ? undefined : localTimeToUtcMinute(endTime),
})
onUpdated(updated)
} catch {
setError('Could not update the schedule.')
} finally {
setSavingSchedule(false)
}
}
async function handleDelete() {
if (!window.confirm(`Delete "${radio.name}"? This can't be undone.`)) return
await deleteRadio(radio.id)
onDeleted()
}
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="h-16 w-16 shrink-0 overflow-hidden rounded-lg bg-surface-container-high">
{radio.artwork_url ? (
<img src={radio.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={22} strokeWidth={1.75} />
</div>
)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-on-surface">{radio.name}</p>
<p className="text-sm text-on-surface-variant">
{radio.band} {radio.frequency.toFixed(1)} · {radio.scope}
</p>
</div>
<label className="shrink-0">
<input type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={handleArtworkChange} disabled={uploading} />
<span className="flex cursor-pointer items-center gap-1.5 rounded-full border border-outline-variant px-3 py-1.5 text-xs font-medium text-on-surface-variant hover:border-primary hover:text-on-surface">
<Upload size={13} strokeWidth={2} />
{uploading ? 'Uploading…' : 'Artwork'}
</span>
</label>
</div>
{error && <p className="text-sm text-error">{error}</p>}
<div>
<div className="mb-2 flex items-center justify-between">
<p className="text-sm font-semibold text-on-surface">Queue</p>
<Button type="button" size="sm" variant="secondary" onClick={() => setPickerOpen(true)}>
Add song
</Button>
</div>
{!loadingQueue && queue.length === 0 && (
<p className="text-sm text-on-surface-variant">No songs queued yet - add one to start broadcasting.</p>
)}
<ul className="space-y-1.5">
{queue.map((track) => (
<li
key={track.track_id}
className="flex items-center justify-between gap-2 rounded-lg border border-outline-variant bg-surface-container px-3 py-2"
>
<div className="min-w-0">
<p className="truncate text-sm font-medium text-on-surface">{track.song.title}</p>
<p className="truncate text-xs text-on-surface-variant">{track.song.artist}</p>
</div>
<button
onClick={() => handleRemoveTrack(track.track_id)}
aria-label={`Remove ${track.song.title} from the queue`}
className="shrink-0 rounded-full p-1.5 text-on-surface-variant hover:bg-surface-container-high hover:text-error"
>
<X size={15} strokeWidth={2} />
</button>
</li>
))}
</ul>
</div>
<div>
<p className="mb-2 text-sm font-semibold text-on-surface">Schedule</p>
<label className="flex items-center gap-2 text-sm text-on-surface-variant">
<input type="checkbox" checked={alwaysOn} onChange={(e) => setAlwaysOn(e.target.checked)} />
Broadcast 24/7
</label>
{!alwaysOn && (
<div className="mt-2 flex items-center gap-2">
<Input type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} aria-label="Start time" />
<span className="text-sm text-on-surface-variant">to</span>
<Input type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} aria-label="End time" />
</div>
)}
<Button type="button" size="sm" variant="secondary" onClick={handleSaveSchedule} disabled={savingSchedule} className="mt-2">
Save schedule
</Button>
</div>
<Button type="button" variant="secondary" onClick={handleDelete} className="w-full gap-1.5 text-error">
<Trash2 size={15} strokeWidth={2} />
Delete station
</Button>
{pickerOpen && <SongPicker onSelect={handleAddSong} onClose={() => setPickerOpen(false)} />}
</div>
)
}
import { 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'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { clearTokens, setTokens } from '../api/client'
import * as authApi from '../api/auth'
import * as radioApi from '../api/radio'
import * as libraryApi from '../api/library'
import type { Radio, NowPlaying } from '../api/radio'
const ME_ID = 1
const OTHER_ID = 2
const STATION: Radio = {
id: 10,
owner_id: OTHER_ID,
name: 'Night Drive FM',
description: null,
artwork_url: null,
band: 'SM',
frequency: 100.0,
scope: 'worldwide',
latitude: null,
longitude: null,
radius_meters: null,
schedule_start_minute: null,
schedule_end_minute: null,
is_active: true,
created_at: '2026-01-01T00:00:00Z',
}
const ON_AIR: NowPlaying = {
on_air: true,
song: { id: 55, user_id: OTHER_ID, title: 'Midnight Run', artist: 'The Band', album: null, coverart: null, duration_seconds: 180 },
offset_seconds: 42,
artwork_url: '/images/1/station.png',
}
function renderTuner(onAddToPlaylist = vi.fn()) {
return render(
<AuthProvider>
<PlayerProvider>
<RadioTuner onAddToPlaylist={onAddToPlaylist} />
</PlayerProvider>
</AuthProvider>,
)
}
describe('RadioTuner', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('test-access', 'test-refresh')
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: ME_ID, username: 'me', role: 'user', has_completed_onboarding: true, privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
vi.stubGlobal('navigator', { ...navigator, geolocation: undefined })
})
afterEach(() => {
clearTokens()
vi.unstubAllEnvs()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('shows the empty state when the dial matches no station', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([])
renderTuner()
expect(await screen.findByText(/No station here/)).toBeInTheDocument()
})
it('locks onto a station within the tuning epsilon and shows what is on air', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
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('Midnight Run')).toBeInTheDocument()
expect(screen.getByText('The Band')).toBeInTheDocument()
})
it('shows an off-air message when the locked station has nothing playing', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue({ on_air: false, song: null, offset_seconds: null, artwork_url: null })
renderTuner()
expect(await screen.findByText(/isn't broadcasting right now/)).toBeInTheDocument()
})
it('switching bands drops the lock until a new browse list resolves', async () => {
const browse = vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
renderTuner()
await screen.findByText('Night Drive FM')
browse.mockResolvedValue([])
await userEvent.click(screen.getByRole('button', { name: 'SF' }))
await waitFor(() => expect(browse).toHaveBeenLastCalledWith({ band: 'SF', lat: undefined, lon: undefined }))
expect(await screen.findByText(/No station here/)).toBeInTheDocument()
})
it('plays the station stream, builds a negative playable id clear of other features', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
vi.spyOn(radioApi, 'fetchRadioStreamUrl').mockResolvedValue('blob:fake-radio-stream')
renderTuner()
await screen.findByText('Midnight Run')
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => expect(radioApi.fetchRadioStreamUrl).toHaveBeenCalledWith(10))
expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('claims the now-playing song before favoriting it, since it belongs to someone else', async () => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([STATION])
vi.spyOn(radioApi, 'getNowPlaying').mockResolvedValue(ON_AIR)
const claim = vi.spyOn(libraryApi, 'claimSharedSong').mockResolvedValue({ status: 'success', library_song_id: 999 })
const favorite = vi.spyOn(libraryApi, 'favoriteSong').mockResolvedValue({ status: 'success', is_liked: true })
renderTuner()
await screen.findByText('Midnight Run')
await userEvent.click(screen.getByRole('button', { name: 'Like Midnight Run' }))
await waitFor(() => expect(claim).toHaveBeenCalledWith('Midnight Run', 'The Band'))
await waitFor(() => expect(favorite).toHaveBeenCalledWith(999))
})
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)
vi.spyOn(libraryApi, 'claimSharedSong').mockResolvedValue({ status: 'success', library_song_id: 999 })
const onAddToPlaylist = vi.fn()
renderTuner(onAddToPlaylist)
await screen.findByText('Midnight Run')
await userEvent.click(screen.getByRole('button', { name: 'Add Midnight Run to a playlist' }))
await waitFor(() => expect(onAddToPlaylist).toHaveBeenCalledWith({ id: 999, title: 'Midnight Run' }))
})
})
import { useEffect, useRef, useState } 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'
const BANDS: RadioBand[] = ['SM', 'SF', 'SR']
const FREQUENCY_MIN = 50.0
const FREQUENCY_MAX = 200.0
// 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
const NOW_PLAYING_POLL_MS = 10_000
// Clear of Rooms' (-roomId) and Soundmarks' (-soundmarkId) own negative-id ranges - see
// PlayableSong's own docstring in PlayerContext.tsx for why these ids just need to be unique
// for play/pause identity, never used to fetch audio.
const RADIO_ID_OFFSET = 1_000_000
const PLACEHOLDER_SONG: ClaimableSong = { id: -1, user_id: -1, title: '', artist: '' }
interface RadioTunerProps {
onAddToPlaylist: (song: { id: number; title: string }) => void
}
/** Band pills + a real tuning dial (a plain 50-200 range input, not a separate text/select
* control) - dragging it re-checks the already-fetched browse list client-side against
* TUNING_LOCK_EPSILON, so moving the slider never itself triggers a request; now-playing is
* only fetched (and polled) once locked onto one station. */
export function RadioTuner({ onAddToPlaylist }: RadioTunerProps) {
const [band, setBand] = useState<RadioBand>('SM')
const [frequency, setFrequency] = useState(100.0)
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)
// 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.
useEffect(() => {
if (!navigator.geolocation || !window.isSecureContext) return
navigator.geolocation.getCurrentPosition(
(pos) => setCoords({ lat: pos.coords.latitude, lon: pos.coords.longitude }),
() => {},
)
}, [])
useEffect(() => {
browseRadios({ band, lat: coords?.lat, lon: coords?.lon })
.then(setStations)
.catch(() => setStations([]))
}, [band, coords])
const lockedStation = stations.find((s) => Math.abs(s.frequency - frequency) < TUNING_LOCK_EPSILON) ?? null
const lockedStationId = lockedStation?.id ?? null
useEffect(() => {
if (lockedStationId === null) {
setNowPlaying(null)
return
}
let active = true
function poll() {
getNowPlaying(lockedStationId!)
.then((np) => {
if (active) setNowPlaying(np)
})
.catch(() => {
if (active) setNowPlaying(null)
})
}
poll()
const handle = setInterval(poll, NOW_PLAYING_POLL_MS)
return () => {
active = false
clearInterval(handle)
}
}, [lockedStationId])
const nowPlayingSong = nowPlaying?.on_air ? nowPlaying.song : null
const claimableSong: ClaimableSong = nowPlayingSong
? {
id: nowPlayingSong.id,
user_id: nowPlayingSong.user_id,
title: nowPlayingSong.title,
artist: nowPlayingSong.artist,
album: nowPlayingSong.album,
coverart: nowPlaying?.artwork_url ?? nowPlayingSong.coverart,
}
: PLACEHOLDER_SONG
// Favoriting/adding-to-playlist the now-playing song reuses the exact same claim-then-act
// mechanism Home's feed rows use - a station's queue song always belongs to someone other
// than the listener (see radio.py's compute_now_playing), the same situation useClaimThenAct
// was generalized for. Streaming the station itself (below) is a different, radio-specific
// action - not a claim, so it doesn't go through this hook.
const { isLiked, claiming, error, handleToggleFavorite, handleAddToPlaylist } = useClaimThenAct(claimableSong)
const stationPlayableId = lockedStation ? -(RADIO_ID_OFFSET + lockedStation.id) : null
const isThisPlaying = stationPlayableId !== null && currentSong?.id === stationPlayableId && isPlaying
function toPlayable(station: Radio, np: NowPlaying): PlayableSong {
return {
id: -(RADIO_ID_OFFSET + station.id),
title: np.song?.title ?? station.name,
artist: np.song?.artist ?? 'Live radio',
coverart: np.artwork_url,
streamUrl: () => fetchRadioStreamUrl(station.id),
}
}
function handlePlay() {
if (!lockedStation || !nowPlaying?.on_air) return
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])
return (
<div>
<div className="mb-4 flex gap-2">
{BANDS.map((b) => (
<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'
}`}
>
{b}
</button>
))}
</div>
<input
type="range"
min={FREQUENCY_MIN}
max={FREQUENCY_MAX}
step={0.1}
value={frequency}
onChange={(e) => setFrequency(Number(e.target.value))}
aria-label="Tuning dial"
className="seek-range w-full"
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}%)`,
}}
/>
<p className="mt-1 text-center text-2xl font-semibold tabular-nums text-on-surface">
{band} {frequency.toFixed(1)}
</p>
<div className="mt-6">
{!lockedStation && <EmptyState icon={RadioTower} message="No station here - keep tuning the dial." />}
{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>
{nowPlayingSong ? (
<div className="flex items-center gap-3">
<div className="h-14 w-14 shrink-0 overflow-hidden rounded-lg bg-surface-container-high">
{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} />
</div>
)}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium 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>
<button
onClick={handleToggleFavorite}
disabled={claiming !== null}
aria-label={isLiked ? `Unlike ${nowPlayingSong.title}` : `Like ${nowPlayingSong.title}`}
aria-pressed={isLiked}
className={`shrink-0 rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed ${
isLiked ? 'text-primary hover:bg-surface-container-high' : 'text-on-surface-variant hover:bg-surface-container-high hover:text-primary'
}`}
>
<Heart size={18} strokeWidth={1.75} fill={isLiked ? 'currentColor' : 'none'} />
</button>
<button
onClick={() => handleAddToPlaylist(onAddToPlaylist)}
disabled={claiming !== null}
aria-label={`Add ${nowPlayingSong.title} to a playlist`}
className="shrink-0 rounded-full p-2 text-on-surface-variant transition-colors hover:bg-surface-container-high hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</div>
) : (
<p className="text-sm text-on-surface-variant">This station isn't broadcasting right now.</p>
)}
</div>
)}
</div>
</div>
)
}
......@@ -19,6 +19,8 @@ function Probe() {
hasPrevious,
isShuffled,
repeatMode,
volume,
setVolume,
playbackError,
toggle,
addToQueue,
......@@ -37,6 +39,7 @@ function Probe() {
<span data-testid="has-previous">{String(hasPrevious)}</span>
<span data-testid="is-shuffled">{String(isShuffled)}</span>
<span data-testid="repeat-mode">{repeatMode}</span>
<span data-testid="volume">{volume}</span>
<span data-testid="playback-error">{playbackError ?? 'none'}</span>
<button onClick={() => toggle(SONG_A, QUEUE)}>Play A</button>
<button onClick={() => toggle(SONG_C, QUEUE)}>Play C</button>
......@@ -47,6 +50,9 @@ function Probe() {
<button onClick={toggleShuffle}>Toggle Shuffle</button>
<button onClick={cycleRepeat}>Cycle Repeat</button>
<button onClick={dismissError}>Dismiss Error</button>
<button onClick={() => setVolume(0.4)}>Set Volume 0.4</button>
<button onClick={() => setVolume(-1)}>Set Volume -1</button>
<button onClick={() => setVolume(5)}>Set Volume 5</button>
</div>
)
}
......@@ -62,6 +68,7 @@ function renderProbe() {
describe('PlayerContext queue navigation', () => {
afterEach(() => {
vi.restoreAllMocks()
window.localStorage.clear()
})
it('steps forward through the queue passed to toggle', async () => {
......@@ -234,4 +241,30 @@ describe('PlayerContext playback errors', () => {
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song C'))
expect(screen.getByTestId('playback-error')).toHaveTextContent('none')
})
it('defaults volume to 1 when nothing is stored', () => {
renderProbe()
expect(screen.getByTestId('volume')).toHaveTextContent('1')
})
it('updates volume and persists it to localStorage', async () => {
renderProbe()
await userEvent.click(screen.getByText('Set Volume 0.4'))
expect(screen.getByTestId('volume')).toHaveTextContent('0.4')
expect(window.localStorage.getItem('stax-volume')).toBe('0.4')
})
it('clamps volume to the 0-1 range', async () => {
renderProbe()
await userEvent.click(screen.getByText('Set Volume -1'))
expect(screen.getByTestId('volume')).toHaveTextContent('0')
await userEvent.click(screen.getByText('Set Volume 5'))
expect(screen.getByTestId('volume')).toHaveTextContent('1')
})
it('restores a previously persisted volume on mount', () => {
window.localStorage.setItem('stax-volume', '0.25')
renderProbe()
expect(screen.getByTestId('volume')).toHaveTextContent('0.25')
})
})
......@@ -39,6 +39,11 @@ interface PlayerContextValue {
hasPrevious: boolean
isShuffled: boolean
repeatMode: RepeatMode
/** 0-1, persisted to localStorage across sessions. Also the hook Radio's live push-to-talk
* voice ducking (Phase 2) ramps down on `voice_start`/back up on `voice_end` - see
* useRadioVoiceDucking. */
volume: number
setVolume: (volume: number) => void
/** Set when the most recent play attempt failed (bad stream, network error, browser
* blocked autoplay, ...) - cleared automatically as soon as another track starts loading. */
playbackError: string | null
......@@ -86,7 +91,18 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const [isShuffled, setIsShuffled] = useState(false)
const [repeatMode, setRepeatMode] = useState<RepeatMode>('off')
const [playbackError, setPlaybackError] = useState<string | null>(null)
const [volume, setVolumeState] = useState<number>(() => {
const stored = window.localStorage.getItem('stax-volume')
const parsed = stored ? parseFloat(stored) : NaN
return Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : 1
})
const audioRef = useRef<HTMLAudioElement | null>(null)
// Read by the mount effect below (a one-time [] effect, so it can't close over live state)
// to set the newly-created Audio element's initial volume.
const volumeRef = useRef(volume)
useEffect(() => {
volumeRef.current = volume
}, [volume])
// The queue as originally handed to toggle(), before any shuffling - restored when shuffle
// is turned back off.
const originalQueueRef = useRef<PlayableSong[]>([])
......@@ -154,6 +170,7 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const audio = new Audio()
audio.volume = volumeRef.current
audioRef.current = audio
const onEnded = () => {
// "Repeat one" only affects what happens when a track finishes on its own - the Next
......@@ -205,6 +222,13 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
setProgress(time)
}, [])
const setVolume = useCallback((next: number) => {
const clamped = Math.min(1, Math.max(0, next))
setVolumeState(clamped)
if (audioRef.current) audioRef.current.volume = clamped
window.localStorage.setItem('stax-volume', String(clamped))
}, [])
const expand = useCallback(() => setIsExpanded(true), [])
const collapse = useCallback(() => setIsExpanded(false), [])
const dismissError = useCallback(() => setPlaybackError(null), [])
......@@ -284,6 +308,8 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
hasPrevious,
isShuffled,
repeatMode,
volume,
setVolume,
playbackError,
toggle,
addToQueue,
......
import { useState } from 'react'
import { claimSharedSong, favoriteSong, unfavoriteSong } from '../api/library'
import { ApiError } from '../api/client'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useAuth } from '../context/AuthContext'
/** Minimal shape any claim-then-act consumer needs - both HomeSong (Home feed/shared search)
* and Radio's now-playing song satisfy this already. */
export interface ClaimableSong {
id: number
user_id: number
title: string
artist: string
album?: string | null
coverart?: string | null
}
/** Generic claim-then-act flow for a song that might belong to someone else's library.
* Originally built inline for Home's feed/shared-search rows (HomeSongRow, HomeAlbumCard's
* expanded track list); extracted here once Radio's now-playing song - which, by definition
* (see radio.py's compute_now_playing), always belongs to someone other than the listener -
* needed the exact same play/add-to-playlist/favorite mechanism with zero new logic.
*
* A song the caller already owns (`user_id === userId`) acts directly via its real library
* id; everyone else's claims a copy first via title+artist matching against the shared
* library (claimSharedSong) - same mechanism Library's SharedSongRow already uses. */
export function useClaimThenAct(song: ClaimableSong, initialIsLiked: boolean = false) {
const { userId } = useAuth()
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [claiming, setClaiming] = useState<'play' | 'playlist' | 'favorite' | null>(null)
const [error, setError] = useState<string | null>(null)
// Optimistic override, same shape as Library.tsx's own favorite toggle - null means "trust
// the caller-supplied initialIsLiked" (only ever true for an owned song anyway), set once
// the viewer actually taps the heart so the UI flips immediately instead of waiting on the
// claim+favorite round trip.
const [likedOverride, setLikedOverride] = useState<boolean | null>(null)
const isOwnSong = song.user_id === userId
const isCurrent = isOwnSong && currentSong?.id === song.id
const isLiked = likedOverride ?? initialIsLiked
function toPlayable(libraryId: number): PlayableSong {
return { id: libraryId, title: song.title, artist: song.artist, album: song.album, coverart: song.coverart }
}
async function resolveLibraryId(): Promise<number> {
if (isOwnSong) return song.id
const res = await claimSharedSong(song.title, song.artist)
return res.library_song_id
}
async function handlePlay() {
if (isOwnSong) {
toggle(toPlayable(song.id), [toPlayable(song.id)])
return
}
setError(null)
setClaiming('play')
try {
const libraryId = await resolveLibraryId()
toggle(toPlayable(libraryId), [toPlayable(libraryId)])
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
async function handleAddToPlaylist(onClaimed: (song: { id: number; title: string }) => void) {
if (isOwnSong) {
onClaimed({ id: song.id, title: song.title })
return
}
setError(null)
setClaiming('playlist')
try {
const libraryId = await resolveLibraryId()
onClaimed({ id: libraryId, title: song.title })
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
/** Claims first if the caller doesn't already own this song (same as play/add-to-playlist),
* then favorites/unfavorites the resulting owned copy - optimistic, reverting the heart on
* failure the same way Library.tsx's own toggle does. */
async function handleToggleFavorite() {
const nextLiked = !isLiked
setLikedOverride(nextLiked)
setError(null)
setClaiming('favorite')
try {
const libraryId = await resolveLibraryId()
await (nextLiked ? favoriteSong(libraryId) : unfavoriteSong(libraryId))
} catch (err) {
setLikedOverride(!nextLiked)
setError(err instanceof ApiError ? err.message : `Could not update "${song.title}"`)
} finally {
setClaiming(null)
}
}
return { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, isLiked, handlePlay, handleAddToPlaylist, handleToggleFavorite }
}
import { useState } from 'react'
import { claimSharedSong, favoriteSong, unfavoriteSong } from '../api/library'
import { ApiError } from '../api/client'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useAuth } from '../context/AuthContext'
import { useClaimThenAct } from './useClaimThenAct'
import type { HomeSong } from '../api/home'
/** Shared by HomeSongRow and HomeAlbumCard's expanded track list (the places a Home-feed song
* can be tapped) so the claim-then-act logic isn't duplicated between them. A Home-feed song
* the caller already owns (`user_id === userId`) acts directly via its real library id;
* everyone else's goes through the same claim-then-act mechanism SharedSongRow already uses
* for Library's shared search results, since that id belongs to someone else's library row and
* nothing (streaming, favoriting, playlisting) can happen on it until the caller has their own
* copy. */
/** Thin wrapper over the generic useClaimThenAct for the one place this originated - Home's
* feed/shared-search rows (HomeSongRow, HomeAlbumCard's expanded track list). See
* useClaimThenAct's own docstring for the full claim-then-act mechanism. */
export function useHomeSongPlayback(song: HomeSong) {
const { userId } = useAuth()
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [claiming, setClaiming] = useState<'play' | 'playlist' | 'favorite' | null>(null)
const [error, setError] = useState<string | null>(null)
// Optimistic override, same shape as Library.tsx's own favorite toggle - null means "trust
// the server-supplied song.is_liked" (only ever true for an owned song anyway), set once the
// viewer actually taps the heart so the UI flips immediately instead of waiting on the
// claim+favorite round trip.
const [likedOverride, setLikedOverride] = useState<boolean | null>(null)
const isOwnSong = song.user_id === userId
const isCurrent = isOwnSong && currentSong?.id === song.id
const isLiked = likedOverride ?? song.is_liked
function toPlayable(libraryId: number): PlayableSong {
return { id: libraryId, title: song.title, artist: song.artist, album: song.album, coverart: song.coverart }
}
async function resolveLibraryId(): Promise<number> {
if (isOwnSong) return song.id
const res = await claimSharedSong(song.title, song.artist)
return res.library_song_id
}
async function handlePlay() {
if (isOwnSong) {
toggle(toPlayable(song.id), [toPlayable(song.id)])
return
}
setError(null)
setClaiming('play')
try {
const libraryId = await resolveLibraryId()
toggle(toPlayable(libraryId), [toPlayable(libraryId)])
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
async function handleAddToPlaylist(onClaimed: (song: { id: number; title: string }) => void) {
if (isOwnSong) {
onClaimed({ id: song.id, title: song.title })
return
}
setError(null)
setClaiming('playlist')
try {
const libraryId = await resolveLibraryId()
onClaimed({ id: libraryId, title: song.title })
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add "${song.title}"`)
} finally {
setClaiming(null)
}
}
/** Claims first if the caller doesn't already own this song (same as play/add-to-playlist),
* then favorites/unfavorites the resulting owned copy - optimistic, reverting the heart on
* failure the same way Library.tsx's own toggle does. */
async function handleToggleFavorite() {
const nextLiked = !isLiked
setLikedOverride(nextLiked)
setError(null)
setClaiming('favorite')
try {
const libraryId = await resolveLibraryId()
await (nextLiked ? favoriteSong(libraryId) : unfavoriteSong(libraryId))
} catch (err) {
setLikedOverride(!nextLiked)
setError(err instanceof ApiError ? err.message : `Could not update "${song.title}"`)
} finally {
setClaiming(null)
}
}
return { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, isLiked, handlePlay, handleAddToPlaylist, handleToggleFavorite }
return useClaimThenAct(song, song.is_liked)
}
/** Radio.schedule_start_minute/end_minute are UTC minutes-since-midnight (radio.py) - the
* creator picks times in their own local timezone via <input type="time">, so these convert
* between the two using today's date purely to resolve the browser's own UTC offset, not as a
* real calendar date (the schedule itself repeats daily, with no date component at all).
* Shared by RadioCreateForm (set once) and RadioManageTab (edit later). */
export function localTimeToUtcMinute(hhmm: string): number {
const [hours, minutes] = hhmm.split(':').map(Number)
const d = new Date()
d.setHours(hours, minutes, 0, 0)
return d.getUTCHours() * 60 + d.getUTCMinutes()
}
export function utcMinuteToLocalTime(minute: number): string {
const d = new Date()
d.setUTCHours(Math.floor(minute / 60), minute % 60, 0, 0)
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Channels } from './Channels'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { setTokens } from '../api/client'
import * as channelsApi from '../api/channels'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
* that's the server's job), matching api/jwt.test.ts's own helper. */
function fakeJwt(payload: object): string {
const base64url = (obj: object) =>
btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
return `${base64url({ alg: 'HS256', typ: 'JWT' })}.${base64url(payload)}.fake-signature`
}
const MY_CHANNEL: channelsApi.Channel = {
id: 1,
owner_id: 1,
name: 'My Channel',
description: null,
avatar_url: null,
created_at: '2026-01-01T00:00:00Z',
}
const OTHER_CHANNEL: channelsApi.Channel = {
id: 2,
owner_id: 5,
name: "Someone Else's Channel",
description: null,
avatar_url: null,
created_at: '2026-01-01T00:00:00Z',
}
function renderChannels() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Channels />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Channels', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows an empty state when there are no channels', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([])
renderChannels()
expect(await screen.findByText(/No channels yet/)).toBeInTheDocument()
})
it('lists channels with their follower count and owner', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([OTHER_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: OTHER_CHANNEL, follower_count: 3 })
renderChannels()
expect(await screen.findByText("Someone Else's Channel")).toBeInTheDocument()
expect(screen.getByText(/3 followers · owner #5/)).toBeInTheDocument()
})
it('creates a channel via the form without needing to pass an owner id', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([])
const create = vi.spyOn(channelsApi, 'createChannel').mockResolvedValue(MY_CHANNEL)
renderChannels()
await screen.findByText(/No channels yet/)
await userEvent.type(screen.getByPlaceholderText('New channel name'), 'My Channel')
await userEvent.click(screen.getByRole('button', { name: 'Create' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('My Channel'))
})
it('does not show a follow button on your own channel', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([MY_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: MY_CHANNEL, follower_count: 0 })
renderChannels()
await screen.findByText('My Channel')
expect(screen.queryByRole('button', { name: /Follow/ })).not.toBeInTheDocument()
})
it('follows and unfollows someone else\'s channel without passing a user id', async () => {
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([OTHER_CHANNEL])
vi.spyOn(channelsApi, 'getChannel').mockResolvedValue({ channel: OTHER_CHANNEL, follower_count: 3 })
const follow = vi.spyOn(channelsApi, 'followChannel').mockResolvedValue({})
const unfollow = vi.spyOn(channelsApi, 'unfollowChannel').mockResolvedValue({ status: 'ok' })
renderChannels()
await screen.findByText("Someone Else's Channel")
await userEvent.click(screen.getByRole('button', { name: 'Follow' }))
expect(follow).toHaveBeenCalledWith(OTHER_CHANNEL.id)
expect(await screen.findByText(/4 followers/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Unfollow' })).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Unfollow' }))
expect(unfollow).toHaveBeenCalledWith(OTHER_CHANNEL.id)
expect(await screen.findByText(/3 followers/)).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { Rss } from 'lucide-react'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { EmptyState } from '../components/ui/EmptyState'
import { SkeletonRow } from '../components/ui/Skeleton'
import { createChannel, followChannel, getChannel, listChannels, unfollowChannel, type Channel } from '../api/channels'
import { getCurrentUserId } from '../api/jwt'
export function Channels() {
const userId = getCurrentUserId()
const [channels, setChannels] = useState<Channel[]>([])
const [loading, setLoading] = useState(true)
const [followerCounts, setFollowerCounts] = useState<Record<number, number>>({})
const [followedIds, setFollowedIds] = useState<Set<number>>(new Set())
const [newName, setNewName] = useState('')
async function refresh() {
const list = await listChannels()
setChannels(list)
setLoading(false)
const counts: Record<number, number> = {}
await Promise.all(
list.map(async (c) => {
const detail = await getChannel(c.id)
counts[c.id] = detail.follower_count
}),
)
setFollowerCounts(counts)
}
useEffect(() => {
refresh()
}, [])
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newName.trim()) return
await createChannel(newName.trim())
setNewName('')
refresh()
}
async function toggleFollow(channelId: number) {
if (followedIds.has(channelId)) {
await unfollowChannel(channelId)
setFollowedIds((s) => new Set([...s].filter((id) => id !== channelId)))
setFollowerCounts((c) => ({ ...c, [channelId]: Math.max(0, c[channelId] - 1) }))
} else {
await followChannel(channelId)
setFollowedIds((s) => new Set(s).add(channelId))
setFollowerCounts((c) => ({ ...c, [channelId]: (c[channelId] ?? 0) + 1 }))
}
}
return (
<>
<form onSubmit={handleCreate} className="mb-6 flex gap-2">
<Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="New channel name" />
<Button type="submit">Create</Button>
</form>
{loading && (
<div className="space-y-2">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{!loading && channels.length === 0 && (
<EmptyState icon={Rss} message="No channels yet - start one to publish vibe sets and stories." />
)}
<ul className="space-y-2">
{channels.map((channel) => (
<li
key={channel.id}
className="flex min-h-[52px] items-center justify-between gap-3 rounded-lg border border-outline-variant bg-surface-container px-4 py-3 transition-colors duration-150 hover:border-outline-variant"
>
<div className="min-w-0">
<p className="truncate font-medium text-on-surface">{channel.name}</p>
<p className="text-xs text-outline">
{followerCounts[channel.id] ?? 0} followers · owner #{channel.owner_id}
</p>
</div>
{channel.owner_id !== userId && (
<Button
variant={followedIds.has(channel.id) ? 'secondary' : 'primary'}
size="sm"
onClick={() => toggleFollow(channel.id)}
className="shrink-0"
>
{followedIds.has(channel.id) ? 'Unfollow' : 'Follow'}
</Button>
)}
</li>
))}
</ul>
</>
)
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RadioPage } from './Radio'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as radioApi from '../api/radio'
import type { Radio } from '../api/radio'
vi.mock('../components/RadioCreateForm', () => ({
RadioCreateForm: ({ onCreated }: { onCreated: (radio: Radio) => void }) => (
<button onClick={() => onCreated(STATION)}>Finish create (mock)</button>
),
}))
vi.mock('../components/RadioManageTab', () => ({
RadioManageTab: ({ radio, onDeleted }: { radio: Radio; onDeleted: () => void }) => (
<div>
<p>Managing {radio.name}</p>
<button onClick={onDeleted}>Delete (mock)</button>
</div>
),
}))
const STATION: Radio = {
id: 9,
owner_id: 1,
name: 'Night Drive FM',
description: null,
artwork_url: null,
band: 'SM',
frequency: 100.0,
scope: 'worldwide',
latitude: null,
longitude: null,
radius_meters: null,
schedule_start_minute: null,
schedule_end_minute: null,
is_active: true,
created_at: '2026-01-01T00:00:00Z',
}
function renderPage() {
return render(
<AuthProvider>
<PlayerProvider>
<RadioPage />
</PlayerProvider>
</AuthProvider>,
)
}
describe('RadioPage', () => {
beforeEach(() => {
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([])
vi.spyOn(radioApi, 'getMyRadios').mockResolvedValue([])
vi.stubGlobal('navigator', { ...navigator, geolocation: undefined })
})
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('shows the tuner on the Listen tab by default', () => {
renderPage()
expect(screen.getByLabelText('Tuning dial')).toBeInTheDocument()
})
it('shows an empty state on My stations when the caller owns none', async () => {
renderPage()
await userEvent.click(screen.getByRole('button', { name: 'My stations' }))
expect(await screen.findByText(/haven't started a station yet/)).toBeInTheDocument()
})
it('lists owned stations and opens management on tap', async () => {
vi.spyOn(radioApi, 'getMyRadios').mockResolvedValue([STATION])
renderPage()
await userEvent.click(screen.getByRole('button', { name: 'My stations' }))
await userEvent.click(await screen.findByText('Night Drive FM'))
expect(await screen.findByText('Managing Night Drive FM')).toBeInTheDocument()
})
it('creates a station and jumps straight into managing it', async () => {
renderPage()
await userEvent.click(screen.getByRole('button', { name: 'My stations' }))
await screen.findByText(/haven't started a station yet/)
await userEvent.click(screen.getByRole('button', { name: /Start a station/ }))
await userEvent.click(screen.getByText('Finish create (mock)'))
expect(await screen.findByText('Managing Night Drive FM')).toBeInTheDocument()
})
it('returns to the station list after deleting', async () => {
vi.spyOn(radioApi, 'getMyRadios').mockResolvedValue([STATION])
renderPage()
await userEvent.click(screen.getByRole('button', { name: 'My stations' }))
await userEvent.click(await screen.findByText('Night Drive FM'))
await screen.findByText('Managing Night Drive FM')
await userEvent.click(screen.getByText('Delete (mock)'))
await waitFor(() => expect(screen.queryByText('Night Drive FM')).not.toBeInTheDocument())
})
})
import { useEffect, useState } from 'react'
import { ChevronLeft, ChevronRight, Plus, RadioTower } from 'lucide-react'
import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { RadioTuner } from '../components/RadioTuner'
import { RadioCreateForm } from '../components/RadioCreateForm'
import { RadioManageTab } from '../components/RadioManageTab'
import { getMyRadios, type Radio } from '../api/radio'
type Tab = 'listen' | 'manage'
/** Named RadioPage (not Radio) to avoid colliding with the already-imported lucide Radio icon
* used elsewhere (e.g. Social.tsx's Rooms tab). Two halves under one page: RadioTuner for
* listening (band + frequency dial) and a "my stations" list for creating/managing the
* caller's own - mirroring how Social.tsx folds several related features under one nav
* destination with an in-page switcher instead of competing top-level tabs. */
export function RadioPage() {
const [tab, setTab] = useState<Tab>('listen')
const [myStations, setMyStations] = useState<Radio[]>([])
const [loadingStations, setLoadingStations] = useState(true)
const [creating, setCreating] = useState(false)
const [managingStation, setManagingStation] = useState<Radio | null>(null)
const [addingSong, setAddingSong] = useState<{ id: number; title: string } | null>(null)
function refreshStations() {
getMyRadios()
.then(setMyStations)
.finally(() => setLoadingStations(false))
}
useEffect(() => {
if (tab === 'manage') refreshStations()
}, [tab])
function handleCreated(radio: Radio) {
setCreating(false)
setMyStations((stations) => [radio, ...stations])
setManagingStation(radio)
}
function handleDeleted() {
setMyStations((stations) => stations.filter((s) => s.id !== managingStation?.id))
setManagingStation(null)
}
function handleUpdated(radio: Radio) {
setMyStations((stations) => stations.map((s) => (s.id === radio.id ? radio : s)))
setManagingStation(radio)
}
return (
<div>
<div className="mb-6 flex gap-2">
<button
onClick={() => setTab('listen')}
aria-pressed={tab === 'listen'}
className={`flex items-center gap-1.5 rounded-full px-4 py-1.5 text-sm font-medium transition-colors duration-150 ${
tab === 'listen'
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
}`}
>
<RadioTower size={14} strokeWidth={2} />
Listen
</button>
<button
onClick={() => setTab('manage')}
aria-pressed={tab === 'manage'}
className={`flex items-center gap-1.5 rounded-full px-4 py-1.5 text-sm font-medium transition-colors duration-150 ${
tab === 'manage'
? 'bg-primary text-on-primary'
: 'border border-outline-variant bg-surface-container text-on-surface-variant hover:border-primary hover:text-on-surface'
}`}
>
My stations
</button>
</div>
{tab === 'listen' && <RadioTuner onAddToPlaylist={setAddingSong} />}
{tab === 'manage' && (
<>
{managingStation ? (
<div>
<button
onClick={() => setManagingStation(null)}
className="mb-4 flex items-center gap-1 text-sm text-on-surface-variant hover:text-on-surface"
>
<ChevronLeft size={16} strokeWidth={2} />
All stations
</button>
<RadioManageTab radio={managingStation} onDeleted={handleDeleted} onUpdated={handleUpdated} />
</div>
) : creating ? (
<div>
<button
onClick={() => setCreating(false)}
className="mb-4 flex items-center gap-1 text-sm text-on-surface-variant hover:text-on-surface"
>
<ChevronLeft size={16} strokeWidth={2} />
Cancel
</button>
<RadioCreateForm onCreated={handleCreated} />
</div>
) : (
<div>
<Button onClick={() => setCreating(true)} className="mb-4 w-full gap-1.5">
<Plus size={16} strokeWidth={2} />
Start a station
</Button>
{!loadingStations && myStations.length === 0 && (
<EmptyState icon={RadioTower} message="You haven't started a station yet - create one to broadcast to the world." />
)}
<ul className="space-y-2">
{myStations.map((station) => (
<li key={station.id}>
<button
onClick={() => setManagingStation(station)}
className="flex min-h-[52px] w-full items-center justify-between gap-3 rounded-lg border border-outline-variant bg-surface-container px-4 py-3 text-left transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/70"
>
<div>
<p className="font-medium text-on-surface">{station.name}</p>
<p className="text-xs text-outline">
{station.band} {station.frequency.toFixed(1)} · {station.scope}
</p>
</div>
<ChevronRight size={18} strokeWidth={2} className="shrink-0 text-on-surface-variant" />
</button>
</li>
))}
</ul>
</div>
)}
</>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</div>
)
}
......@@ -38,8 +38,9 @@ describe('Roadmap', () => {
expect(screen.getByText(/Playlists page: list, create, view tracks, playback/)).toBeInTheDocument()
// To-do lists - a "ready" item that moved out of backend once this pass's work landed,
// and its frontend counterpart that's now unblocked by the same work.
expect(screen.getByText('Channels: vibe sets, stories, showcase screens')).toBeInTheDocument()
expect(screen.getByText('Delete buttons + confirm dialogs for playlists and playlist tracks')).toBeInTheDocument()
// Channels was fully replaced by Radio (2026-10-12), not left as a dangling to-do.
expect(screen.getByText(/Channels -> Radio/)).toBeInTheDocument()
// A "needs design" idea split into its own backend half and frontend half.
expect(screen.getByText('Migrate off SQLite to PostgreSQL + PostGIS')).toBeInTheDocument()
expect(screen.getByText('Wire a "save to library" action for liked Discovery matches')).toBeInTheDocument()
......
......@@ -77,8 +77,13 @@ const BACKEND_DONE: DoneGroup[] = [
],
},
{
area: 'Channels',
items: ['Create/follow/unfollow', 'Vibe sets, 24h audio stories, and showcase endpoints (built, no frontend yet)'],
area: 'Channels -> Radio',
items: [
'Channels (create/follow, vibe sets, 24h audio stories, showcase) fully removed (2026-10-12) - the backend shipped but the vibe-sets/stories/showcase pieces never got any frontend at all; confirmed zero usage before deleting both the router and the UI shell rather than leaving a dead feature half-built forever.',
'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.',
],
},
{
area: 'Posts',
......@@ -180,6 +185,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Space Grotesk (Google Fonts, external CDN link in index.html) replaced by the preset\'s own DM Sans Variable / Outfit Variable, both self-hosted via @fontsource-variable - no external font request at all now, consistent with how the rest of the app avoids third-party runtime dependencies.',
'Settings toggle switches no longer render their thumb outside the pill (fixed 2026-10-07, reported right after the above shipped): the thumb relied on left:auto plus a translate-x offset for its position, but the native <button>\'s text-align:center UA default - never neutralized by an explicit left - made the auto-resolved static position land near the pill\'s right edge regardless of checked state, so the translate pushed it visibly outside the pill in both states instead of sliding within it. Anchored with an explicit left-0.5 base position instead (the standard Tailwind switch recipe), so it no longer depends on the browser\'s static-position resolution for an auto-positioned box.',
'Fixed a real app-wide contrast bug in the token bridge above (2026-10-07, reported as "timestamps not visible" and "dark mode harder to read than light"): `outline` - used as TEXT color in ~65 places (timestamps, subtitles, hints, muted icons) - had been bridged to `--border`, a value shadcn deliberately keeps near-invisible for hairline dividers (10%-opacity white in dark mode, barely contains a dark-on-white page in light mode). `outline-variant`, which actually is only ever used for borders/dividers, was correctly left pointing at `--border`; `outline` now points at `--muted-foreground`, the token shadcn designs to be legible at caption size. One-line fix, every page benefits since the token is shared app-wide.',
'FullPlayer gained a real volume slider (2026-10-12) - PlayerContext.volume/setVolume (0-1, clamped, persisted to localStorage, applied to the one shared <audio> element on every change and restored on mount) closes a long-standing gap and incidentally gives Radio\'s Phase 2 live-voice ducking a lever to pull.',
'FullPlayer\'s Lyrics screen gained a persistent mini transport (seek bar, timestamps, previous/play-pause/next) pinned below the scrollable text (2026-10-07, reported as "controls aren\'t visible" and "lyrics tab is a bit dry") - previously the only way to pause or skip while reading lyrics was backing out to the main Now Playing screen first, and the screen was just a wall of text with nothing else going on. Same approach Spotify\'s own lyrics view takes: lyrics don\'t have to be a dead end.',
'FullPlayer\'s root panel now caps its height at h-svh (small viewport height) instead of relying on inset-0\'s implicit 100% (fixed 2026-10-07, reported as "lyrics bleed in at the bottom and shifts the UI"): mobile browsers size a fixed element against the *large* viewport by default (as if the address bar were already hidden), so with the bar actually showing, the panel was taller than what could be seen - its bottom edge (the Lyrics screen\'s own header, in practice) peeked in below the fold, and a real touch scroll could drag the whole thing. svh is always sized for the bar being visible, so there\'s never more height than can be shown at once.',
'First full visual redesign (2026-08-23), sourced from a Stitch design export: cobalt/periwinkle-on-deep-ink Material-3-style token system (primary #b8c3ff / primary-container #2e5bff on #131313), Space Grotesk, sharp 4px-radius geometry - deliberately not the export\'s mint-green "Stax" variant, which read too close to an existing music app\'s brand color. Superseded by the shadcn swap above, but the token *names* and page structure it established are still exactly what every component uses today.',
......@@ -221,7 +227,8 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [
'Rooms, Channels, and Posts merged under one nav destination (2026-08-23) with an in-page Rooms/Channels/Posts tab switcher, instead of three top-level tabs competing for the same "who\'s doing what" attention',
'Rooms: chat, reactions, DJ song picker, pass-the-aux controls, now-playing card (RoomView stays a genuinely full-screen experience, not wrapped in the app chrome)',
'Channels: list + follow/unfollow UI only - vibe sets/stories/showcase have no UI yet',
'Rooms gained real invite codes, PIN protection, and location-based discovery (2026-10-12) - the create form takes an optional 4-digit PIN and a location toggle (via LocationPicker), a join-by-code form and a "near me" map (new RoomsNearbyMap.tsx) cover the other two discovery paths. A shared attemptJoin() backs all three entry points and opens a PIN-entry screen on a 403, distinguishing "wrong PIN" from other failures. The room\'s own DJ sees their invite code and PIN status in RoomView\'s header; nobody else does.',
'Channels tab replaced by Radio (2026-10-12): band (SM/SF/SR) pills + a real 50.0-200.0 tuning dial (RadioTuner.tsx) that locks onto a station using the same 0.3 epsilon as the backend, entirely client-side against an already-fetched browse list - dragging the slider never itself hits the network. Favoriting/playlisting the now-playing song reuses useClaimThenAct (extracted from Home\'s own useHomeSongPlayback - Radio\'s now-playing song always belongs to someone other than the listener, the exact situation that hook already handled). Playing the station itself builds a PlayableSong with a distinct negative id (-1,000,000 - stationId, clear of Rooms\'/Soundmarks\' own ranges) and seeks to the server-computed offset once the stream\'s duration is known, so joining mid-song actually joins mid-song instead of restarting the track. A "My stations" sub-tab covers the creator side: RadioCreateForm (band/frequency dial, worldwide-vs-local toggle, schedule 24/7-or-fixed-window) and RadioManageTab (queue via the existing SongPicker, artwork upload, schedule edit, delete). New RadioLocationPicker.tsx (sibling to LocationPicker, not a modification of it) draws a broadcast-radius circle whose size is derived live from the map\'s current zoom/pan via Leaflet\'s own distance() rather than a separate manual numeric input - zooming in or out is how the radius gets picked.',
'Posts: feed, composer, recursive remix-tree view with "remix this" at every node',
'New "Messages" 4th tab (2026-09-13, DMInbox) for the new Direct Messages backend - a thread list (shown as "User #<id>", since threads carry only participant ids, not usernames) linking out to a real routed page at /dm/:threadId (DMThreadView, mirrors RoomView\'s header/scrollback/input shape) for the actual conversation. Room chat messages are now keyed by their real database id instead of array position, matching the backend\'s move off the old in-memory deque.',
'New minimal /settings page (2026-09-13): the two privacy toggles (share live location, allow direct messages), both off by default - kept out of Social.tsx since they\'re account-level, not social content.',
......@@ -295,12 +302,6 @@ const FRONTEND_TODO: WorkItem[] = [
status: 'ready',
note: 'Library songs got both (2026-08-31, swipe-to-delete + window.confirm) - playlists and individual playlist tracks still have neither, despite the backend supporting all three deletes since 2026-08-18.',
},
{
item: 'Channels: vibe sets, stories, showcase screens',
status: 'ready',
note: 'Backend endpoints already exist and work - zero UI.',
},
{ item: 'Volume control in the player', status: 'ready' },
{
item: 'Global error boundary',
status: 'ready',
......
......@@ -6,7 +6,7 @@ import { Social } from './Social'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as socialApi from '../api/social'
import * as channelsApi from '../api/channels'
import * as radioApi from '../api/radio'
function renderSocial() {
return render(
......@@ -26,11 +26,13 @@ describe('Social', () => {
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([])
vi.spyOn(channelsApi, 'listChannels').mockResolvedValue([])
vi.spyOn(radioApi, 'browseRadios').mockResolvedValue([])
vi.stubGlobal('navigator', { ...navigator, geolocation: undefined })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
......@@ -39,13 +41,13 @@ describe('Social', () => {
expect(await screen.findByPlaceholderText('Room name')).toBeInTheDocument()
})
it('switches to the Channels panel when tapped', async () => {
it('switches to the Radio panel when tapped', async () => {
renderSocial()
await screen.findByPlaceholderText('Room name')
await userEvent.click(screen.getByRole('button', { name: 'Channels' }))
await userEvent.click(screen.getByRole('button', { name: 'Radio' }))
expect(await screen.findByPlaceholderText('New channel name')).toBeInTheDocument()
expect(await screen.findByLabelText('Tuning dial')).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Room name')).not.toBeInTheDocument()
})
......
import { useState } from 'react'
import { Disc3, MessageCircle, Radio, Rss } from 'lucide-react'
import { Disc3, MessageCircle, Radio, RadioTower } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Rooms } from './Rooms'
import { Channels } from './Channels'
import { RadioPage } from './Radio'
import { Posts } from './Posts'
import { DMInbox } from '../components/DMInbox'
type Tab = 'rooms' | 'channels' | 'posts' | 'messages'
type Tab = 'rooms' | 'radio' | 'posts' | 'messages'
const TABS: { id: Tab; label: string; icon: typeof Radio }[] = [
{ id: 'rooms', label: 'Rooms', icon: Radio },
{ id: 'channels', label: 'Channels', icon: Rss },
// RadioTower, not Radio - that lucide icon is already Rooms' own, immediately above.
{ id: 'radio', label: 'Radio', icon: RadioTower },
{ id: 'posts', label: 'Posts', icon: Disc3 },
{ id: 'messages', label: 'Messages', icon: MessageCircle },
]
/** Every socially-driven feature (live listening rooms, creator channels, the post/remix
* feed) lives under one nav destination with an in-page switcher, instead of three separate
* top-level tabs competing for the same "who's doing what" attention. */
/** Every socially-driven feature (live listening rooms, creator radio stations, the post/
* remix feed) lives under one nav destination with an in-page switcher, instead of separate
* top-level tabs competing for the same "who's doing what" attention. Channels was removed
* (2026-10-12, replaced by this Radio tab - see Roadmap.tsx). */
export function Social() {
const [tab, setTab] = useState<Tab>('rooms')
return (
<Layout title="Social">
{/* overflow-x-auto + shrink-0 pills: four full-label pills (Rooms/Channels/Posts/
Messages) don't fit a phone-width viewport without this - confirmed live via a
mobile-viewport sweep, where the row pushed the whole page wider than the screen
instead of wrapping or scrolling. */}
{/* overflow-x-auto + shrink-0 pills: four full-label pills (Rooms/Radio/Posts/Messages)
don't fit a phone-width viewport without this - confirmed live via a mobile-viewport
sweep, where the row pushed the whole page wider than the screen instead of wrapping
or scrolling. */}
<div className="mb-6 flex gap-2 overflow-x-auto">
{TABS.map((t) => {
const active = tab === t.id
......@@ -52,7 +54,7 @@ export function Social() {
between tabs with no transition at all. */}
<div key={tab} className="animate-content-enter">
{tab === 'rooms' && <Rooms />}
{tab === 'channels' && <Channels />}
{tab === 'radio' && <RadioPage />}
{tab === 'posts' && <Posts />}
{tab === 'messages' && <DMInbox />}
</div>
......
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