Commit bba848ef authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Dedicated album page, route-level code splitting, lyrics affordance fix

Album cards/rows now navigate to a real /library/album page (SongRow
extracted to its own component so both Library and the new page share
it) showing tracks in genuine order via the backend's new endpoint,
replacing the same-day expand-in-place version - starting playback
from any track queues the rest of the real album order behind it.

Every route is now a React.lazy() chunk instead of one ~590KB bundle
loaded before any page could render (down to ~397KB initial + per-
route chunks fetched on demand); Library/Playlists cover art also
loads lazily so a long list doesn't compete with the requests that
matter for first paint.

FullPlayer's inline lyric line gets a small Quote icon - couldn't
reproduce a "lyrics not shown" report after testing 8 real library
songs, but plain gray text not visually reading as an interactive
lyrics preview was a plausible contributor either way.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 95b835fc
Pipeline #1162 failed with stage
in 14 minutes and 55 seconds
import { lazy, Suspense } from 'react'
import { Navigate, Route, Routes } from 'react-router-dom' import { Navigate, Route, Routes } from 'react-router-dom'
import { Library } from './pages/Library'
import { Playlists } from './pages/Playlists'
import { TelegramLink } from './pages/TelegramLink'
import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery'
import { Social } from './pages/Social'
import { Remix } from './pages/Remix'
import { Soundmarks } from './pages/Soundmarks'
import { BusinessPanel } from './pages/BusinessPanel'
import { AdminPanel } from './pages/AdminPanel'
import { Roadmap } from './pages/Roadmap'
import { Login } from './pages/Login'
import { ProtectedRoute } from './components/ProtectedRoute' import { ProtectedRoute } from './components/ProtectedRoute'
import { RequireRole } from './components/RequireRole' import { RequireRole } from './components/RequireRole'
// Lazy, not eager, imports - every page used to ship in one ~590KB bundle loaded before *any*
// route could render, including the very first one someone hits (Login or Library). Splitting
// per-route means the browser only fetches the JS the current page actually needs; navigating
// to a route not visited yet fetches its chunk on demand (and caches it for next time).
const Library = lazy(() => import('./pages/Library').then((m) => ({ default: m.Library })))
const AlbumDetail = lazy(() => import('./pages/AlbumDetail').then((m) => ({ default: m.AlbumDetail })))
const Playlists = lazy(() => import('./pages/Playlists').then((m) => ({ default: m.Playlists })))
const TelegramLink = lazy(() => import('./pages/TelegramLink').then((m) => ({ default: m.TelegramLink })))
const Upload = lazy(() => import('./pages/Upload').then((m) => ({ default: m.Upload })))
const Discovery = lazy(() => import('./pages/Discovery').then((m) => ({ default: m.Discovery })))
const Social = lazy(() => import('./pages/Social').then((m) => ({ default: m.Social })))
const Remix = lazy(() => import('./pages/Remix').then((m) => ({ default: m.Remix })))
const Soundmarks = lazy(() => import('./pages/Soundmarks').then((m) => ({ default: m.Soundmarks })))
const BusinessPanel = lazy(() => import('./pages/BusinessPanel').then((m) => ({ default: m.BusinessPanel })))
const AdminPanel = lazy(() => import('./pages/AdminPanel').then((m) => ({ default: m.AdminPanel })))
const Roadmap = lazy(() => import('./pages/Roadmap').then((m) => ({ default: m.Roadmap })))
const Login = lazy(() => import('./pages/Login').then((m) => ({ default: m.Login })))
function protect(element: React.ReactElement) { function protect(element: React.ReactElement) {
return <ProtectedRoute>{element}</ProtectedRoute> return <ProtectedRoute>{element}</ProtectedRoute>
} }
function RouteFallback() {
// Deliberately bare (no Layout chrome) - Layout itself lives inside each lazy page, so it
// isn't available to wrap this fallback with, and pulling it in separately here would just
// reintroduce the eager-bundle cost this split exists to avoid.
return (
<div className="flex h-dvh items-center justify-center bg-background">
<span className="h-6 w-6 animate-spin rounded-full border-2 border-outline-variant border-t-on-surface" />
</div>
)
}
export function App() { export function App() {
return ( return (
<Routes> <Suspense fallback={<RouteFallback />}>
<Route path="/login" element={<Login />} /> <Routes>
<Route path="/library" element={protect(<Library />)} /> <Route path="/login" element={<Login />} />
<Route path="/playlists" element={protect(<Playlists />)} /> <Route path="/library" element={protect(<Library />)} />
<Route path="/telegram-link" element={protect(<TelegramLink />)} /> <Route path="/library/album" element={protect(<AlbumDetail />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/discovery" element={protect(<Discovery />)} /> <Route path="/telegram-link" element={protect(<TelegramLink />)} />
<Route path="/social" element={protect(<Social />)} /> <Route path="/upload" element={protect(<Upload />)} />
<Route path="/remix" element={protect(<Remix />)} /> <Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/soundmarks" element={protect(<Soundmarks />)} /> <Route path="/social" element={protect(<Social />)} />
{/* Old, now-merged routes - redirect rather than 404 in case anything still links here. */} <Route path="/remix" element={protect(<Remix />)} />
<Route path="/rooms" element={<Navigate to="/social" replace />} /> <Route path="/soundmarks" element={protect(<Soundmarks />)} />
<Route path="/channels" element={<Navigate to="/social" replace />} /> {/* Old, now-merged routes - redirect rather than 404 in case anything still links here. */}
<Route path="/posts" element={<Navigate to="/social" replace />} /> <Route path="/rooms" element={<Navigate to="/social" replace />} />
<Route path="/nearby" element={<Navigate to="/soundmarks" replace />} /> <Route path="/channels" element={<Navigate to="/social" replace />} />
<Route path="/drops" element={<Navigate to="/soundmarks" replace />} /> <Route path="/posts" element={<Navigate to="/social" replace />} />
<Route <Route path="/nearby" element={<Navigate to="/soundmarks" replace />} />
path="/business" <Route path="/drops" element={<Navigate to="/soundmarks" replace />} />
element={ <Route
<RequireRole role="business_admin"> path="/business"
<BusinessPanel /> element={
</RequireRole> <RequireRole role="business_admin">
} <BusinessPanel />
/> </RequireRole>
<Route }
path="/admin" />
element={ <Route
<RequireRole role="super_admin"> path="/admin"
<AdminPanel /> element={
</RequireRole> <RequireRole role="super_admin">
} <AdminPanel />
/> </RequireRole>
<Route }
path="/roadmap" />
element={ <Route
<RequireRole role="super_admin"> path="/roadmap"
<Roadmap /> element={
</RequireRole> <RequireRole role="super_admin">
} <Roadmap />
/> </RequireRole>
<Route path="*" element={<Navigate to="/library" replace />} /> }
</Routes> />
<Route path="*" element={<Navigate to="/library" replace />} />
</Routes>
</Suspense>
) )
} }
...@@ -35,6 +35,22 @@ export function searchLibrary(query: string) { ...@@ -35,6 +35,22 @@ export function searchLibrary(query: string) {
}) })
} }
export interface Album {
album: string
artist: string
coverart: string | null
track_count: number
songs: LibrarySong[]
}
/** A single album's tracks in real track order (parsed from each song's track_number), for the
* dedicated album page - unlike AlbumMatch above (a search-results grouping, unordered), this is
* what "tap an album, see its tracks in the right order" actually reads from. */
export function getAlbum(album: string, artist: string) {
const params = new URLSearchParams({ album, artist })
return apiFetch<{ status: string; album: Album }>(`/library/album?${params}`)
}
/** Deletes the song from disk and from every playlist it's part of, not just this list - the /** Deletes the song from disk and from every playlist it's part of, not just this list - the
* backend cascades PlaylistTrack rows itself, so callers don't need to reconcile playlists * backend cascades PlaylistTrack rows itself, so callers don't need to reconcile playlists
* separately after this resolves. */ * separately after this resolves. */
......
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
Music2, Music2,
Pause, Pause,
Play, Play,
Quote,
Repeat, Repeat,
Repeat1, Repeat1,
ScrollText, ScrollText,
...@@ -305,16 +306,20 @@ export function FullPlayer() { ...@@ -305,16 +306,20 @@ export function FullPlayer() {
feel like part of the Now Playing screen rather than a separate lyrics feature. feel like part of the Now Playing screen rather than a separate lyrics feature.
Still a real button (not just a swipe target) so it's reachable without a Still a real button (not just a swipe target) so it's reachable without a
touchscreen. Only rendered once there's something to show, matching Spotify touchscreen. Only rendered once there's something to show, matching Spotify
(which hides this row entirely rather than linking to an empty screen). */} (which hides this row entirely rather than linking to an empty screen). The Quote
icon exists purely so this reads as "lyrics" at a glance - plain centered gray
text on its own looked too much like an ordinary subtitle to register as an
interactive lyrics preview. */}
{inlineLyricText && ( {inlineLyricText && (
<button <button
ref={lyricsLineButtonRef} ref={lyricsLineButtonRef}
onClick={openLyrics} onClick={openLyrics}
tabIndex={queueOpen || lyricsOpen ? -1 : 0} tabIndex={queueOpen || lyricsOpen ? -1 : 0}
aria-label={`Lyrics: ${inlineLyricText}`} aria-label={`Lyrics: ${inlineLyricText}`}
className="mt-4 truncate rounded-lg px-2 py-1 text-center text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary" className="mt-4 flex w-full items-center justify-center gap-1.5 rounded-lg px-2 py-1 text-sm text-on-surface-variant transition-colors hover:text-on-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
> >
{inlineLyricText} <Quote size={13} strokeWidth={2} className="shrink-0 opacity-70" />
<span className="truncate">{inlineLyricText}</span>
</button> </button>
)} )}
</div> </div>
......
import { ListMusic, ListPlus, Music2, Pause, Play, Trash2 } from 'lucide-react'
import type { LibrarySong } from '../api/library'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useSwipeAction } from '../hooks/useSwipeAction'
export function toPlayable(song: LibrarySong): PlayableSong {
return {
id: song.id,
title: song.title,
artist: song.artist,
album: song.album,
coverart: song.coverart,
lyrics: song.lyrics,
}
}
const SWIPE_VISUAL_MAX = 120
/** One playable row - shared by the Library page (full list and default view's expanded-album
* tracks), the album detail page, and search's "Songs" section, so play/pause/add-to-playlist
* behavior stays identical everywhere a song can appear instead of being reimplemented per
* context. Also swipeable: right to queue (non-destructive, fires immediately), left to delete
* (destructive, `onDelete` owns the confirm step since it also owns the list state that needs
* updating after). */
export function SongRow({
song,
queue,
onAddToPlaylist,
onDelete,
}: {
song: LibrarySong
queue: LibrarySong[]
onAddToPlaylist: (song: LibrarySong) => void
onDelete: (song: LibrarySong) => void
}) {
const { currentSong, isPlaying, isLoading: streamLoading, toggle, addToQueue } = usePlayer()
const isCurrent = currentSong?.id === song.id
const { deltaX, swiping, handlers } = useSwipeAction({
onSwipeRight: () => addToQueue(toPlayable(song)),
onSwipeLeft: () => onDelete(song),
})
const visualDelta = Math.max(-SWIPE_VISUAL_MAX, Math.min(SWIPE_VISUAL_MAX, deltaX))
return (
<li className="group relative -mx-1 overflow-hidden rounded-xl">
{/* Colored panels revealed from each edge as the row is dragged - only one is ever
visible since useSwipeAction clamps deltaX to zero in whichever direction has no
registered handler, and both directions are wired here. */}
<div className="absolute inset-0 flex items-stretch" aria-hidden="true">
<div
className="flex items-center gap-2 overflow-hidden bg-primary/15 pl-4 text-primary"
style={{ width: Math.max(0, visualDelta) }}
>
<ListMusic size={18} strokeWidth={2} className="shrink-0" />
</div>
<div className="flex-1" />
<div
className="flex items-center justify-end gap-2 overflow-hidden bg-error/15 pr-4 text-error"
style={{ width: Math.max(0, -visualDelta) }}
>
<Trash2 size={18} strokeWidth={2} className="shrink-0" />
</div>
</div>
<div
{...handlers}
style={{ transform: `translateX(${visualDelta}px)`, touchAction: 'pan-y' }}
className={`relative flex items-center gap-1 rounded-xl border border-transparent bg-background pr-2 ${
swiping ? '' : 'transition-transform duration-200 ease-out'
} ${deltaX === 0 ? 'hover:border-outline-variant hover:bg-surface-container' : ''}`}
>
{/* 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-primary disabled:cursor-not-allowed"
>
{/* Play/pause overlays the artwork itself on hover (Spotify's card pattern), rather
than sitting in a separate always-visible control next to it - stays visible
without hovering for whichever track is actually current, same as Spotify keeps
its now-playing indicator on screen for the active track specifically. */}
<div className="relative h-12 w-12 shrink-0">
{song.coverart ? (
<img src={song.coverart} alt="" loading="lazy" decoding="async" className="h-12 w-12 rounded-lg object-cover" />
) : (
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<span
className={`absolute inset-0 flex items-center justify-center rounded-lg bg-black/50 text-white transition-opacity duration-150 ${
isCurrent ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
}`}
>
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/40 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={18} strokeWidth={2} fill="currentColor" />
) : (
<Play size={18} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</div>
<div className="min-w-0 flex-1">
<p className={`truncate font-medium ${isCurrent ? 'text-primary' : 'text-on-surface group-hover:text-primary'}`}>
{song.title}
</p>
<p className="truncate text-sm text-on-surface-variant">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
</p>
</div>
</button>
<button
onClick={() => onAddToPlaylist(song)}
aria-label={`Add ${song.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"
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</div>
</li>
)
}
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AlbumDetail } from './AlbumDetail'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
const SONG_1 = {
id: 1,
user_id: 1,
title: 'First',
artist: 'Duran Duran',
album: 'Astronaut',
genre: 'Pop',
coverart: 'http://example.com/art.jpg',
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
const SONG_2 = { ...SONG_1, id: 2, title: 'Second' }
const ALBUM = { album: 'Astronaut', artist: 'Duran Duran', coverart: 'http://example.com/art.jpg', track_count: 2, songs: [SONG_1, SONG_2] }
// Fires the full pointer drag sequence useSwipeAction listens for, same as Library.test.tsx's
// own helper - pointer events bubble from a descendant (e.g. the row's Play button) the same
// way in jsdom as in a real browser.
function swipe(target: HTMLElement, fromX: number, toX: number) {
fireEvent.pointerDown(target, { clientX: fromX, pointerId: 1 })
fireEvent.pointerMove(target, { clientX: toX, pointerId: 1 })
fireEvent.pointerUp(target, { clientX: toX, pointerId: 1 })
}
function renderAlbumDetail(initialPath = '/library/album?album=Astronaut&artist=Duran+Duran') {
return render(
<MemoryRouter initialEntries={[initialPath]}>
<AuthProvider>
<PlayerProvider>
<Routes>
<Route path="/library" element={<p>Back on Library</p>} />
<Route path="/library/album" element={<AlbumDetail />} />
</Routes>
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('AlbumDetail', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('redirects to the library when album/artist query params are missing', async () => {
vi.spyOn(libraryApi, 'getAlbum')
renderAlbumDetail('/library/album')
expect(await screen.findByText('Back on Library')).toBeInTheDocument()
expect(libraryApi.getAlbum).not.toHaveBeenCalled()
})
it('fetches and shows the album in real track order', async () => {
const getAlbum = vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
renderAlbumDetail()
expect(getAlbum).toHaveBeenCalledWith('Astronaut', 'Duran Duran')
// Not asserting on a heading here - Layout's own page title *also* reads "Astronaut" (from
// the URL query param, synchronously on mount), so there are genuinely two "Astronaut"
// headings once the album data loads. The track count line is unambiguous and only exists
// once the fetch has actually resolved.
expect(await screen.findByText('Duran Duran · 2 tracks')).toBeInTheDocument()
const rows = screen.getAllByRole('listitem')
expect(within(rows[0]).getByText('First')).toBeInTheDocument()
expect(within(rows[1]).getByText('Second')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockRejectedValue(new ApiError(404, 'Album not found', null))
renderAlbumDetail()
expect(await screen.findByText('Album not found')).toBeInTheDocument()
})
it('plays the whole album in order from the Play button, starting at the first track', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderAlbumDetail()
// Same race as the test above - wait on something that only exists once the album has
// actually loaded, not the heading (Layout's own page title reads "Astronaut" immediately).
await userEvent.click(await screen.findByRole('button', { name: 'Play album' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(1))
})
it('starting playback from the second track still queues the rest of the album in order', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderAlbumDetail()
const secondRow = (await screen.findByText('Second')).closest('li')!
await userEvent.click(within(secondRow).getByRole('button', { name: 'Play' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(2))
// The queue is the real album order (not just [Second]) - Next should move to whatever
// comes after Second in that order, i.e. nothing here since it's the last track, but the
// dialog's queue view is the simplest way to confirm the whole ordered list was passed.
await userEvent.click(await screen.findByRole('button', { name: /Open player/ }))
const dialog = await screen.findByRole('dialog', { name: /Now playing/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'Open queue' }))
const queueItems = within(dialog).getAllByRole('listitem')
expect(within(queueItems[0]).getByText('First')).toBeInTheDocument()
expect(within(queueItems[1]).getByText('Second')).toBeInTheDocument()
})
it('opens the add-to-playlist modal for a track', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
const getPlaylists = vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
renderAlbumDetail()
const row = (await screen.findByText('First')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Add First to a playlist' }))
expect(await screen.findByRole('dialog', { name: 'Add "First" to a playlist' })).toBeInTheDocument()
expect(getPlaylists).toHaveBeenCalled()
})
it('deletes a track and keeps the remaining ones', async () => {
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: ALBUM })
const deleteLibrarySong = vi.spyOn(libraryApi, 'deleteLibrarySong').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderAlbumDetail()
const row = (await screen.findByText('First')).closest('li')!
// Swipe left past the delete threshold, same gesture as Library's own rows.
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
expect(deleteLibrarySong).toHaveBeenCalledWith(1)
await waitFor(() => expect(screen.queryByText('First')).not.toBeInTheDocument())
expect(screen.getByText('Second')).toBeInTheDocument()
})
it('navigates back to the library after deleting the last remaining track', async () => {
const oneTrackAlbum = { ...ALBUM, track_count: 1, songs: [SONG_1] }
vi.spyOn(libraryApi, 'getAlbum').mockResolvedValue({ status: 'success', album: oneTrackAlbum })
vi.spyOn(libraryApi, 'deleteLibrarySong').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderAlbumDetail()
const row = (await screen.findByText('First')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
expect(await screen.findByText('Back on Library')).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { Music2, Pause, Play } from 'lucide-react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { deleteLibrarySong, getAlbum, type Album, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { SongRow, toPlayable } from '../components/SongRow'
import { SkeletonRow } from '../components/ui/Skeleton'
import { usePlayer } from '../context/PlayerContext'
export function AlbumDetail() {
const [searchParams] = useSearchParams()
const navigate = useNavigate()
const albumName = searchParams.get('album') ?? ''
const artist = searchParams.get('artist') ?? ''
const [album, setAlbum] = useState<Album | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<LibrarySong | null>(null)
const [deleteError, setDeleteError] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
useEffect(() => {
if (!albumName || !artist) {
navigate('/library', { replace: true })
return
}
setLoading(true)
setError(null)
getAlbum(albumName, artist)
.then((res) => setAlbum(res.album))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load album'))
.finally(() => setLoading(false))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [albumName, artist])
// Same reasoning as Library's own handleDelete - owns the confirm step since it also owns
// the list state that needs updating after (and, unlike Library, has to handle the album
// becoming empty by navigating back rather than rendering a dangling empty page).
async function handleDelete(song: LibrarySong) {
if (!window.confirm(`Delete "${song.title}"? This can't be undone.`)) return
setDeleteError(null)
try {
await deleteLibrarySong(song.id)
setAlbum((prev) => {
if (!prev) return prev
const songs = prev.songs.filter((s) => s.id !== song.id)
if (songs.length === 0) {
navigate('/library', { replace: true })
return prev
}
return { ...prev, songs, track_count: songs.length }
})
} catch (err) {
setDeleteError(err instanceof ApiError ? err.message : `Could not delete "${song.title}"`)
}
}
const isAlbumCurrent = !!album && album.songs.some((s) => s.id === currentSong?.id)
return (
<Layout title={albumName || 'Album'}>
{loading && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
{deleteError && <p className="mb-2 text-sm text-error">{deleteError}</p>}
{album && (
<>
<div className="mb-6 flex flex-col items-center gap-4 text-center sm:flex-row sm:items-end sm:text-left">
{album.coverart ? (
<img
src={album.coverart}
alt=""
className="h-40 w-40 shrink-0 rounded-2xl object-cover shadow-lg shadow-black/30"
/>
) : (
<div className="flex h-40 w-40 shrink-0 items-center justify-center rounded-2xl bg-surface-container-high text-on-surface-variant">
<Music2 size={40} strokeWidth={1.25} />
</div>
)}
{/* Album name itself isn't repeated here - Layout's own title above already shows
it, and this page is the first to pair a rich header with that title, so
showing the same name twice (once small, once large) would just be visual
noise rather than a second real heading. */}
<div className="min-w-0">
<p className="text-xs font-semibold uppercase tracking-[0.1em] text-primary">Album</p>
<p className="mt-1 text-sm text-on-surface-variant">
{album.artist} · {album.track_count} track{album.track_count === 1 ? '' : 's'}
</p>
<button
onClick={() => toggle(toPlayable(album.songs[0]), album.songs.map(toPlayable))}
disabled={isAlbumCurrent && streamLoading}
aria-label={isAlbumCurrent && isPlaying ? 'Pause album' : 'Play album'}
className="mt-4 flex items-center gap-2 rounded-full bg-primary px-5 py-2.5 text-sm font-semibold text-on-primary transition-transform duration-150 ease-out active:scale-95 disabled:opacity-50"
>
{isAlbumCurrent && streamLoading ? (
<span className="h-4 w-4 animate-spin rounded-full border-2 border-on-primary/30 border-t-on-primary" />
) : isAlbumCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" />
)}
{isAlbumCurrent && isPlaying ? 'Pause' : 'Play'}
</button>
</div>
</div>
{/* Passing the whole ordered album as `queue`, not just the tapped song, means
starting playback from any track (not only the first) still plays through the
rest of the album in the same real track order - the entire point of this page
existing separately from the unordered album-grid preview. */}
<ul className="space-y-1">
{album.songs.map((song) => (
<SongRow key={song.id} song={song} queue={album.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
))}
</ul>
</>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout>
)
}
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom' import { MemoryRouter, Route, Routes, useSearchParams } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Library } from './Library' import { Library } from './Library'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
...@@ -9,6 +9,14 @@ import { ApiError } from '../api/client' ...@@ -9,6 +9,14 @@ import { ApiError } from '../api/client'
import * as libraryApi from '../api/library' import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream' import * as streamApi from '../api/stream'
// Stands in for the real AlbumDetail page (covered by its own test file) - just enough to prove
// Library navigated to the right place with the right query params, without pulling in a whole
// second page's data-fetching and rendering.
function AlbumRouteProbe() {
const [params] = useSearchParams()
return <p>Album route: {params.get('album')} by {params.get('artist')}</p>
}
const SONG = { const SONG = {
id: 1, id: 1,
user_id: 1, user_id: 1,
...@@ -38,7 +46,10 @@ function renderLibrary() { ...@@ -38,7 +46,10 @@ function renderLibrary() {
<MemoryRouter> <MemoryRouter>
<AuthProvider> <AuthProvider>
<PlayerProvider> <PlayerProvider>
<Library /> <Routes>
<Route path="/" element={<Library />} />
<Route path="/library/album" element={<AlbumRouteProbe />} />
</Routes>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
</MemoryRouter>, </MemoryRouter>,
...@@ -102,21 +113,13 @@ describe('Library', () => { ...@@ -102,21 +113,13 @@ describe('Library', () => {
expect(screen.queryByRole('heading', { name: 'Albums' })).not.toBeInTheDocument() expect(screen.queryByRole('heading', { name: 'Albums' })).not.toBeInTheDocument()
}) })
it('expands an album card from the default view to show and play its tracks', async () => { it('navigates to the album detail page when an album card is tapped in the default view', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] }) vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary() renderLibrary()
await userEvent.click(await screen.findByRole('button', { name: /Astronaut/ })) await userEvent.click(await screen.findByRole('button', { name: /Astronaut/ }))
const allSongsSection = screen.getByRole('heading', { name: 'All Songs' }).closest('div')! expect(await screen.findByText('Album route: Astronaut by Duran Duran')).toBeInTheDocument()
// Two "Invisible" rows now exist - one in the expanded album, one in All Songs - so play
// the one inside the album's own track list specifically.
const trackRows = screen.getAllByText('Invisible').map((el) => el.closest('li')!)
const albumTrackRow = trackRows.find((row) => !allSongsSection.contains(row))!
await userEvent.click(within(albumTrackRow).getByRole('button', { name: 'Play' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(1))
}) })
it('shows a load error using the ApiError message', async () => { it('shows a load error using the ApiError message', async () => {
...@@ -198,25 +201,21 @@ describe('Library', () => { ...@@ -198,25 +201,21 @@ describe('Library', () => {
expect(screen.queryByText('Invisible')).not.toBeInTheDocument() expect(screen.queryByText('Invisible')).not.toBeInTheDocument()
}) })
it('expands an album to show and play its tracks', async () => { it('navigates to the album detail page when a search result album row is tapped', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] }) vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({ vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({
status: 'success', status: 'success',
songs: [], songs: [],
albums: [{ album: 'Astronaut', artist: 'Duran Duran', coverart: null, track_count: 1, songs: [SONG] }], albums: [{ album: 'Astronaut', artist: 'Duran Duran', coverart: null, track_count: 1, songs: [SONG] }],
}) })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary() renderLibrary()
await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'astronaut') await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'astronaut')
const albumButton = await screen.findByRole('button', { name: /Astronaut/ }) const albumButton = await screen.findByRole('button', { name: /Astronaut/ })
expect(screen.queryByText('Invisible')).not.toBeInTheDocument()
await userEvent.click(albumButton) await userEvent.click(albumButton)
const trackRow = (await screen.findByText('Invisible')).closest('li')! expect(await screen.findByText('Album route: Astronaut by Duran Duran')).toBeInTheDocument()
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 () => { it('shows an empty state for a search with no matches', async () => {
......
This diff is collapsed.
...@@ -110,7 +110,7 @@ export function Playlists() { ...@@ -110,7 +110,7 @@ export function Playlists() {
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed" className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"
> >
{song.coverart ? ( {song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" /> <img src={song.coverart} alt="" loading="lazy" decoding="async" 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-surface-container-high text-on-surface-variant"> <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-surface-container-high text-on-surface-variant">
<Music2 size={18} strokeWidth={1.75} /> <Music2 size={18} strokeWidth={1.75} />
......
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