Commit d9dde94c authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Radio: real toggle for local scope, visible broadcast circle, editable after creation

The "Reach: Worldwide/Local" pill pair read as two unrelated buttons rather
than one feature being switched on - replaced with a single ToggleRow ("Tie
to a real-world location"), the same shared switch component and wording
already used elsewhere (Settings, Rooms' own location toggle).

That surfaced a real bug in the shared component: ToggleRow's switch button
had no explicit type, so inside an actual <form> (its first use inside one)
it defaulted to type="submit" and silently submitted the form with stale
state on click instead of just toggling. Fixed in ToggleRow itself.

The broadcast-radius circle was real but easy to miss - 0.12 fill opacity on
a dark basemap, and briefly rendered as a literal zero-radius circle before
the viewport-derived radius was computed. Strengthened its contrast, skipped
the zero-radius frame, and added an explicit "~Xkm radius" badge on the map.

The location+circle picker was also only ever reachable once, during station
creation. RadioManageTab gained the same toggle + picker + a "Save broadcast
area" action, so an existing station's broadcast area is visible and
editable afterward too - the backend (PATCH /radio/{id}) already supported
this, only the frontend wiring was missing.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 14d15e8e
...@@ -67,7 +67,7 @@ describe('RadioCreateForm', () => { ...@@ -67,7 +67,7 @@ describe('RadioCreateForm', () => {
render(<RadioCreateForm onCreated={vi.fn()} />) render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station') await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station')
await userEvent.click(screen.getByRole('button', { name: 'Local' })) await userEvent.click(screen.getByRole('switch', { name: 'Tie to a real-world location' }))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' })) await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
expect(await screen.findByText(/Place your station on the map/)).toBeInTheDocument() expect(await screen.findByText(/Place your station on the map/)).toBeInTheDocument()
...@@ -79,7 +79,7 @@ describe('RadioCreateForm', () => { ...@@ -79,7 +79,7 @@ describe('RadioCreateForm', () => {
render(<RadioCreateForm onCreated={vi.fn()} />) render(<RadioCreateForm onCreated={vi.fn()} />)
await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station') await userEvent.type(screen.getByPlaceholderText('Station name'), 'Local Station')
await userEvent.click(screen.getByRole('button', { name: 'Local' })) await userEvent.click(screen.getByRole('switch', { name: 'Tie to a real-world location' }))
await userEvent.click(screen.getByText('Place station (mock)')) await userEvent.click(screen.getByText('Place station (mock)'))
await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' })) await userEvent.click(screen.getByRole('button', { name: 'Start broadcasting' }))
......
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import { MapPin } from 'lucide-react'
import { Button } from './ui/Button' import { Button } from './ui/Button'
import { Input, Textarea } from './ui/Input' import { Input, Textarea } from './ui/Input'
import { ToggleRow } from './ui/ToggleRow'
import { RadioLocationPicker } from './RadioLocationPicker' import { RadioLocationPicker } from './RadioLocationPicker'
import { createRadio, type Radio, type RadioBand, type RadioScope } from '../api/radio' import { createRadio, type Radio, type RadioBand, type RadioScope } from '../api/radio'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
...@@ -102,35 +104,14 @@ export function RadioCreateForm({ onCreated }: RadioCreateFormProps) { ...@@ -102,35 +104,14 @@ export function RadioCreateForm({ onCreated }: RadioCreateFormProps) {
</p> </p>
</div> </div>
<div> <ToggleRow
<p className="mb-1.5 text-xs font-medium text-on-surface-variant">Reach</p> icon={MapPin}
<div className="flex gap-2"> label="Tie to a real-world location"
<button description={scope === 'local' ? 'Only listeners inside your broadcast circle can tune in' : 'Off - anyone, anywhere can tune in'}
type="button" checked={scope === 'local'}
onClick={() => setScope('worldwide')} saving={false}
aria-pressed={scope === 'worldwide'} onToggle={() => setScope((s) => (s === 'local' ? 'worldwide' : 'local'))}
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' && ( {scope === 'local' && (
<RadioLocationPicker <RadioLocationPicker
......
...@@ -182,11 +182,16 @@ export function RadioLocationPicker({ latitude, longitude, radiusMeters, onChang ...@@ -182,11 +182,16 @@ export function RadioLocationPicker({ latitude, longitude, radiusMeters, onChang
{hasPin && ( {hasPin && (
<> <>
<RadiusFromViewport centerLat={latitude} onRadiusChange={onRadiusChange} /> <RadiusFromViewport centerLat={latitude} onRadiusChange={onRadiusChange} />
<Circle {/* Only rendered once a real radius exists - skips a one-frame flash of a
center={[latitude, longitude]} literal zero-radius (and therefore invisible) circle between placing the pin
radius={radiusMeters ?? 0} and RadiusFromViewport's effect computing the first real value. */}
pathOptions={{ color: '#2e5bff', fillColor: '#2e5bff', fillOpacity: 0.12, weight: 2 }} {radiusMeters != null && (
/> <Circle
center={[latitude, longitude]}
radius={radiusMeters}
pathOptions={{ color: '#5ab0ff', fillColor: '#5ab0ff', fillOpacity: 0.28, weight: 3, dashArray: '6 6' }}
/>
)}
<Marker <Marker
position={[latitude, longitude]} position={[latitude, longitude]}
icon={soundmarkIcon('generic')} icon={soundmarkIcon('generic')}
...@@ -201,6 +206,11 @@ export function RadioLocationPicker({ latitude, longitude, radiusMeters, onChang ...@@ -201,6 +206,11 @@ export function RadioLocationPicker({ latitude, longitude, radiusMeters, onChang
</> </>
)} )}
</MapContainer> </MapContainer>
{hasPin && radiusMeters != null && (
<div className="absolute left-2.5 top-2.5 z-[1000] rounded-full border border-outline-variant bg-surface-container/90 px-2.5 py-1 text-xs font-semibold text-on-surface shadow-lg backdrop-blur">
~{(radiusMeters / 1000).toFixed(1)}km radius
</div>
)}
<button <button
type="button" type="button"
onClick={handleLocateMe} onClick={handleLocateMe}
......
...@@ -11,6 +11,16 @@ vi.mock('./SongPicker', () => ({ ...@@ -11,6 +11,16 @@ vi.mock('./SongPicker', () => ({
), ),
})) }))
// Real Leaflet map, covered by its own test file - stubbed to its essential contract here,
// same pattern RadioCreateForm.test.tsx and Rooms.test.tsx use for the same/sibling picker.
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 STATION: Radio = { const STATION: Radio = {
id: 9, id: 9,
owner_id: 1, owner_id: 1,
...@@ -114,6 +124,34 @@ describe('RadioManageTab', () => { ...@@ -114,6 +124,34 @@ describe('RadioManageTab', () => {
expect(body.schedule_end_minute).not.toBeUndefined() expect(body.schedule_end_minute).not.toBeUndefined()
}) })
it('saves a new broadcast area once tied to a location and placed on the map', 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.getByRole('switch', { name: 'Tie to a real-world location' }))
await userEvent.click(screen.getByText('Place station (mock)'))
await userEvent.click(screen.getByRole('button', { name: 'Save broadcast area' }))
await waitFor(() =>
expect(update).toHaveBeenCalledWith(9, { scope: 'local', latitude: 12.5, longitude: 45.5, radius_meters: 5000 }),
)
})
it('refuses to save a local broadcast area with no pin placed yet', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const update = vi.spyOn(radioApi, 'updateRadio')
renderTab()
await screen.findByText(/No songs queued yet/)
await userEvent.click(screen.getByRole('switch', { name: 'Tie to a real-world location' }))
await userEvent.click(screen.getByRole('button', { name: 'Save broadcast area' }))
expect(await screen.findByText(/Place your station on the map/)).toBeInTheDocument()
expect(update).not.toHaveBeenCalled()
})
it('deletes the station after confirming', async () => { it('deletes the station after confirming', async () => {
vi.spyOn(radioApi, 'getQueue').mockResolvedValue([]) vi.spyOn(radioApi, 'getQueue').mockResolvedValue([])
const del = vi.spyOn(radioApi, 'deleteRadio').mockResolvedValue({ status: 'success' }) const del = vi.spyOn(radioApi, 'deleteRadio').mockResolvedValue({ status: 'success' })
......
import { useEffect, useState, type ChangeEvent } from 'react' import { useEffect, useState, type ChangeEvent } from 'react'
import { Music2, Trash2, Upload, X } from 'lucide-react' import { MapPin, Music2, Trash2, Upload, X } from 'lucide-react'
import { Button } from './ui/Button' import { Button } from './ui/Button'
import { Input } from './ui/Input' import { Input } from './ui/Input'
import { ToggleRow } from './ui/ToggleRow'
import { SongPicker } from './SongPicker' import { SongPicker } from './SongPicker'
import { addToQueue, deleteRadio, getQueue, removeFromQueue, updateRadio, uploadRadioArtwork, type Radio, type RadioQueueTrack } from '../api/radio' import { RadioLocationPicker } from './RadioLocationPicker'
import { addToQueue, deleteRadio, getQueue, removeFromQueue, updateRadio, uploadRadioArtwork, type Radio, type RadioQueueTrack, type RadioScope } from '../api/radio'
import { localTimeToUtcMinute, utcMinuteToLocalTime } from '../lib/radioSchedule' import { localTimeToUtcMinute, utcMinuteToLocalTime } from '../lib/radioSchedule'
interface RadioManageTabProps { interface RadioManageTabProps {
...@@ -24,6 +26,11 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr ...@@ -24,6 +26,11 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr
const [startTime, setStartTime] = useState(radio.schedule_start_minute !== null ? utcMinuteToLocalTime(radio.schedule_start_minute) : '09:00') 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 [endTime, setEndTime] = useState(radio.schedule_end_minute !== null ? utcMinuteToLocalTime(radio.schedule_end_minute) : '17:00')
const [savingSchedule, setSavingSchedule] = useState(false) const [savingSchedule, setSavingSchedule] = useState(false)
const [scope, setScope] = useState<RadioScope>(radio.scope)
const [latitude, setLatitude] = useState<number | null>(radio.latitude)
const [longitude, setLongitude] = useState<number | null>(radio.longitude)
const [radiusMeters, setRadiusMeters] = useState<number | null>(radio.radius_meters)
const [savingLocation, setSavingLocation] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
function refreshQueue() { function refreshQueue() {
...@@ -87,6 +94,28 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr ...@@ -87,6 +94,28 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr
} }
} }
async function handleSaveLocation() {
if (scope === 'local' && (latitude === null || longitude === null || radiusMeters === null)) {
setError('Place your station on the map to set its broadcast area.')
return
}
setSavingLocation(true)
setError(null)
try {
const { radio: updated } = await updateRadio(radio.id, {
scope,
latitude: scope === 'local' ? latitude! : undefined,
longitude: scope === 'local' ? longitude! : undefined,
radius_meters: scope === 'local' ? radiusMeters! : undefined,
})
onUpdated(updated)
} catch {
setError('Could not update the broadcast area.')
} finally {
setSavingLocation(false)
}
}
async function handleDelete() { async function handleDelete() {
if (!window.confirm(`Delete "${radio.name}"? This can't be undone.`)) return if (!window.confirm(`Delete "${radio.name}"? This can't be undone.`)) return
await deleteRadio(radio.id) await deleteRadio(radio.id)
...@@ -172,6 +201,35 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr ...@@ -172,6 +201,35 @@ export function RadioManageTab({ radio, onDeleted, onUpdated }: RadioManageTabPr
</Button> </Button>
</div> </div>
<div>
<p className="mb-2 text-sm font-semibold text-on-surface">Broadcast area</p>
<ToggleRow
icon={MapPin}
label="Tie to a real-world location"
description={scope === 'local' ? 'Only listeners inside your broadcast circle can tune in' : 'Off - anyone, anywhere can tune in'}
checked={scope === 'local'}
saving={savingLocation}
onToggle={() => setScope((s) => (s === 'local' ? 'worldwide' : 'local'))}
/>
{scope === 'local' && (
<div className="mt-3">
<RadioLocationPicker
latitude={latitude}
longitude={longitude}
radiusMeters={radiusMeters}
onChange={(lat, lon) => {
setLatitude(lat)
setLongitude(lon)
}}
onRadiusChange={setRadiusMeters}
/>
</div>
)}
<Button type="button" size="sm" variant="secondary" onClick={handleSaveLocation} disabled={savingLocation} className="mt-2">
Save broadcast area
</Button>
</div>
<Button type="button" variant="secondary" onClick={handleDelete} className="w-full gap-1.5 text-error"> <Button type="button" variant="secondary" onClick={handleDelete} className="w-full gap-1.5 text-error">
<Trash2 size={15} strokeWidth={2} /> <Trash2 size={15} strokeWidth={2} />
Delete station Delete station
......
...@@ -28,6 +28,7 @@ export function ToggleRow({ ...@@ -28,6 +28,7 @@ export function ToggleRow({
<p className="text-xs text-on-surface-variant">{description}</p> <p className="text-xs text-on-surface-variant">{description}</p>
</div> </div>
<button <button
type="button"
role="switch" role="switch"
aria-checked={checked} aria-checked={checked}
aria-label={label} aria-label={label}
......
...@@ -88,6 +88,7 @@ const BACKEND_DONE: DoneGroup[] = [ ...@@ -88,6 +88,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Tuning dial: granular drag + station snapping (2026-10-12): the native <input type="range"> was replaced with a custom pointer- and keyboard-driven dial (same pointer-capture-after-movement pattern as useSwipeAction) because a native range\'s drag sensitivity is fixed to element-width/(max-min) with no way to slow it down - dragging now reads raw pixel deltas against a fixed DIAL_PIXELS_PER_UNIT instead. The dial also snaps exactly onto any station within the same 0.3 tuning epsilon the backend already locks onto, with tick marks on the track showing where each station sits.', 'Tuning dial: granular drag + station snapping (2026-10-12): the native <input type="range"> was replaced with a custom pointer- and keyboard-driven dial (same pointer-capture-after-movement pattern as useSwipeAction) because a native range\'s drag sensitivity is fixed to element-width/(max-min) with no way to slow it down - dragging now reads raw pixel deltas against a fixed DIAL_PIXELS_PER_UNIT instead. The dial also snaps exactly onto any station within the same 0.3 tuning epsilon the backend already locks onto, with tick marks on the track showing where each station sits.',
'Radio artwork fix + dial redesign v2 (2026-10-13): custom station artwork wasn\'t rendering - storage.store_image returns a backend-relative path ("/images/7/x.png") meant to be loaded same-origin, but neither the dev vite proxy nor prod\'s nginx config had a rule for anything besides /api, so the browser requested it against its own origin and 404\'d. Both gained an /images proxy rule mirroring /api\'s (vite.config.ts; deploy/scripts/deploy.sh\'s generated nginx site config). Separately, the v1 dial (above) turned out to still feel disconnected: its thumb was positioned by percent-of-the-full-150-unit-range while drag sensitivity was a decoupled pixel constant, so the thumb visibly lagged far behind the finger - a real mismatch, not just "the range is big." Replaced with a scrolling-tape dial: a fixed center needle never moves, and a tape of whole-MHz ticks (plus taller, colored station ticks) scrolls underneath it at exactly the same px-per-MHz rate the drag itself reads at, so the marks track the finger 1:1 regardless of how wide the 50-200 range is. The dial now also snaps onto whole MHz values during a drag (WHOLE_NUMBER_SNAP_EPSILON, tighter than the station epsilon so it doesn\'t fight precision near a real station), each landed-on detent firing a single Vibration-API tick (feature-detected, silently a no-op where unsupported) rather than buzzing continuously through a sweep. New +/- buttons flank the frequency readout for an exact 0.1 nudge - deliberately routed through a separate step path that skips the whole-number magnet entirely, since a magnet strong enough to feel satisfying on a drag would otherwise make it impossible to ever press-step one tick away from a whole number.', 'Radio artwork fix + dial redesign v2 (2026-10-13): custom station artwork wasn\'t rendering - storage.store_image returns a backend-relative path ("/images/7/x.png") meant to be loaded same-origin, but neither the dev vite proxy nor prod\'s nginx config had a rule for anything besides /api, so the browser requested it against its own origin and 404\'d. Both gained an /images proxy rule mirroring /api\'s (vite.config.ts; deploy/scripts/deploy.sh\'s generated nginx site config). Separately, the v1 dial (above) turned out to still feel disconnected: its thumb was positioned by percent-of-the-full-150-unit-range while drag sensitivity was a decoupled pixel constant, so the thumb visibly lagged far behind the finger - a real mismatch, not just "the range is big." Replaced with a scrolling-tape dial: a fixed center needle never moves, and a tape of whole-MHz ticks (plus taller, colored station ticks) scrolls underneath it at exactly the same px-per-MHz rate the drag itself reads at, so the marks track the finger 1:1 regardless of how wide the 50-200 range is. The dial now also snaps onto whole MHz values during a drag (WHOLE_NUMBER_SNAP_EPSILON, tighter than the station epsilon so it doesn\'t fight precision near a real station), each landed-on detent firing a single Vibration-API tick (feature-detected, silently a no-op where unsupported) rather than buzzing continuously through a sweep. New +/- buttons flank the frequency readout for an exact 0.1 nudge - deliberately routed through a separate step path that skips the whole-number magnet entirely, since a magnet strong enough to feel satisfying on a drag would otherwise make it impossible to ever press-step one tick away from a whole number.',
'Fixed: global library search in Radio\'s queue manager (2026-10-13) - RadioManageTab\'s "Add song" reuses SongPicker, whose "Public Library" tab calls GET /soundmarks/song-library, which was still gated get_current_business_admin even though Radio hands this same picker to any station owner, admin or not. A plain user got a silent 403 (SongPicker swallows the error into an empty "No songs found" state, so nothing looked broken, it just never returned results). Relaxed to get_current_user, same reasoning as the geocode endpoints above - a plain title/artist search has nothing business-admin-specific about it. Confirmed live with a real plain-role account: 403 before the fix, real results after.', 'Fixed: global library search in Radio\'s queue manager (2026-10-13) - RadioManageTab\'s "Add song" reuses SongPicker, whose "Public Library" tab calls GET /soundmarks/song-library, which was still gated get_current_business_admin even though Radio hands this same picker to any station owner, admin or not. A plain user got a silent 403 (SongPicker swallows the error into an empty "No songs found" state, so nothing looked broken, it just never returned results). Relaxed to get_current_user, same reasoning as the geocode endpoints above - a plain title/artist search has nothing business-admin-specific about it. Confirmed live with a real plain-role account: 403 before the fix, real results after.',
'Local-scope UX pass (2026-10-14): the "Reach: Worldwide/Local" pill pair in RadioCreateForm read as two unrelated buttons rather than one feature being switched on, so it was rebuilt as a single ToggleRow ("Tie to a real-world location") - the same shared switch component Settings/Onboarding already use, and the same wording Rooms\' own location toggle uses, instead of each feature inventing its own phrasing. Fixed a real latent bug surfaced by that change: ToggleRow\'s switch <button> had no explicit type, so clicking it inside an actual <form> (its first use inside one) defaulted to type="submit" and silently submitted the surrounding form with stale state instead of just flipping the toggle - fixed in the shared component itself (type="button"), not worked around locally, since any future form usage would hit the same bug. The broadcast-radius circle on the map was real but easy to miss - fillOpacity 0.12 on a dark basemap - strengthened to a dashed, higher-contrast outline, skipped entirely for the one frame before a real radius exists (previously flashed as a literal zero-radius circle), and paired with an explicit "~Xkm radius" badge on the map itself rather than only a caption line below it. The location+circle picker was also only ever reachable once, during station creation - RadioManageTab gained the same ToggleRow + RadioLocationPicker + a "Save broadcast area" action so an existing station\'s broadcast area is visible and editable after creation too, not just in the one-time create flow (PATCH /radio/{id} already supported this; only the frontend was missing the wiring).',
], ],
}, },
{ {
......
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