Commit bfeb291d authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Play library-matched Discovery hits, add song+album search to Library

Discovery history now shows a real Play button (not just a static
title/artist) for any match that's already in the caller's own
library, wired into the same PlayerContext/toggle pattern the Library
page uses.

Library page gets a search box: songs and albums (a derived grouping,
click to expand and play its tracks) as separate result sections while
searching, replacing the plain list rather than filtering it in place.
Factored the row markup into a shared SongRow component - it's now
reused by the full list, search's Songs section, and expanded album
tracks instead of being duplicated three times.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 03d757b0
Pipeline #1123 canceled with stage
......@@ -9,6 +9,9 @@ export interface DiscoveredSong {
coverart: string | null
detected_at: string
liked: boolean | null
/** Set when this match's title+artist already exists in the caller's own library - lets the
* UI offer a real Play button instead of just showing what was detected. */
library_song_id: number | null
}
export function getDiscoveryHistory() {
......
......@@ -17,8 +17,19 @@ export function getLibrary() {
return apiFetch<{ status: string; library: LibrarySong[] }>('/library')
}
export interface AlbumMatch {
album: string
artist: string
coverart: string | null
track_count: number
songs: LibrarySong[]
}
/** Universal search across the caller's own library - songs matching title/artist/genre, plus
* albums (a derived (album, artist) grouping, not a separate entity) matching album name or
* artist. */
export function searchLibrary(query: string) {
return apiFetch<{ status: string; results: LibrarySong[] }>('/library/search', {
return apiFetch<{ status: string; songs: LibrarySong[]; albums: AlbumMatch[] }>('/library/search', {
method: 'POST',
form: { query },
})
......
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor, within } 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'
......@@ -6,6 +6,7 @@ import { Discovery } from './Discovery'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as discoveryApi from '../api/discovery'
import * as streamApi from '../api/stream'
const SONG = {
id: 1,
......@@ -16,6 +17,7 @@ const SONG = {
coverart: null,
detected_at: '2026-01-01T00:00:00Z',
liked: null,
library_song_id: null,
}
/** Stands in for the real MediaRecorder - jsdom has no audio capture support at all, so this
......@@ -199,4 +201,28 @@ describe('Discovery', () => {
expect(swipeSpy).toHaveBeenCalledWith(1, true)
})
it('shows no Play button for a match that is not in the library', async () => {
vi.spyOn(discoveryApi, 'getDiscoveryHistory').mockResolvedValue({ status: 'success', history: [SONG] })
renderDiscovery()
await screen.findByText('Test Song')
expect(screen.queryByRole('button', { name: 'Play' })).not.toBeInTheDocument()
})
it('plays a match that already exists in the library', async () => {
const matched = { ...SONG, library_song_id: 42 }
vi.spyOn(discoveryApi, 'getDiscoveryHistory').mockResolvedValue({ status: 'success', history: [matched] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderDiscovery()
const row = (await screen.findByText('Test Song')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(fetchStreamUrl).toHaveBeenCalledWith(42)
})
expect(await within(row).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
})
import { useEffect, useRef, useState } from 'react'
import { Ear, Heart, Music2, X } from 'lucide-react'
import { Ear, Heart, Music2, Pause, Play, 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'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
function toPlayable(song: DiscoveredSong): PlayableSong {
return { id: song.library_song_id!, title: song.title, artist: song.artist, coverart: song.coverart }
}
const LISTEN_SECONDS = 5
......@@ -42,6 +47,7 @@ export function Discovery() {
const [message, setMessage] = useState<string | null>(null)
const [listening, setListening] = useState(false)
const [countdown, setCountdown] = useState(LISTEN_SECONDS)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const recorderRef = useRef<MediaRecorder | null>(null)
const streamRef = useRef<MediaStream | null>(null)
......@@ -194,7 +200,9 @@ export function Discovery() {
)}
<ul className="divide-y divide-neutral-800/80">
{history.map((song) => (
{history.map((song) => {
const isCurrent = song.library_song_id !== null && currentSong?.id === song.library_song_id
return (
<li key={song.id} className="flex items-center gap-4 py-3">
{song.coverart ? (
<img src={song.coverart} alt="" className="h-10 w-10 shrink-0 rounded-md object-cover" />
......@@ -207,6 +215,22 @@ export function Discovery() {
<p className="truncate font-medium text-white">{song.title}</p>
<p className="truncate text-sm text-neutral-400">{song.artist}</p>
</div>
{song.library_song_id !== null && (
<button
onClick={() => toggle(toPlayable(song), history.filter((s) => s.library_song_id !== null).map(toPlayable))}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded-full text-neutral-400 transition-all duration-150 hover:text-white active:scale-90 disabled:cursor-not-allowed"
>
{isCurrent && streamLoading ? (
<span className="h-4 w-4 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={18} strokeWidth={2} fill="currentColor" />
) : (
<Play size={18} strokeWidth={2} fill="currentColor" />
)}
</button>
)}
<button
onClick={() => handleSwipe(song.id, true)}
aria-label="Like"
......@@ -226,7 +250,8 @@ export function Discovery() {
<X size={19} strokeWidth={2} />
</button>
</li>
))}
)
})}
</ul>
</Layout>
)
......
......@@ -118,4 +118,72 @@ describe('Library', () => {
// also start playback.
expect(fetchStreamUrl).not.toHaveBeenCalled()
})
it('searches and shows separate Songs and Albums sections', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const searchLibrary = vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({
status: 'success',
songs: [{ ...SONG, id: 2, title: 'Rio', album: 'Rio' }],
albums: [{ album: 'Astronaut', artist: 'Duran Duran', coverart: null, track_count: 1, songs: [SONG] }],
})
renderLibrary()
await screen.findByText('Invisible')
await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'duran')
await waitFor(() => expect(searchLibrary).toHaveBeenCalledWith('duran'))
expect(await screen.findByText('Albums')).toBeInTheDocument()
expect(screen.getByText('Astronaut')).toBeInTheDocument()
expect(screen.getByText('Duran Duran · 1 track')).toBeInTheDocument()
expect(screen.getByText('Songs')).toBeInTheDocument()
expect(screen.getByText('Rio')).toBeInTheDocument()
// The full unfiltered library list is replaced while a search is active, not shown alongside it.
expect(screen.queryByText('Invisible')).not.toBeInTheDocument()
})
it('expands an album to show and play its tracks', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({
status: 'success',
songs: [],
albums: [{ album: 'Astronaut', artist: 'Duran Duran', coverart: null, track_count: 1, songs: [SONG] }],
})
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'astronaut')
const albumButton = await screen.findByRole('button', { name: /Astronaut/ })
expect(screen.queryByText('Invisible')).not.toBeInTheDocument()
await userEvent.click(albumButton)
const trackRow = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(trackRow).getByRole('button', { name: 'Play' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(1))
})
it('shows an empty state for a search with no matches', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({ status: 'success', songs: [], albums: [] })
renderLibrary()
await screen.findByText('Invisible')
await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'nothing matches this')
expect(await screen.findByText(/No results for/)).toBeInTheDocument()
})
it('clearing the search returns to the full library list', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({ status: 'success', songs: [], albums: [] })
renderLibrary()
const input = screen.getByPlaceholderText('Search songs and albums')
await userEvent.type(input, 'nothing matches this')
await screen.findByText(/No results for/)
await userEvent.clear(input)
expect(await screen.findByText('Invisible')).toBeInTheDocument()
})
})
This diff is collapsed.
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