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 (
<Suspense fallback={<RouteFallback />}>
<Routes> <Routes>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/library" element={protect(<Library />)} /> <Route path="/library" element={protect(<Library />)} />
<Route path="/library/album" element={protect(<AlbumDetail />)} />
<Route path="/playlists" element={protect(<Playlists />)} /> <Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/telegram-link" element={protect(<TelegramLink />)} /> <Route path="/telegram-link" element={protect(<TelegramLink />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/upload" element={protect(<Upload />)} />
...@@ -62,5 +82,6 @@ export function App() { ...@@ -62,5 +82,6 @@ export function App() {
/> />
<Route path="*" element={<Navigate to="/library" replace />} /> <Route path="*" element={<Navigate to="/library" replace />} />
</Routes> </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 () => {
......
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { ListMusic, ListPlus, Music2, Pause, Play, Search, Trash2 } from 'lucide-react' import { Music2, Search } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { deleteLibrarySong, getLibrary, searchLibrary, type AlbumMatch, type LibrarySong } from '../api/library' import { deleteLibrarySong, getLibrary, searchLibrary, type AlbumMatch, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal' import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { SongRow } from '../components/SongRow'
import { Input } from '../components/ui/Input' import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton' import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useSwipeAction } from '../hooks/useSwipeAction'
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 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. 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). */
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="" 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>
)
}
function albumKey(album: AlbumMatch): string {
return `${album.album}::${album.artist}`
}
/** Client-side mirror of /library/search's (album, artist) grouping - the default library view /** Client-side mirror of /library/search's (album, artist) grouping - the default library view
* needs the same album grid the search results get, but there's no reason to round-trip to the * needs the same album grid the search results get, but there's no reason to round-trip to the
* backend for it: the full song list (with each song's own album/coverart) is already loaded, * backend for it: the full song list (with each song's own album/coverart) is already loaded,
* so it's derived here instead of adding a second endpoint that returns the same shape. Skips * so it's derived here instead of adding a second endpoint that returns the same shape. Skips
* songs with no album, same as the backend does. */ * songs with no album, same as the backend does. Track order within each group doesn't matter
* here - the album detail page fetches its own real ordering, this is only used for the grid's
* cover art / track count / navigation target. */
function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] { function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] {
const byKey = new Map<string, AlbumMatch>() const byKey = new Map<string, AlbumMatch>()
for (const song of songs) { for (const song of songs) {
...@@ -159,17 +34,18 @@ function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] { ...@@ -159,17 +34,18 @@ function groupIntoAlbums(songs: LibrarySong[]): AlbumMatch[] {
return Array.from(byKey.values()) return Array.from(byKey.values())
} }
function AlbumCard({ album, expanded, onToggle }: { album: AlbumMatch; expanded: boolean; onToggle: () => void }) { function albumHref(album: { album: string; artist: string }): string {
return `/library/album?${new URLSearchParams({ album: album.album, artist: album.artist })}`
}
function AlbumCard({ album, onOpen }: { album: AlbumMatch; onOpen: () => void }) {
return ( return (
<button <button
onClick={onToggle} onClick={onOpen}
aria-expanded={expanded} className="flex min-w-0 flex-col gap-2 rounded-xl border border-transparent p-3 text-left transition-colors hover:border-outline-variant hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
className={`flex min-w-0 flex-col gap-2 rounded-xl border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
expanded ? 'border-primary bg-surface-container' : 'border-transparent hover:border-outline-variant hover:bg-surface-container'
}`}
> >
{album.coverart ? ( {album.coverart ? (
<img src={album.coverart} alt="" className="aspect-square w-full rounded-lg object-cover" /> <img src={album.coverart} alt="" loading="lazy" decoding="async" className="aspect-square w-full rounded-lg object-cover" />
) : ( ) : (
<div className="flex aspect-square w-full items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant"> <div className="flex aspect-square w-full items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Music2 size={28} strokeWidth={1.5} /> <Music2 size={28} strokeWidth={1.5} />
...@@ -186,6 +62,7 @@ function AlbumCard({ album, expanded, onToggle }: { album: AlbumMatch; expanded: ...@@ -186,6 +62,7 @@ function AlbumCard({ album, expanded, onToggle }: { album: AlbumMatch; expanded:
} }
export function Library() { export function Library() {
const navigate = useNavigate()
const [songs, setSongs] = useState<LibrarySong[]>([]) const [songs, setSongs] = useState<LibrarySong[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
...@@ -195,10 +72,8 @@ export function Library() { ...@@ -195,10 +72,8 @@ export function Library() {
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<{ songs: LibrarySong[]; albums: AlbumMatch[] } | null>(null) const [searchResults, setSearchResults] = useState<{ songs: LibrarySong[]; albums: AlbumMatch[] } | null>(null)
const [searching, setSearching] = useState(false) const [searching, setSearching] = useState(false)
const [expandedAlbum, setExpandedAlbum] = useState<string | null>(null)
const albums = useMemo(() => groupIntoAlbums(songs), [songs]) const albums = useMemo(() => groupIntoAlbums(songs), [songs])
const expandedAlbumData = albums.find((a) => albumKey(a) === expandedAlbum) ?? null
useEffect(() => { useEffect(() => {
getLibrary() getLibrary()
...@@ -223,8 +98,9 @@ export function Library() { ...@@ -223,8 +98,9 @@ export function Library() {
}, [query]) }, [query])
// Owns the confirm step (not SongRow) since it's also the one that has to reconcile the // Owns the confirm step (not SongRow) since it's also the one that has to reconcile the
// song's removal across every local list it can appear in - the full library, the current // song's removal across every local list it can appear in - the full library and the current
// search's Songs section, and any album groupings within that search. // search's Songs/Albums sections (album groupings in the default view derive from `songs`
// itself via useMemo, so they update for free without any separate reconciliation here).
async function handleDelete(song: LibrarySong) { async function handleDelete(song: LibrarySong) {
if (!window.confirm(`Delete "${song.title}"? This can't be undone.`)) return if (!window.confirm(`Delete "${song.title}"? This can't be undone.`)) return
setDeleteError(null) setDeleteError(null)
...@@ -289,18 +165,14 @@ export function Library() { ...@@ -289,18 +165,14 @@ export function Library() {
<div className="mb-6"> <div className="mb-6">
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2> <h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2>
<ul className="space-y-1"> <ul className="space-y-1">
{searchResults.albums.map((album) => { {searchResults.albums.map((album) => (
const key = albumKey(album) <li key={`${album.album}::${album.artist}`}>
const expanded = expandedAlbum === key
return (
<li key={key}>
<button <button
onClick={() => setExpandedAlbum(expanded ? null : key)} onClick={() => navigate(albumHref(album))}
aria-expanded={expanded}
className="-mx-1 flex w-full items-center gap-4 rounded-xl border border-transparent px-2 py-3 text-left transition-colors hover:border-outline-variant hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary" className="-mx-1 flex w-full items-center gap-4 rounded-xl border border-transparent px-2 py-3 text-left transition-colors hover:border-outline-variant hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
> >
{album.coverart ? ( {album.coverart ? (
<img src={album.coverart} alt="" className="h-12 w-12 shrink-0 rounded-lg object-cover" /> <img src={album.coverart} alt="" loading="lazy" decoding="async" className="h-12 w-12 shrink-0 rounded-lg object-cover" />
) : ( ) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant"> <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-surface-container-high text-on-surface-variant">
<Music2 size={18} strokeWidth={1.75} /> <Music2 size={18} strokeWidth={1.75} />
...@@ -313,16 +185,8 @@ export function Library() { ...@@ -313,16 +185,8 @@ export function Library() {
</p> </p>
</div> </div>
</button> </button>
{expanded && (
<ul className="mb-2 space-y-1 pl-4">
{album.songs.map((s) => (
<SongRow key={s.id} song={s} queue={album.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
))}
</ul>
)}
</li> </li>
) ))}
})}
</ul> </ul>
</div> </div>
)} )}
...@@ -343,31 +207,10 @@ export function Library() { ...@@ -343,31 +207,10 @@ export function Library() {
<div className="mb-8"> <div className="mb-8">
<h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2> <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Albums</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"> <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
{albums.map((album) => { {albums.map((album) => (
const key = albumKey(album) <AlbumCard key={`${album.album}::${album.artist}`} album={album} onOpen={() => navigate(albumHref(album))} />
return (
<AlbumCard
key={key}
album={album}
expanded={expandedAlbum === key}
onToggle={() => setExpandedAlbum(expandedAlbum === key ? null : key)}
/>
)
})}
</div>
{expandedAlbumData && (
<ul className="mt-3 space-y-1">
{expandedAlbumData.songs.map((s) => (
<SongRow
key={s.id}
song={s}
queue={expandedAlbumData.songs}
onAddToPlaylist={setAddingSong}
onDelete={handleDelete}
/>
))} ))}
</ul> </div>
)}
</div> </div>
)} )}
......
...@@ -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} />
......
...@@ -86,6 +86,7 @@ const BACKEND_DONE: DoneGroup[] = [ ...@@ -86,6 +86,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Playlists: create, list, detail with ordered tracks, add track', 'Playlists: create, list, detail with ordered tracks, add track',
'Delete: songs (+ file on disk), playlists (+ their tracks), single playlist tracks - all owner-scoped', 'Delete: songs (+ file on disk), playlists (+ their tracks), single playlist tracks - all owner-scoped',
'/music/tag and /music/upload no longer return a download_url (2026-09-01) - same access-control gap as the old remix one below: the URL pointed at the unauthenticated /downloads static mount with no ownership check, so anyone who saw or guessed a path could pull another user\'s file. Nothing served it any more once the frontend switched the Upload result card to "add to playlist" instead of a download link, so it was removed rather than patched; playback goes through the already-auth-scoped /library/stream/{id}.', '/music/tag and /music/upload no longer return a download_url (2026-09-01) - same access-control gap as the old remix one below: the URL pointed at the unauthenticated /downloads static mount with no ownership check, so anyone who saw or guessed a path could pull another user\'s file. Nothing served it any more once the frontend switched the Upload result card to "add to playlist" instead of a download link, so it was removed rather than patched; playback goes through the already-auth-scoped /library/stream/{id}.',
'LibrarySong.track_number + GET /library/album (2026-09-01): identify_audio() (Shazam, or MusicBrainz\'s release-list for AcoustID hits) always computed a track number, and IdentifiedTrack already cached it, but LibrarySong itself had no column for it - so an album\'s tracks had no real order to sort by anywhere they were shown. Persisted through the shared tag/upload pipeline; the new endpoint returns one (album, artist)\'s tracks sorted by it (numberless tracks last, then alphabetically) for the frontend\'s new dedicated album page.',
], ],
}, },
{ {
...@@ -188,9 +189,10 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -188,9 +189,10 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [ items: [
'Library page with playback', 'Library page with playback',
'Real-time synced lyrics in the full-screen player (2026-08-31): line-by-line highlight follows playback position (last line whose timestamp has passed), auto-scrolls the active line to center, tapping a line seeks there - Spotify\'s actual signature lyrics behavior, not an approximation. Falls back to the existing static full-text view when a song has plain lyrics but no synced timing, and to the empty state when it has neither. Fixed same day: the synced-lyrics lookup was only attempted when the identification candidate itself had no plain lyrics already - but Shazam and Gemini can both independently return a plain snippet, which was silently skipping the sync fetch (and any real timing that existed) whenever that happened. Now always attempted, with synced data winning over the candidate\'s own plain text when found; existing library songs were backfilled', 'Real-time synced lyrics in the full-screen player (2026-08-31): line-by-line highlight follows playback position (last line whose timestamp has passed), auto-scrolls the active line to center, tapping a line seeks there - Spotify\'s actual signature lyrics behavior, not an approximation. Falls back to the existing static full-text view when a song has plain lyrics but no synced timing, and to the empty state when it has neither. Fixed same day: the synced-lyrics lookup was only attempted when the identification candidate itself had no plain lyrics already - but Shazam and Gemini can both independently return a plain snippet, which was silently skipping the sync fetch (and any real timing that existed) whenever that happened. Now always attempted, with synced data winning over the candidate\'s own plain text when found; existing library songs were backfilled',
'Lyrics presentation rebuilt to match Spotify\'s actual current pattern, not the "tap a bar to swap cover for lyrics" one from 08-31 (2026-09-01, researched via web search rather than guessed at): the live synced line now plays right under the cover art on the main Now Playing screen at all times - no tap needed to see it, matching what Spotify itself shipped as its headline update here. The full scrollable lyrics view is a step deeper, reached by swiping up on the cover (Spotify\'s real gesture) or tapping the live line (kept as a focusable fallback for keyboard/screen-reader use, since Spotify itself keeps a tappable entry point alongside the swipe) - a real slide-up screen with its own back control, closed by swipe-down, the back button, Escape, or system back, not the previous in-place crossfade toggle.', 'Lyrics presentation rebuilt to match Spotify\'s actual current pattern, not the "tap a bar to swap cover for lyrics" one from 08-31 (2026-09-01, researched via web search rather than guessed at): the live synced line now plays right under the cover art on the main Now Playing screen at all times - no tap needed to see it, matching what Spotify itself shipped as its headline update here. The full scrollable lyrics view is a step deeper, reached by swiping up on the cover (Spotify\'s real gesture) or tapping the live line (kept as a focusable fallback for keyboard/screen-reader use, since Spotify itself keeps a tappable entry point alongside the swipe) - a real slide-up screen with its own back control, closed by swipe-down, the back button, Escape, or system back, not the previous in-place crossfade toggle. Verified against 8 real library songs with a mix of synced/plain/no lyrics via Playwright and the line rendered correctly for all of them (only the one genuinely lyrics-less track showed nothing, as intended) - a follow-up report of "lyrics not shown" couldn\'t be reproduced, so a Quote icon was added next to the line as a same-day follow-up in case the real issue was the plain-text line not visually reading as an interactive lyrics preview.',
'Universal search box: separate Songs and Albums result sections while searching (an album expands to show/play its tracks) - replaces the plain list rather than filtering it in place', 'Universal search box: separate Songs and Albums result sections while searching - replaces the plain list rather than filtering it in place',
'Spotify-style default (non-search) view (2026-09-01): an Albums grid of cover-art cards above an always-on All Songs list covering the full library. The (album, artist) grouping is derived client-side from the already-loaded song list (mirroring /library/search\'s own grouping) rather than adding a second backend endpoint that would return the same shape - deletions and new songs update both sections for free since All Songs and the album groups both derive from the same one songs array. Tapping a card expands its tracks below the grid, same interaction as search\'s album rows.', 'Spotify-style default (non-search) view (2026-09-01): an Albums grid of cover-art cards above an always-on All Songs list covering the full library. The (album, artist) grouping is derived client-side from the already-loaded song list (mirroring /library/search\'s own grouping) rather than adding a second backend endpoint that would return the same shape - deletions and new songs update both sections for free since All Songs and the album groups both derive from the same one songs array.',
'Dedicated album page at /library/album (2026-09-01), replacing the earlier same-day expand-in-place version - tapping an album (from either the default grid or a search result row) now navigates to a real page showing its tracks in genuine track order, not upload/discovery order. This closed a real gap: identify_audio() (and the IdentifiedTrack cache) always computed a track_number, but LibrarySong had no column to store it in, so it was silently discarded on every tag/upload - added the column, a migration, persistence in _identify_tag_and_store, and a new GET /library/album?album=&artist= endpoint that sorts by it (numberless tracks sort after numbered ones, then alphabetically). Starting playback from any track in the list queues the rest of the real album order behind it, not just that one song. The page originally repeated the album name twice (Layout\'s own page-title heading, plus a second large one in the header) - caught by a genuinely flaky test rather than a design review, since jsdom happily renders two <h1>s with identical text where a real glance at the screenshot would\'ve caught it sooner; now only the one from Layout remains.',
'Playlists page: list, create, view tracks, playback', 'Playlists page: list, create, view tracks, playback',
'Add-to-playlist modal from the Library page (add existing or create-and-add)', 'Add-to-playlist modal from the Library page (add existing or create-and-add)',
'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)', 'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)',
...@@ -221,6 +223,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -221,6 +223,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'In-app "Install Stax" banner (2026-08-31): the browser\'s own install icon is easy to miss entirely, so useInstallPrompt captures beforeinstallprompt at module load (not inside a component effect - each page wraps its own <Layout>, so a component-scoped listener could miss the one-per-page-load event if it fires before that particular page happens to mount) and InstallBanner surfaces a real "Install" button from it; iOS Safari has no such event at all, so it shows manual Share -> Add to Home Screen instructions instead', 'In-app "Install Stax" banner (2026-08-31): the browser\'s own install icon is easy to miss entirely, so useInstallPrompt captures beforeinstallprompt at module load (not inside a component effect - each page wraps its own <Layout>, so a component-scoped listener could miss the one-per-page-load event if it fires before that particular page happens to mount) and InstallBanner surfaces a real "Install" button from it; iOS Safari has no such event at all, so it shows manual Share -> Add to Home Screen instructions instead',
'System/Android back button closes overlays instead of leaving the page underneath them (2026-08-31): useBackButtonClose pushes one history entry per open overlay onto a shared stack (not one popstate listener per instance, since a single back press must close only the top-most of several nested overlays - e.g. FullPlayer\'s Queue screen on top of FullPlayer itself - not all of them at once) - wired into FullPlayer (+ its Queue screen as a second nested level), Layout\'s mobile More sheet, AddToPlaylistModal, SongPicker, and RemixSongPicker. Fixed same day: closing an overlay via an action that *also* navigates (e.g. a More-sheet item, which is both a route Link and calls onClose) was clobbering that navigation - the cleanup unconditionally called history.back() to consume its own entry, which by then was buried under the Link\'s own pushState, so it undid the navigation instead. Each pushed entry now carries a unique id and cleanup only consumes it if it\'s still the current one', 'System/Android back button closes overlays instead of leaving the page underneath them (2026-08-31): useBackButtonClose pushes one history entry per open overlay onto a shared stack (not one popstate listener per instance, since a single back press must close only the top-most of several nested overlays - e.g. FullPlayer\'s Queue screen on top of FullPlayer itself - not all of them at once) - wired into FullPlayer (+ its Queue screen as a second nested level), Layout\'s mobile More sheet, AddToPlaylistModal, SongPicker, and RemixSongPicker. Fixed same day: closing an overlay via an action that *also* navigates (e.g. a More-sheet item, which is both a route Link and calls onClose) was clobbering that navigation - the cleanup unconditionally called history.back() to consume its own entry, which by then was buried under the Link\'s own pushState, so it undid the navigation instead. Each pushed entry now carries a unique id and cleanup only consumes it if it\'s still the current one',
'Swipe gestures on Library rows (2026-08-31): useSwipeAction (pointer-events based, no gesture library) drives a swipe-right-to-queue / swipe-left-to-delete interaction, sharing the same PlayerContext.addToQueue used elsewhere - queueing appends without touching whatever is currently playing, unlike toggle() which replaces the whole queue and starts playback. Fixed same day, found via real end-to-end (Playwright) testing rather than the unit suite: pointer capture was engaged unconditionally on pointerdown, which redirects the browser\'s synthesized click to the capturing row instead of whatever was actually tapped - silently breaking every button inside a row (Play, Add to playlist) on a real device. Invisible in jsdom, which stubs setPointerCapture as a no-op. Now only captures once a real drag is detected (a few px of movement), leaving plain taps untouched', 'Swipe gestures on Library rows (2026-08-31): useSwipeAction (pointer-events based, no gesture library) drives a swipe-right-to-queue / swipe-left-to-delete interaction, sharing the same PlayerContext.addToQueue used elsewhere - queueing appends without touching whatever is currently playing, unlike toggle() which replaces the whole queue and starts playback. Fixed same day, found via real end-to-end (Playwright) testing rather than the unit suite: pointer capture was engaged unconditionally on pointerdown, which redirects the browser\'s synthesized click to the capturing row instead of whatever was actually tapped - silently breaking every button inside a row (Play, Add to playlist) on a real device. Invisible in jsdom, which stubs setPointerCapture as a no-op. Now only captures once a real drag is detected (a few px of movement), leaving plain taps untouched',
'Route-level code splitting (2026-09-01): every page used to ship in one ~590KB JS bundle loaded before *any* route could render, including whichever one happened to be first (Login or Library) - Vite\'s own build output was flagging this. Every page is now a separate React.lazy() chunk fetched on demand instead, cutting the initial bundle to ~397KB with the rest split per-route (e.g. Roadmap and AdminPanel, both rarely the first thing a session needs, now cost nothing until actually visited). Library and Playlists cover-art images also switched to loading="lazy" so a long list/grid doesn\'t compete with the API/audio-stream requests that actually matter for first paint.',
], ],
}, },
] ]
......
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