Commit 5c07defd authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add locate-me to the soundmark map, and automatic mic listening to Discovery

LocationPicker: a locate-me button sits on the map itself now instead
of requiring an address search - tapping it drops the pin at the
browser's location and reverse-geocodes it into the address field, so
there's something readable to correct rather than just bare
coordinates. Search, click, and drag all still work exactly the same
afterward.

Discovery: replaced the file-drop-only control (identify's docstring
already said "from the microphone", but nothing actually captured
audio) with a real one - tap once, it records exactly 5 seconds
automatically via getUserMedia/MediaRecorder with a pulsing/countdown
animation, then submits through the same identify pipeline. Falls back
to the old file-drop control on browsers without mic support instead
of just breaking.

Added Discovery's first tests (previously zero coverage) alongside 4
new LocationPicker tests for the locate-me flow.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 06806f34
Pipeline #1118 canceled with stage
......@@ -157,6 +157,14 @@ export function geocodeAddress(q: string) {
return apiFetch<{ status: string; results: GeocodeResult[] }>(`/soundmarks/geocode?${params}`)
}
/** The inverse of geocodeAddress - given coordinates (e.g. from the browser's "locate me"),
* looks up a human-readable address to pre-fill the location picker's search field with.
* display_name is null if Nominatim couldn't find anything at those coordinates. */
export function reverseGeocode(lat: number, lon: number) {
const params = new URLSearchParams({ lat: String(lat), lon: String(lon) })
return apiFetch<{ status: string; display_name: string | null }>(`/soundmarks/reverse-geocode?${params}`)
}
export interface SoundmarkProposal {
id: number
song: SoundmarkSong | null
......
......@@ -5,6 +5,18 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { LocationPicker } from './LocationPicker'
import * as soundmarksApi from '../api/soundmarks'
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 48.8584, longitude: 2.2945 } } as GeolocationPosition
const geolocation = {
getCurrentPosition: vi.fn((success: PositionCallback, error?: PositionErrorCallback) => {
if (succeed) success(position)
else error?.({ code, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 } as GeolocationPositionError)
}),
}
vi.stubGlobal('navigator', { ...navigator, geolocation })
return geolocation
}
function Controlled({ initialLat = null, initialLon = null }: { initialLat?: number | null; initialLon?: number | null }) {
// Mirrors how AdminPanel actually uses LocationPicker - a controlled lat/lon pair updated
// via onChange, not the picker holding its own coordinate state.
......@@ -28,6 +40,7 @@ function Controlled({ initialLat = null, initialLon = null }: { initialLat?: num
describe('LocationPicker', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('shows no coordinates hint text until a location is picked', () => {
......@@ -66,4 +79,55 @@ describe('LocationPicker', () => {
render(<Controlled initialLat={48.8584} initialLon={2.2945} />)
expect(screen.getByText(/48.85840, 2.29450/)).toBeInTheDocument()
})
it('locate me drops the pin at the current position and fills the address from reverse geocoding', async () => {
vi.stubGlobal('isSecureContext', true)
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'reverseGeocode').mockResolvedValue({
status: 'success',
display_name: '48 Rue de Rivoli, Paris, France',
})
render(<Controlled />)
await userEvent.click(screen.getByLabelText('Use my current location'))
await waitFor(() => {
expect(screen.getByTestId('coords')).toHaveTextContent('48.8584,2.2945')
})
expect(await screen.findByDisplayValue('48 Rue de Rivoli, Paris, France')).toBeInTheDocument()
})
it('locate me still places the pin even if reverse geocoding finds no address', async () => {
vi.stubGlobal('isSecureContext', true)
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'reverseGeocode').mockResolvedValue({ status: 'success', display_name: null })
render(<Controlled />)
await userEvent.click(screen.getByLabelText('Use my current location'))
await waitFor(() => {
expect(screen.getByTestId('coords')).toHaveTextContent('48.8584,2.2945')
})
})
it('shows an error when location access is denied', async () => {
vi.stubGlobal('isSecureContext', true)
mockGeolocation({ succeed: false, code: 1 })
render(<Controlled />)
await userEvent.click(screen.getByLabelText('Use my current location'))
expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument()
})
it('refuses to request location on an insecure origin', async () => {
vi.stubGlobal('isSecureContext', false)
const geolocation = mockGeolocation({ succeed: true })
render(<Controlled />)
await userEvent.click(screen.getByLabelText('Use my current location'))
expect(await screen.findByText(/secure \(https:\/\/\) connection/)).toBeInTheDocument()
expect(geolocation.getCurrentPosition).not.toHaveBeenCalled()
})
})
import { useEffect, useState } from 'react'
import { MapContainer, Marker, TileLayer, useMap, useMapEvents } from 'react-leaflet'
import type { LeafletMouseEvent } from 'leaflet'
import { MapPin, Search } from 'lucide-react'
import { LocateFixed, MapPin, Search } from 'lucide-react'
import { Input } from './ui/Input'
import { geocodeAddress, type GeocodeResult } from '../api/soundmarks'
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
......@@ -46,6 +46,8 @@ export function LocationPicker({ latitude, longitude, onChange }: LocationPicker
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()) {
......@@ -70,6 +72,51 @@ export function LocationPicker({ latitude, longitude, onChange }: LocationPicker
setShowResults(false)
}
/** Drops the pin at the browser's current location and pre-fills the address field from it -
* a starting point, not a lock-in: search, click, or drag still work exactly the same
* afterward to correct it. */
function handleLocateMe() {
setLocateError(null)
if (!navigator.geolocation) {
setLocateError("Your browser doesn't support location services.")
return
}
// Same secure-context check as the Nearby page's live location - the Geolocation API
// fails with the same "permission denied" code on plain http:// as a real user decline,
// so without this check the error message would send someone chasing a browser setting
// that can't fix it.
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, this only fills
// in the address text.
})
.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
......@@ -126,9 +173,20 @@ export function LocationPicker({ latitude, longitude, onChange }: LocationPicker
/>
)}
</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-neutral-700 bg-neutral-900/90 text-neutral-200 shadow-lg backdrop-blur transition-colors duration-150 hover:bg-neutral-800 disabled:opacity-50"
>
<LocateFixed size={17} strokeWidth={2} className={locating ? 'animate-pulse' : ''} />
</button>
</div>
{locateError && <p className="mt-1 text-xs text-red-400">{locateError}</p>}
<p className="mt-1 text-xs text-neutral-500">
Search an address, click the map, or drag the pin to fine-tune.
Search an address, tap <LocateFixed size={11} strokeWidth={2} className="inline -translate-y-px" />, or click the map to place the pin - drag to fine-tune.
{hasPin && ` ${latitude.toFixed(5)}, ${longitude.toFixed(5)}`}
</p>
</div>
......
import { act, fireEvent, 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 { Discovery } from './Discovery'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as discoveryApi from '../api/discovery'
const SONG = {
id: 1,
user_id: 1,
title: 'Test Song',
artist: 'Test Artist',
genre: 'Pop',
coverart: null,
detected_at: '2026-01-01T00:00:00Z',
liked: null,
}
/** Stands in for the real MediaRecorder - jsdom has no audio capture support at all, so this
* is what makes the "record 5 seconds automatically" flow testable without a browser. start()
* fires one synchronous data chunk (a real recorder would stream several over time, but the
* component only cares that *something* arrives before stop()); stop() is driven by the
* component's own countdown, not by the test calling it directly - mirrors how a real 5-second
* auto-stop actually happens. */
class FakeMediaRecorder {
static isTypeSupported(type: string) {
return type === 'audio/webm'
}
ondataavailable: ((e: { data: Blob }) => void) | null = null
onstop: (() => void) | null = null
mimeType: string
constructor(_stream: MediaStream, options?: { mimeType?: string }) {
this.mimeType = options?.mimeType ?? 'audio/webm'
}
start() {
this.ondataavailable?.({ data: new Blob(['fake-audio-bytes']) })
}
stop() {
this.onstop?.()
}
}
function mockMicSupport() {
const stopTrack = vi.fn()
const stream = { getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream
const getUserMedia = vi.fn().mockResolvedValue(stream)
vi.stubGlobal('navigator', { ...navigator, mediaDevices: { getUserMedia } })
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
return { getUserMedia, stopTrack }
}
function renderDiscovery() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Discovery />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Discovery', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.spyOn(discoveryApi, 'getDiscoveryHistory').mockResolvedValue({ status: 'success', history: [] })
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('falls back to a file-drop control when the browser has no microphone support', async () => {
// jsdom defines neither navigator.mediaDevices nor MediaRecorder by default - this is the
// real, unmocked test environment, exercising the actual feature-detection fallback rather
// than a simulated "unsupported browser".
renderDiscovery()
expect(await screen.findByText("Drop a short clip of what's playing to identify it")).toBeInTheDocument()
expect(screen.queryByLabelText(/Listen for what/)).not.toBeInTheDocument()
})
it('records 5 seconds automatically, shows a listening state, and submits the clip', async () => {
mockMicSupport()
const listenSpy = vi.spyOn(discoveryApi, 'listen').mockResolvedValue({
status: 'success',
detected: { title: 'Found Song', artist: 'Found Artist' },
discovery_id: 42,
})
renderDiscovery()
const button = await screen.findByLabelText(/Listen for what/)
// Fake timers have to be active *before* the click, since that's what starts the
// component's countdown setInterval - switching to fake timers afterward wouldn't take
// over a real interval already running. fireEvent (not userEvent) deliberately - userEvent's
// own internal delay handling doesn't play well with fake timers here, and a plain click
// event is all this needs: React calls the onClick handler synchronously either way.
vi.useFakeTimers()
try {
await act(async () => {
fireEvent.click(button)
})
expect(screen.getByLabelText(/Listening, 5 seconds left/)).toBeInTheDocument()
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
} finally {
vi.useRealTimers()
}
expect(listenSpy).toHaveBeenCalledTimes(1)
const submittedFile = listenSpy.mock.calls[0][0]
expect(submittedFile).toBeInstanceOf(File)
expect(submittedFile.type).toBe('audio/webm')
await waitFor(() => {
expect(screen.getByText('Detected: Found Song - Found Artist')).toBeInTheDocument()
})
// The button returns to its idle label once identification finishes.
expect(await screen.findByLabelText(/Listen for what/)).toBeInTheDocument()
})
it('releases the microphone once recording stops', async () => {
const { stopTrack } = mockMicSupport()
vi.spyOn(discoveryApi, 'listen').mockResolvedValue({ status: 'success', detected: {}, discovery_id: 1 })
renderDiscovery()
const button = await screen.findByLabelText(/Listen for what/)
vi.useFakeTimers()
try {
await act(async () => {
fireEvent.click(button)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
} finally {
vi.useRealTimers()
}
expect(stopTrack).toHaveBeenCalled()
})
it('shows an error if microphone permission is denied', async () => {
vi.stubGlobal('navigator', {
...navigator,
mediaDevices: { getUserMedia: vi.fn().mockRejectedValue(new Error('Permission denied')) },
})
vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
const listenSpy = vi.spyOn(discoveryApi, 'listen')
renderDiscovery()
await userEvent.click(await screen.findByLabelText(/Listen for what/))
expect(await screen.findByText(/Couldn't access the microphone/)).toBeInTheDocument()
expect(listenSpy).not.toHaveBeenCalled()
})
it('swiping like/dismiss updates the history list', async () => {
vi.spyOn(discoveryApi, 'getDiscoveryHistory').mockResolvedValue({ status: 'success', history: [SONG] })
const swipeSpy = vi.spyOn(discoveryApi, 'swipe').mockResolvedValue({ status: 'success', message: 'ok' })
renderDiscovery()
await userEvent.click(await screen.findByLabelText('Like'))
expect(swipeSpy).toHaveBeenCalledWith(1, true)
})
})
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Ear, Heart, Music2, X } from 'lucide-react'
import { Layout } from '../components/Layout'
import { getDiscoveryHistory, listen, swipe, type DiscoveredSong } from '../api/discovery'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
const LISTEN_SECONDS = 5
function checkMicSupport(): boolean {
return typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia && typeof MediaRecorder !== 'undefined'
}
function extensionFor(mimeType: string): string {
if (mimeType.includes('mp4')) return 'm4a'
if (mimeType.includes('ogg')) return 'ogg'
return 'webm'
}
export function Discovery() {
// Lazy initializer so this reflects navigator/MediaRecorder at mount time, not module-import
// time - matters for tests, which stub those globals per-test before rendering.
const [micSupported] = useState(checkMicSupport)
const [history, setHistory] = useState<DiscoveredSong[]>([])
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
const [listening, setListening] = useState(false)
const [countdown, setCountdown] = useState(LISTEN_SECONDS)
const recorderRef = useRef<MediaRecorder | null>(null)
const streamRef = useRef<MediaStream | null>(null)
const chunksRef = useRef<Blob[]>([])
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
function refresh() {
getDiscoveryHistory()
......@@ -19,6 +41,19 @@ export function Discovery() {
useEffect(refresh, [])
function stopStream() {
streamRef.current?.getTracks().forEach((t) => t.stop())
streamRef.current = null
if (intervalRef.current !== null) {
clearInterval(intervalRef.current)
intervalRef.current = null
}
}
// Releases the microphone if the user navigates away mid-recording, instead of leaving it
// captured until the browser tab itself closes.
useEffect(() => stopStream, [])
async function handleListen(file: File) {
setBusy(true)
setMessage(null)
......@@ -37,6 +72,48 @@ export function Discovery() {
}
}
async function startListening() {
setMessage(null)
let stream: MediaStream
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true })
} catch {
setMessage("Couldn't access the microphone - check your browser's permission for this site.")
return
}
streamRef.current = stream
const mimeType = ['audio/webm', 'audio/mp4', 'audio/ogg'].find((t) => MediaRecorder.isTypeSupported(t))
const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream)
recorderRef.current = recorder
chunksRef.current = []
recorder.ondataavailable = (e) => {
if (e.data.size > 0) chunksRef.current.push(e.data)
}
recorder.onstop = () => {
stopStream()
setListening(false)
const type = recorder.mimeType || 'audio/webm'
const blob = new Blob(chunksRef.current, { type })
handleListen(new File([blob], `clip.${extensionFor(type)}`, { type }))
}
recorder.start()
setListening(true)
setCountdown(LISTEN_SECONDS)
intervalRef.current = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
recorder.stop()
return 0
}
return prev - 1
})
}, 1000)
}
async function handleSwipe(songId: number, liked: boolean) {
await swipe(songId, liked)
setHistory((h) => h.map((s) => (s.id === songId ? { ...s, liked } : s)))
......@@ -44,6 +121,36 @@ export function Discovery() {
return (
<Layout title="Discovery">
{micSupported ? (
<div className="mb-8 flex flex-col items-center gap-3 rounded-xl border border-neutral-800 p-8 text-center">
<button
type="button"
onClick={startListening}
disabled={listening || busy}
aria-label={listening ? `Listening, ${countdown} seconds left` : 'Listen for what’s playing'}
className="relative flex h-20 w-20 items-center justify-center rounded-full transition-transform duration-150 active:scale-95 disabled:active:scale-100"
>
{listening && (
<>
<span className="absolute inset-0 animate-ping rounded-full bg-emerald-500/30" />
<span className="absolute inset-0 rounded-full bg-emerald-500/10" />
</>
)}
<span
className={`relative flex h-20 w-20 items-center justify-center rounded-full border transition-colors duration-150 ${
listening
? 'border-emerald-500 bg-emerald-500/15 text-emerald-400'
: 'border-neutral-700 bg-neutral-900 text-neutral-400 hover:border-neutral-600 hover:text-neutral-200'
}`}
>
{listening ? <span className="text-xl font-semibold tabular-nums">{countdown}</span> : <Ear size={26} strokeWidth={1.5} />}
</span>
</button>
<span className="text-sm text-neutral-400">
{listening ? 'Listening…' : busy ? 'Identifying…' : "Tap to identify what's playing - listens for 5 seconds"}
</span>
</div>
) : (
<label className="mb-8 flex cursor-pointer flex-col items-center gap-3 rounded-xl border border-dashed border-neutral-700 p-8 text-center transition-colors duration-150 hover:border-neutral-600 hover:bg-neutral-900/50">
<Ear size={26} strokeWidth={1.5} className="text-neutral-500" />
<span className="text-sm text-neutral-400">Drop a short clip of what's playing to identify it</span>
......@@ -54,8 +161,9 @@ export function Discovery() {
onChange={(e) => e.target.files?.[0] && handleListen(e.target.files[0])}
className="hidden"
/>
{busy && <span className="text-xs text-neutral-500">Listening…</span>}
{busy && <span className="text-xs text-neutral-500">Identifying…</span>}
</label>
)}
{message && <p className="-mt-4 mb-6 text-sm text-emerald-400">{message}</p>}
<h2 className="mb-3 text-xs font-medium uppercase tracking-wider text-neutral-500">Last 24 hours</h2>
......
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