Commit 0f155d5e authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add Playlist UI - the first item off the roadmap's "Next" column

Playlists have had a fully working backend (create, list, add-track) with
zero frontend UI since much earlier in this project. Adds:

- New page (/playlists, in nav): list playlists, create one inline, open
  one to see and play its tracks, back button to return to the list.
- AddToPlaylistModal: a per-row action on the Library page to add a song
  to an existing playlist, or create a new one and add to it in one step -
  mirrors SongPicker's modal pattern. Stays open after a successful add so
  adding to several playlists doesn't mean reopening the picker each time.
- Backend: new GET /playlists/{id} (stax_backend_api, separate commit) -
  the only endpoint actually missing; everything else already existed.

Verified live end to end through the deployed proxy: create a playlist,
add a real library song, fetch the playlist back with its track. Updated
the Roadmap page to reflect this is done.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent d53c3623
Pipeline #1093 canceled with stage
import { Navigate, Route, Routes } from 'react-router-dom' import { Navigate, Route, Routes } from 'react-router-dom'
import { Library } from './pages/Library' import { Library } from './pages/Library'
import { Playlists } from './pages/Playlists'
import { Upload } from './pages/Upload' import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery' import { Discovery } from './pages/Discovery'
import { Rooms } from './pages/Rooms' import { Rooms } from './pages/Rooms'
...@@ -24,6 +25,7 @@ export function App() { ...@@ -24,6 +25,7 @@ export function App() {
<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="/playlists" element={protect(<Playlists />)} />
<Route path="/upload" element={protect(<Upload />)} /> <Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} /> <Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/rooms" element={protect(<Rooms />)} /> <Route path="/rooms" element={protect(<Rooms />)} />
......
...@@ -39,6 +39,10 @@ export function getPlaylists() { ...@@ -39,6 +39,10 @@ export function getPlaylists() {
return apiFetch<{ status: string; playlists: Playlist[] }>('/playlists') return apiFetch<{ status: string; playlists: Playlist[] }>('/playlists')
} }
export function getPlaylist(playlistId: number) {
return apiFetch<{ status: string; playlist: Playlist; tracks: LibrarySong[] }>(`/playlists/${playlistId}`)
}
export function createPlaylist(name: string) { export function createPlaylist(name: string) {
return apiFetch<{ status: string; playlist: Playlist }>('/playlists', { return apiFetch<{ status: string; playlist: Playlist }>('/playlists', {
method: 'POST', method: 'POST',
......
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AddToPlaylistModal } from './AddToPlaylistModal'
import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
const SONG = {
id: 1,
user_id: 1,
title: 'Invisible',
artist: 'Duran Duran',
album: 'Astronaut',
genre: 'Pop',
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
const PLAYLIST_A = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z' }
const PLAYLIST_B = { id: 11, user_id: 1, name: 'Party', created_at: '2026-01-02T00:00:00Z' }
describe('AddToPlaylistModal', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('lists the caller\'s playlists', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST_A, PLAYLIST_B] })
render(<AddToPlaylistModal song={SONG} onClose={vi.fn()} />)
expect(await screen.findByText('Chill')).toBeInTheDocument()
expect(screen.getByText('Party')).toBeInTheDocument()
})
it('shows an empty-state message when there are no playlists yet', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
render(<AddToPlaylistModal song={SONG} onClose={vi.fn()} />)
expect(await screen.findByText('No playlists yet - create one above.')).toBeInTheDocument()
})
it('adds the song to a playlist and shows a checkmark instead of closing', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST_A] })
const addToPlaylist = vi.spyOn(libraryApi, 'addToPlaylist').mockResolvedValue({ status: 'success', message: 'ok' })
const onClose = vi.fn()
render(<AddToPlaylistModal song={SONG} onClose={onClose} />)
await userEvent.click(await screen.findByText('Chill'))
expect(addToPlaylist).toHaveBeenCalledWith(10, 1)
expect(await screen.findByRole('button', { name: /Chill/ })).toBeDisabled()
expect(onClose).not.toHaveBeenCalled()
})
it('shows an error and stays open when adding fails', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST_A] })
vi.spyOn(libraryApi, 'addToPlaylist').mockRejectedValue(new ApiError(500, 'Server exploded', null))
render(<AddToPlaylistModal song={SONG} onClose={vi.fn()} />)
await userEvent.click(await screen.findByText('Chill'))
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
it('creates a new playlist and immediately adds the song to it', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const newPlaylist = { id: 12, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z' }
const createPlaylist = vi.spyOn(libraryApi, 'createPlaylist').mockResolvedValue({ status: 'success', playlist: newPlaylist })
const addToPlaylist = vi.spyOn(libraryApi, 'addToPlaylist').mockResolvedValue({ status: 'success', message: 'ok' })
render(<AddToPlaylistModal song={SONG} onClose={vi.fn()} />)
await screen.findByText('No playlists yet - create one above.')
await userEvent.type(screen.getByLabelText('New playlist name'), 'Road Trip')
await userEvent.click(screen.getByRole('button', { name: 'Create playlist' }))
expect(createPlaylist).toHaveBeenCalledWith('Road Trip')
expect(await screen.findByText('Road Trip')).toBeInTheDocument()
expect(addToPlaylist).toHaveBeenCalledWith(12, 1)
})
it('closes when the backdrop is clicked', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const onClose = vi.fn()
render(<AddToPlaylistModal song={SONG} onClose={onClose} />)
await userEvent.click(screen.getByRole('dialog'))
expect(onClose).toHaveBeenCalled()
})
it('closes on Escape', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const onClose = vi.fn()
render(<AddToPlaylistModal song={SONG} onClose={onClose} />)
await userEvent.keyboard('{Escape}')
expect(onClose).toHaveBeenCalled()
})
})
import { useEffect, useState } from 'react'
import { Check, ListMusic, Plus, X } from 'lucide-react'
import { addToPlaylist, createPlaylist, getPlaylists, type LibrarySong, type Playlist } from '../api/library'
import { ApiError } from '../api/client'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
interface AddToPlaylistModalProps {
song: LibrarySong
onClose: () => void
}
/** Modal for adding a single song (from the Library page) to one or more of the caller's own
* playlists - stays open after a successful add (rather than closing immediately) so adding to
* several playlists in a row doesn't mean reopening the picker each time. */
export function AddToPlaylistModal({ song, onClose }: AddToPlaylistModalProps) {
const [playlists, setPlaylists] = useState<Playlist[]>([])
const [loading, setLoading] = useState(true)
const [addedIds, setAddedIds] = useState<Set<number>>(new Set())
const [busyId, setBusyId] = useState<number | null>(null)
const [error, setError] = useState<string | null>(null)
const [newName, setNewName] = useState('')
const [creating, setCreating] = useState(false)
useEffect(() => {
getPlaylists()
.then((res) => setPlaylists(res.playlists))
.catch(() => {
// Modal just shows an empty list if this fails - the "New playlist" form still works.
})
.finally(() => setLoading(false))
}, [])
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
async function handleAdd(playlist: Playlist) {
setBusyId(playlist.id)
setError(null)
try {
await addToPlaylist(playlist.id, song.id)
setAddedIds((prev) => new Set(prev).add(playlist.id))
} catch (err) {
setError(err instanceof ApiError ? err.message : `Could not add to "${playlist.name}"`)
} finally {
setBusyId(null)
}
}
async function handleCreateAndAdd(e: React.FormEvent) {
e.preventDefault()
if (!newName.trim()) return
setCreating(true)
setError(null)
try {
const res = await createPlaylist(newName.trim())
setPlaylists((p) => [res.playlist, ...p])
setNewName('')
await handleAdd(res.playlist)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Could not create playlist')
} finally {
setCreating(false)
}
}
return (
<div
role="dialog"
aria-modal="true"
aria-label={`Add "${song.title}" to a playlist`}
className="fixed inset-0 z-40 flex items-end justify-center bg-black/60 sm:items-center"
onClick={onClose}
>
<div
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden rounded-t-2xl bg-neutral-900 sm:rounded-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-neutral-800 px-4 py-3">
<p className="min-w-0 truncate text-sm font-semibold text-white">Add "{song.title}" to playlist</p>
<button
onClick={onClose}
aria-label="Close"
className="shrink-0 rounded-full p-1.5 text-neutral-400 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<X size={18} strokeWidth={2} />
</button>
</div>
<form onSubmit={handleCreateAndAdd} className="flex items-center gap-2 px-4 pt-3">
<Input
placeholder="New playlist name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
aria-label="New playlist name"
/>
<Button type="submit" size="sm" disabled={creating || !newName.trim()} aria-label="Create playlist">
<Plus size={16} strokeWidth={2} />
</Button>
</form>
{error && <p className="px-4 pt-2 text-sm text-red-400">{error}</p>}
<ul className="mt-2 flex-1 overflow-y-auto px-2 pb-3">
{!loading && playlists.length === 0 && (
<p className="px-2 py-8 text-center text-sm text-neutral-500">No playlists yet - create one above.</p>
)}
{playlists.map((playlist) => {
const added = addedIds.has(playlist.id)
return (
<li key={playlist.id}>
<button
onClick={() => handleAdd(playlist)}
disabled={added || busyId === playlist.id}
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-default"
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<ListMusic size={14} strokeWidth={1.75} />
</div>
<p className="min-w-0 flex-1 truncate text-sm font-medium text-white">{playlist.name}</p>
{added ? (
<Check size={16} strokeWidth={2} className="shrink-0 text-emerald-400" />
) : busyId === playlist.id ? (
<span className="h-3.5 w-3.5 shrink-0 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : (
<Plus size={16} strokeWidth={2} className="shrink-0 text-neutral-500" />
)}
</button>
</li>
)
})}
</ul>
</div>
</div>
)
}
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
Disc3, Disc3,
Headphones, Headphones,
Library, Library,
ListMusic,
LogOut, LogOut,
Map, Map,
MapPin, MapPin,
...@@ -26,6 +27,7 @@ import { PlaybackErrorToast } from './PlaybackErrorToast' ...@@ -26,6 +27,7 @@ import { PlaybackErrorToast } from './PlaybackErrorToast'
const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/library', label: 'Library', icon: Library }, { to: '/library', label: 'Library', icon: Library },
{ to: '/playlists', label: 'Playlists', icon: ListMusic },
{ to: '/upload', label: 'Upload', icon: Upload }, { to: '/upload', label: 'Upload', icon: Upload },
{ to: '/discovery', label: 'Discover', icon: Compass }, { to: '/discovery', label: 'Discover', icon: Compass },
{ to: '/rooms', label: 'Rooms', icon: Radio }, { to: '/rooms', label: 'Rooms', icon: Radio },
......
...@@ -101,4 +101,21 @@ describe('Library', () => { ...@@ -101,4 +101,21 @@ describe('Library', () => {
expect(await within(row).findByRole('button', { name: 'Play' })).toBeInTheDocument() expect(await within(row).findByRole('button', { name: 'Play' })).toBeInTheDocument()
expect(fetchStreamUrl).toHaveBeenCalledTimes(1) // not called again on pause expect(fetchStreamUrl).toHaveBeenCalledTimes(1) // not called again on pause
}) })
it('opens the add-to-playlist modal for a song without triggering playback', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const getPlaylists = vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Add Invisible to a playlist' }))
expect(await screen.findByRole('dialog', { name: 'Add "Invisible" to a playlist' })).toBeInTheDocument()
expect(getPlaylists).toHaveBeenCalled()
// Opening the modal is a separate button from the row's own Play button - it must not
// also start playback.
expect(fetchStreamUrl).not.toHaveBeenCalled()
})
}) })
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Music2, Pause, Play } from 'lucide-react' import { ListPlus, Music2, Pause, Play } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library' import { getLibrary, 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 { 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 { usePlayer, type PlayableSong } from '../context/PlayerContext'
...@@ -22,6 +23,7 @@ export function Library() { ...@@ -22,6 +23,7 @@ export function Library() {
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)
const [addingSong, setAddingSong] = useState<LibrarySong | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
useEffect(() => { useEffect(() => {
...@@ -49,15 +51,17 @@ export function Library() { ...@@ -49,15 +51,17 @@ export function Library() {
{songs.map((song) => { {songs.map((song) => {
const isCurrent = currentSong?.id === song.id const isCurrent = currentSong?.id === song.id
return ( return (
<li key={song.id}> <li key={song.id} className="-mx-2 flex items-center gap-1 rounded-lg pr-2 hover:bg-white/5">
{/* The whole row plays the song, not just the little icon on the right - the {/* 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 icon is now a status indicator rendered inside this same button, not a
separate control. */} 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 <button
onClick={() => toggle(toPlayable(song), songs.map(toPlayable))} onClick={() => toggle(toPlayable(song), songs.map(toPlayable))}
disabled={isCurrent && streamLoading} disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'} aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed" className="flex min-w-0 flex-1 items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
> >
{song.coverart ? ( {song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" /> <img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
...@@ -83,10 +87,19 @@ export function Library() { ...@@ -83,10 +87,19 @@ export function Library() {
)} )}
</span> </span>
</button> </button>
<button
onClick={() => setAddingSong(song)}
aria-label={`Add ${song.title} to a playlist`}
className="shrink-0 rounded-full p-2 text-neutral-500 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</li> </li>
) )
})} })}
</ul> </ul>
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout> </Layout>
) )
} }
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Playlists } from './Playlists'
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 PLAYLIST = { id: 10, user_id: 1, name: 'Chill', created_at: '2026-01-01T00:00:00Z' }
const SONG = {
id: 1,
user_id: 1,
title: 'Invisible',
artist: 'Duran Duran',
album: 'Astronaut',
genre: 'Pop',
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
function renderPlaylists() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Playlists />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Playlists', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the empty state when there are no playlists', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
renderPlaylists()
expect(await screen.findByText(/No playlists yet/)).toBeInTheDocument()
})
it('renders each playlist once loaded', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST] })
renderPlaylists()
expect(await screen.findByText('Chill')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockRejectedValue(new ApiError(500, 'Server exploded', null))
renderPlaylists()
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
it('creates a playlist and adds it to the list', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [] })
const newPlaylist = { id: 20, user_id: 1, name: 'Road Trip', created_at: '2026-01-03T00:00:00Z' }
const createPlaylist = vi.spyOn(libraryApi, 'createPlaylist').mockResolvedValue({ status: 'success', playlist: newPlaylist })
renderPlaylists()
await screen.findByText(/No playlists yet/)
await userEvent.click(screen.getByRole('button', { name: 'New playlist' }))
await userEvent.type(screen.getByLabelText('Playlist name'), 'Road Trip')
await userEvent.click(screen.getByRole('button', { name: 'Create' }))
expect(createPlaylist).toHaveBeenCalledWith('Road Trip')
expect(await screen.findByText('Road Trip')).toBeInTheDocument()
})
it('opens a playlist and shows its tracks', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST] })
vi.spyOn(libraryApi, 'getPlaylist').mockResolvedValue({ status: 'success', playlist: PLAYLIST, tracks: [SONG] })
renderPlaylists()
await userEvent.click(await screen.findByText('Chill'))
expect(await screen.findByText('Invisible')).toBeInTheDocument()
expect(screen.getByText('Duran Duran · Astronaut')).toBeInTheDocument()
})
it('shows the empty state for a playlist with no tracks', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST] })
vi.spyOn(libraryApi, 'getPlaylist').mockResolvedValue({ status: 'success', playlist: PLAYLIST, tracks: [] })
renderPlaylists()
await userEvent.click(await screen.findByText('Chill'))
expect(await screen.findByText(/No songs in this playlist yet/)).toBeInTheDocument()
})
it('goes back to the playlist list', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST] })
vi.spyOn(libraryApi, 'getPlaylist').mockResolvedValue({ status: 'success', playlist: PLAYLIST, tracks: [SONG] })
renderPlaylists()
await userEvent.click(await screen.findByText('Chill'))
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Playlists' }))
expect(await screen.findByText(/Your own playlists/)).toBeInTheDocument()
})
it('plays a track from within a playlist', async () => {
vi.spyOn(libraryApi, 'getPlaylists').mockResolvedValue({ status: 'success', playlists: [PLAYLIST] })
vi.spyOn(libraryApi, 'getPlaylist').mockResolvedValue({ status: 'success', playlist: PLAYLIST, tracks: [SONG] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderPlaylists()
await userEvent.click(await screen.findByText('Chill'))
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(fetchStreamUrl).toHaveBeenCalledWith(1)
})
expect(await within(row).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { ArrowLeft, ListMusic, Music2, Pause, Play, Plus } from 'lucide-react'
import { createPlaylist, getPlaylist, getPlaylists, type LibrarySong, type Playlist } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
function toPlayable(song: LibrarySong): PlayableSong {
return {
id: song.id,
title: song.title,
artist: song.artist,
album: song.album,
coverart: song.coverart,
lyrics: song.lyrics,
}
}
export function Playlists() {
const [playlists, setPlaylists] = useState<Playlist[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [creating, setCreating] = useState(false)
const [newName, setNewName] = useState('')
const [createBusy, setCreateBusy] = useState(false)
const [createError, setCreateError] = useState<string | null>(null)
const [selected, setSelected] = useState<Playlist | null>(null)
const [tracks, setTracks] = useState<LibrarySong[]>([])
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function loadPlaylists() {
setLoading(true)
getPlaylists()
.then((res) => setPlaylists(res.playlists))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load playlists'))
.finally(() => setLoading(false))
}
useEffect(() => {
loadPlaylists()
}, [])
function openPlaylist(playlist: Playlist) {
setSelected(playlist)
setDetailLoading(true)
setDetailError(null)
getPlaylist(playlist.id)
.then((res) => setTracks(res.tracks))
.catch((err) => setDetailError(err instanceof ApiError ? err.message : 'Failed to load playlist'))
.finally(() => setDetailLoading(false))
}
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newName.trim()) return
setCreateBusy(true)
setCreateError(null)
try {
const res = await createPlaylist(newName.trim())
setPlaylists((p) => [res.playlist, ...p])
setNewName('')
setCreating(false)
} catch (err) {
setCreateError(err instanceof ApiError ? err.message : 'Could not create playlist')
} finally {
setCreateBusy(false)
}
}
if (selected) {
return (
<Layout title={selected.name}>
<button
onClick={() => setSelected(null)}
className="mb-4 flex items-center gap-1.5 text-sm text-neutral-400 transition-colors hover:text-white"
>
<ArrowLeft size={16} strokeWidth={2} />
Playlists
</button>
{detailLoading && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{detailError && <p className="text-sm text-red-400">{detailError}</p>}
{!detailLoading && !detailError && tracks.length === 0 && (
<EmptyState icon={Music2} message="No songs in this playlist yet - add some from your Library." />
)}
<ul className="divide-y divide-neutral-800/80">
{tracks.map((song) => {
const isCurrent = currentSong?.id === song.id
return (
<li key={song.id}>
<button
onClick={() => toggle(toPlayable(song), tracks.map(toPlayable))}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
>
{song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{song.title}</p>
<p className="truncate text-sm text-neutral-400">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
</li>
)
})}
</ul>
</Layout>
)
}
return (
<Layout title="Playlists">
<div className="mb-4 flex items-center justify-between gap-3">
<p className="text-sm text-neutral-500">Your own playlists, built from songs in your library.</p>
{!creating && (
<Button size="sm" onClick={() => setCreating(true)}>
<Plus size={16} strokeWidth={2} />
New playlist
</Button>
)}
</div>
{creating && (
<form onSubmit={handleCreate} className="mb-6 flex items-start gap-2">
<div className="flex-1">
<Input
placeholder="Playlist name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
autoFocus
aria-label="Playlist name"
/>
{createError && <p className="mt-1.5 text-sm text-red-400">{createError}</p>}
</div>
<Button type="submit" size="sm" disabled={createBusy || !newName.trim()}>
{createBusy ? 'Creating…' : 'Create'}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setCreating(false)
setNewName('')
setCreateError(null)
}}
>
Cancel
</Button>
</form>
)}
{loading && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="text-sm text-red-400">{error}</p>}
{!loading && !error && playlists.length === 0 && (
<EmptyState icon={ListMusic} message="No playlists yet - create one to start collecting songs." />
)}
<ul className="divide-y divide-neutral-800/80">
{playlists.map((playlist) => (
<li key={playlist.id}>
<button
onClick={() => openPlaylist(playlist)}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<ListMusic size={18} strokeWidth={1.75} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{playlist.name}</p>
<p className="truncate text-sm text-neutral-400">
Created {new Date(playlist.created_at).toLocaleDateString()}
</p>
</div>
</button>
</li>
))}
</ul>
</Layout>
)
}
...@@ -85,10 +85,10 @@ const FEATURES: Feature[] = [ ...@@ -85,10 +85,10 @@ const FEATURES: Feature[] = [
sub: 'Tagging, storage, playback', sub: 'Tagging, storage, playback',
status: 'good', status: 'good',
statusLabel: 'Mostly functional', statusLabel: 'Mostly functional',
built: 'Upload, tag, stream, cross-user scoping all correct — no impersonation holes.', built: 'Upload, tag, stream, cross-user scoping all correct — no impersonation holes. Playlist UI shipped 2026-08-16: create, view, add tracks, playback — reusing the existing backend endpoints plus one new GET /playlists/{id} for track detail.',
gaps: 'No delete for songs or playlist tracks. Playlists, library search, and a standalone lyrics fetch all have working endpoints with no UI. Upload.tsx has zero tests.', gaps: 'No delete for songs, playlists, or playlist tracks. Library search and a standalone lyrics fetch still have working endpoints with no UI. Upload.tsx has zero tests.',
backendTests: '28', backendTests: '32',
frontendTests: '5', frontendTests: '15',
}, },
{ {
name: 'Remix', name: 'Remix',
...@@ -135,7 +135,6 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[ ...@@ -135,7 +135,6 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
sub: 'Built, unreachable', sub: 'Built, unreachable',
dot: 'bg-amber-400', dot: 'bg-amber-400',
items: [ items: [
'Playlist UI — create, view, add tracks. Backend is ready.',
'Channels: vibe sets, stories, showcase screens.', 'Channels: vibe sets, stories, showcase screens.',
'Discovery → Library — make "like" actually save the song.', 'Discovery → Library — make "like" actually save the song.',
"Wire remix's library linking into the composer UI.", "Wire remix's library linking into the composer UI.",
...@@ -185,8 +184,8 @@ export function Roadmap() { ...@@ -185,8 +184,8 @@ export function Roadmap() {
{[ {[
['9', 'Feature areas'], ['9', 'Feature areas'],
['0', 'Critical security gaps'], ['0', 'Critical security gaps'],
['206', 'Backend tests'], ['210', 'Backend tests'],
['152', 'Frontend tests'], ['168', 'Frontend tests'],
['4', 'Pages w/ zero tests'], ['4', 'Pages w/ zero tests'],
].map(([n, l]) => ( ].map(([n, l]) => (
<div key={l}> <div key={l}>
......
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