Commit 2566afa1 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add shared in-app player so uploaded/library songs play consistently

Uploaded tracks are already added to the user's library server-side;
this makes them playable immediately via the same persistent player
used on the Library page, instead of each page owning its own audio
element and only offering a raw download link.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent c5510a27
Pipeline #1043 canceled with stage
......@@ -2,7 +2,9 @@ import type { ReactNode } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { Compass, Headphones, Library, LogOut, Radio, Rss, Upload, Wand2, type LucideIcon } from 'lucide-react'
import { useAuth } from '../context/AuthContext'
import { usePlayer } from '../context/PlayerContext'
import { Button } from './ui/Button'
import { NowPlayingBar } from './NowPlayingBar'
const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/library', label: 'Library', icon: Library },
......@@ -15,6 +17,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
export function Layout({ title, children }: { title: string; children: ReactNode }) {
const { logout } = useAuth()
const { currentSong } = usePlayer()
const location = useLocation()
async function handleLogout() {
......@@ -61,11 +64,15 @@ export function Layout({ title, children }: { title: string; children: ReactNode
</nav>
</header>
<main className="mx-auto max-w-2xl px-4 py-6 pb-24 sm:px-6 sm:py-8 sm:pb-8">
<main
className={`mx-auto max-w-2xl px-4 py-6 sm:px-6 sm:py-8 ${currentSong ? 'pb-40 sm:pb-24' : 'pb-24 sm:pb-8'}`}
>
<h1 className="mb-6 text-xl font-semibold tracking-tight">{title}</h1>
{children}
</main>
<NowPlayingBar />
{/* Bottom tab bar: mobile only, fixed, thumb-reachable. Hidden entirely at sm+ where
the top nav takes over instead. */}
<nav
......
import { Music2, Pause, Play } from 'lucide-react'
import { usePlayer } from '../context/PlayerContext'
/** Persistent player bar, visible on every page while a song is loaded (like Spotify's
* bottom bar) - stacked above the mobile tab bar (bottom-14 ≈ its height) since both are
* fixed to the viewport bottom; sits directly at the bottom on sm+ where there's no tab bar. */
export function NowPlayingBar() {
const { currentSong, isPlaying, isLoading, toggle } = usePlayer()
if (!currentSong) return null
return (
<div
className="fixed inset-x-0 bottom-14 z-20 border-t border-neutral-800 bg-neutral-900/95 backdrop-blur sm:bottom-0"
style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
>
<div className="mx-auto flex max-w-2xl items-center gap-3 px-4 py-2.5 sm:px-6">
{currentSong.coverart ? (
<img src={currentSong.coverart} alt="" className="h-10 w-10 shrink-0 rounded-md object-cover" />
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={16} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{currentSong.title}</p>
<p className="truncate text-xs text-neutral-400">{currentSong.artist}</p>
</div>
<button
onClick={() => toggle(currentSong)}
disabled={isLoading}
aria-label={isPlaying ? 'Pause' : 'Play'}
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white transition-transform active:scale-90 disabled:opacity-50"
>
{isLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</button>
</div>
</div>
)
}
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react'
import { fetchStreamUrl } from '../api/stream'
/** Minimal shape the player needs - both LibrarySong (Library page) and TagResponse's
* metadata (Upload page, right after tagging - has library_song_id/cover_art instead of
* id/coverart) get adapted to this at the call site, so the player itself doesn't care which
* page a song came from. */
export interface PlayableSong {
id: number
title: string
artist: string
coverart?: string | null
}
interface PlayerContextValue {
currentSong: PlayableSong | null
isPlaying: boolean
isLoading: boolean
/** Toggles play/pause if this song is already current, otherwise starts playing it fresh. */
toggle: (song: PlayableSong) => void
pause: () => void
}
const PlayerContext = createContext<PlayerContextValue | null>(null)
export function PlayerProvider({ children }: { children: ReactNode }) {
const [currentSong, setCurrentSong] = useState<PlayableSong | null>(null)
const [isPlaying, setIsPlaying] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const audioRef = useRef<HTMLAudioElement | null>(null)
const objectUrlRef = useRef<string | null>(null)
// Guards against a slow fetchStreamUrl resolving after the user has already moved on to a
// different song - without this, an old request landing late could stomp the new one.
const requestIdRef = useRef(0)
useEffect(() => {
const audio = new Audio()
audioRef.current = audio
const onEnded = () => setIsPlaying(false)
audio.addEventListener('ended', onEnded)
return () => {
audio.removeEventListener('ended', onEnded)
audio.pause()
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
}
}, [])
const pause = useCallback(() => {
audioRef.current?.pause()
setIsPlaying(false)
}, [])
const toggle = useCallback(
(song: PlayableSong) => {
const audio = audioRef.current
if (!audio) return
if (currentSong?.id === song.id) {
if (isPlaying) {
pause()
} else {
audio.play()
setIsPlaying(true)
}
return
}
const requestId = ++requestIdRef.current
setCurrentSong(song)
setIsLoading(true)
setIsPlaying(false)
fetchStreamUrl(song.id)
.then((url) => {
if (requestId !== requestIdRef.current) {
URL.revokeObjectURL(url) // a newer toggle() call already superseded this one
return
}
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
objectUrlRef.current = url
audio.src = url
return audio.play().then(() => {
if (requestId === requestIdRef.current) setIsPlaying(true)
})
})
.catch(() => {
if (requestId === requestIdRef.current) setCurrentSong(null)
})
.finally(() => {
if (requestId === requestIdRef.current) setIsLoading(false)
})
},
[currentSong, isPlaying, pause],
)
return (
<PlayerContext.Provider value={{ currentSong, isPlaying, isLoading, toggle, pause }}>
{children}
</PlayerContext.Provider>
)
}
export function usePlayer(): PlayerContextValue {
const ctx = useContext(PlayerContext)
if (!ctx) throw new Error('usePlayer must be used within a PlayerProvider')
return ctx
}
......@@ -4,12 +4,15 @@ import { BrowserRouter } from 'react-router-dom'
import './index.css'
import { App } from './App.tsx'
import { AuthProvider } from './context/AuthContext.tsx'
import { PlayerProvider } from './context/PlayerContext.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>
<AuthProvider>
<App />
<PlayerProvider>
<App />
</PlayerProvider>
</AuthProvider>
</BrowserRouter>
</StrictMode>,
......
import { render, screen, waitFor } from '@testing-library/react'
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 { Library } from './Library'
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'
......@@ -25,7 +26,9 @@ function renderLibrary() {
return render(
<MemoryRouter>
<AuthProvider>
<Library />
<PlayerProvider>
<Library />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
......@@ -72,14 +75,16 @@ describe('Library', () => {
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
await screen.findByText('Invisible')
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await userEvent.click(within(row).getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(fetchStreamUrl).toHaveBeenCalledWith(1)
})
expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
// NowPlayingBar mounts a second "Pause" button once a song is loaded - the row's own
// button is the one under test here.
expect(await within(row).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('pauses without re-fetching the stream when clicked again while playing', async () => {
......@@ -87,13 +92,13 @@ describe('Library', () => {
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await screen.findByRole('button', { name: 'Pause' })
const row = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(row).getByRole('button', { name: 'Play' }))
await within(row).findByRole('button', { name: 'Pause' })
await userEvent.click(screen.getByRole('button', { name: 'Pause' }))
await userEvent.click(within(row).getByRole('button', { name: 'Pause' }))
expect(await screen.findByRole('button', { name: 'Play' })).toBeInTheDocument()
expect(await within(row).findByRole('button', { name: 'Play' })).toBeInTheDocument()
expect(fetchStreamUrl).toHaveBeenCalledTimes(1) // not called again on pause
})
})
import { useEffect, useRef, useState } from 'react'
import { useEffect, useState } from 'react'
import { Music2, Pause, Play } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library'
import { fetchStreamUrl } from '../api/stream'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer } from '../context/PlayerContext'
export function Library() {
const [songs, setSongs] = useState<LibrarySong[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [playingId, setPlayingId] = useState<number | null>(null)
const [streamLoading, setStreamLoading] = useState<number | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const objectUrlRef = useRef<string | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
useEffect(() => {
getLibrary()
......@@ -24,40 +21,8 @@ export function Library() {
.finally(() => setLoading(false))
}, [])
useEffect(() => {
return () => {
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
}
}, [])
async function handlePlay(song: LibrarySong) {
if (playingId === song.id) {
audioRef.current?.pause()
setPlayingId(null)
return
}
setStreamLoading(song.id)
try {
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
const url = await fetchStreamUrl(song.id)
objectUrlRef.current = url
if (audioRef.current) {
audioRef.current.src = url
await audioRef.current.play()
}
setPlayingId(song.id)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to play song')
} finally {
setStreamLoading(null)
}
}
return (
<Layout title="Library">
<audio ref={audioRef} onEnded={() => setPlayingId(null)} className="hidden" />
{loading && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
......@@ -71,39 +36,42 @@ export function Library() {
)}
<ul className="divide-y divide-neutral-800/80">
{songs.map((song) => (
<li key={song.id} className="flex items-center gap-4 py-3">
{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>
<Button
variant="secondary"
size="icon"
onClick={() => handlePlay(song)}
disabled={streamLoading === song.id}
aria-label={playingId === song.id ? 'Pause' : 'Play'}
>
{streamLoading === song.id ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : playingId === song.id ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
{songs.map((song) => {
const isCurrent = currentSong?.id === song.id
return (
<li key={song.id} className="flex items-center gap-4 py-3">
{song.coverart ? (
<img src={song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-md object-cover" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
<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>
)}
</Button>
</li>
))}
<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>
<Button
variant="secondary"
size="icon"
onClick={() => toggle({ id: song.id, title: song.title, artist: song.artist, coverart: song.coverart })}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
>
{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" />
)}
</Button>
</li>
)
})}
</ul>
</Layout>
)
......
import { useState } from 'react'
import { UploadCloud } from 'lucide-react'
import { Pause, Play, UploadCloud } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { ProgressBar } from '../components/ui/ProgressBar'
import { uploadDirect, type TagResponse } from '../api/music'
import { usePlayer } from '../context/PlayerContext'
type Stage = 'idle' | 'uploading' | 'processing'
......@@ -37,6 +38,8 @@ export function Upload() {
}
const busy = stage !== 'idle'
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const isCurrent = !!result && currentSong?.id === result.metadata.library_song_id
return (
<Layout title="Upload &amp; Tag">
......@@ -79,19 +82,43 @@ export function Upload() {
{result.metadata.cover_art && (
<img src={result.metadata.cover_art} alt="" className="h-20 w-20 rounded-lg object-cover" />
)}
<div>
<div className="min-w-0 flex-1">
<p className="font-semibold text-white">{result.metadata.title}</p>
<p className="text-sm text-neutral-400">
{result.metadata.artist} · {result.metadata.album} · {result.metadata.genre}
</p>
<a
href={result.download_url}
target="_blank"
rel="noreferrer"
className="mt-2 inline-block text-sm text-emerald-400 hover:underline"
>
Download tagged file
</a>
<div className="mt-3 flex items-center gap-3">
<Button
size="sm"
onClick={() =>
toggle({
id: result.metadata.library_song_id,
title: result.metadata.title,
artist: result.metadata.artist,
coverart: result.metadata.cover_art,
})
}
disabled={isCurrent && streamLoading}
className="gap-1.5"
>
{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={14} strokeWidth={2} fill="currentColor" />
) : (
<Play size={14} strokeWidth={2} fill="currentColor" />
)}
{isCurrent && isPlaying ? 'Pause' : 'Play'}
</Button>
<a
href={result.download_url}
target="_blank"
rel="noreferrer"
className="text-sm text-neutral-400 hover:text-white hover:underline"
>
Download tagged file
</a>
</div>
</div>
</div>
)}
......
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