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()
})
})
import { useEffect, useState } from 'react'
import { ListPlus, Music2, Pause, Play } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library'
import { ListPlus, Music2, Pause, Play, Search } from 'lucide-react'
import { getLibrary, searchLibrary, type AlbumMatch, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
......@@ -19,12 +20,81 @@ function toPlayable(song: LibrarySong): PlayableSong {
}
}
/** One playable row - shared by the full library list, search's "Songs" section, and an
* expanded album's tracks, so play/pause/add-to-playlist behavior stays identical everywhere
* a song can appear instead of being reimplemented per context. */
function SongRow({
song,
queue,
onAddToPlaylist,
}: {
song: LibrarySong
queue: LibrarySong[]
onAddToPlaylist: (song: LibrarySong) => void
}) {
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const isCurrent = currentSong?.id === song.id
return (
<li className="-mx-2 flex items-center gap-1 rounded-lg pr-2 hover:bg-white/5">
{/* The whole row plays the song, not just the little icon on the right - the icon is
now a status indicator rendered inside this same button, not a separate control.
The "add to playlist" button is a sibling, not nested inside this one, so it can
have its own click target without either button triggering the other. */}
<button
onClick={() => toggle(toPlayable(song), queue.map(toPlayable))}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex min-w-0 flex-1 items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
>
{song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{song.title}</p>
<p className="truncate text-sm text-neutral-400">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
<button
onClick={() => onAddToPlaylist(song)}
aria-label={`Add ${song.title} to a playlist`}
className="shrink-0 rounded-full p-2 text-neutral-500 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</li>
)
}
function albumKey(album: AlbumMatch): string {
return `${album.album}::${album.artist}`
}
export function Library() {
const [songs, setSongs] = useState<LibrarySong[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<LibrarySong | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<{ songs: LibrarySong[]; albums: AlbumMatch[] } | null>(null)
const [searching, setSearching] = useState(false)
const [expandedAlbum, setExpandedAlbum] = useState<string | null>(null)
useEffect(() => {
getLibrary()
......@@ -33,9 +103,36 @@ export function Library() {
.finally(() => setLoading(false))
}, [])
useEffect(() => {
if (!query.trim()) {
setSearchResults(null)
return
}
setSearching(true)
const handle = setTimeout(() => {
searchLibrary(query.trim())
.then((res) => setSearchResults({ songs: res.songs, albums: res.albums }))
.catch(() => setSearchResults({ songs: [], albums: [] }))
.finally(() => setSearching(false))
}, 400)
return () => clearTimeout(handle)
}, [query])
const isSearching = searchResults !== null
return (
<Layout title="Library">
{loading && (
<div className="relative mb-6">
<Search size={16} strokeWidth={2} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500" />
<Input
placeholder="Search songs and albums"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9"
/>
</div>
{loading && !isSearching && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
<SkeletonRow />
......@@ -43,61 +140,80 @@ export function Library() {
</div>
)}
{error && <p className="text-sm text-red-400">{error}</p>}
{!loading && !error && songs.length === 0 && (
{!loading && !error && !isSearching && songs.length === 0 && (
<EmptyState icon={Music2} message="No songs yet - tag something from Telegram to see it here." />
)}
<ul className="divide-y divide-neutral-800/80">
{songs.map((song) => {
const isCurrent = currentSong?.id === song.id
return (
<li key={song.id} className="-mx-2 flex items-center gap-1 rounded-lg pr-2 hover:bg-white/5">
{/* The whole row plays the song, not just the little icon on the right - the
icon is now a status indicator rendered inside this same button, not a
separate control. The "add to playlist" button is a sibling, not nested
inside this one, so it can have its own click target without either button
triggering the other. */}
<button
onClick={() => toggle(toPlayable(song), songs.map(toPlayable))}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex min-w-0 flex-1 items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
>
{song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{song.title}</p>
<p className="truncate text-sm text-neutral-400">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
<button
onClick={() => setAddingSong(song)}
aria-label={`Add ${song.title} to a playlist`}
className="shrink-0 rounded-full p-2 text-neutral-500 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</li>
)
})}
</ul>
{isSearching ? (
<>
{searching && (
<div className="space-y-3">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{!searching && searchResults.songs.length === 0 && searchResults.albums.length === 0 && (
<EmptyState icon={Search} message={`No results for "${query.trim()}"`} />
)}
{!searching && searchResults.albums.length > 0 && (
<div className="mb-6">
<h2 className="mb-2 text-xs font-medium uppercase tracking-wider text-neutral-500">Albums</h2>
<ul className="divide-y divide-neutral-800/80">
{searchResults.albums.map((album) => {
const key = albumKey(album)
const expanded = expandedAlbum === key
return (
<li key={key}>
<button
onClick={() => setExpandedAlbum(expanded ? null : key)}
aria-expanded={expanded}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
{album.coverart ? (
<img src={album.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{album.album}</p>
<p className="truncate text-sm text-neutral-400">
{album.artist} · {album.track_count} track{album.track_count === 1 ? '' : 's'}
</p>
</div>
</button>
{expanded && (
<ul className="mb-2 divide-y divide-neutral-800/80 pl-4">
{album.songs.map((s) => (
<SongRow key={s.id} song={s} queue={album.songs} onAddToPlaylist={setAddingSong} />
))}
</ul>
)}
</li>
)
})}
</ul>
</div>
)}
{!searching && searchResults.songs.length > 0 && (
<div>
<h2 className="mb-2 text-xs font-medium uppercase tracking-wider text-neutral-500">Songs</h2>
<ul className="divide-y divide-neutral-800/80">
{searchResults.songs.map((song) => (
<SongRow key={song.id} song={song} queue={searchResults.songs} onAddToPlaylist={setAddingSong} />
))}
</ul>
</div>
)}
</>
) : (
<ul className="divide-y divide-neutral-800/80">
{songs.map((song) => (
<SongRow key={song.id} song={song} queue={songs} onAddToPlaylist={setAddingSong} />
))}
</ul>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
......
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