Commit 54d3c423 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a full-screen Spotify-style player: lyrics, next/previous, queue

PlayerContext now tracks a queue (whatever list a song was played
from) plus playback progress/duration, and exposes next/previous that
step through it - auto-advancing on track end, restarting the current
track on "previous" if more than a few seconds in, same as Spotify.
Tapping the mini-player (NowPlayingBar) opens a full-screen view with
a seek bar, transport controls, and a lyrics toggle backed by the
lyrics the backend already tags songs with.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 2566afa1
Pipeline #1044 canceled with stage
import { useState } from 'react'
import { ChevronDown, ListMusic, Music2, Pause, Play, SkipBack, SkipForward } from 'lucide-react'
import { usePlayer } from '../context/PlayerContext'
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '0:00'
const mins = Math.floor(seconds / 60)
const secs = Math.floor(seconds % 60)
return `${mins}:${secs.toString().padStart(2, '0')}`
}
/** Full-screen "Now Playing" view, opened from NowPlayingBar - mirrors the Spotify pattern
* of a persistent mini-player that expands into a dedicated screen with transport controls,
* a seek bar, and a lyrics toggle. Renders nothing when collapsed or when nothing is loaded. */
export function FullPlayer() {
const {
currentSong,
isPlaying,
isLoading,
isExpanded,
progress,
duration,
hasNext,
toggle,
next,
previous,
seek,
collapse,
} = usePlayer()
const [showLyrics, setShowLyrics] = useState(false)
if (!isExpanded || !currentSong) return null
return (
<div className="fixed inset-0 z-30 flex flex-col bg-neutral-950 text-white">
<div
className="flex items-center justify-between px-4 pt-4 sm:px-6"
style={{ paddingTop: 'calc(env(safe-area-inset-top) + 1rem)' }}
>
<button
onClick={collapse}
aria-label="Minimize player"
className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-400 transition-colors hover:bg-neutral-900 hover:text-white"
>
<ChevronDown size={22} strokeWidth={2} />
</button>
<p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Now Playing</p>
<button
onClick={() => setShowLyrics((v) => !v)}
aria-label={showLyrics ? 'Show cover art' : 'Show lyrics'}
aria-pressed={showLyrics}
className={`flex h-10 w-10 items-center justify-center rounded-full transition-colors ${
showLyrics ? 'bg-neutral-900 text-emerald-400' : 'text-neutral-400 hover:bg-neutral-900 hover:text-white'
}`}
>
<ListMusic size={19} strokeWidth={2} />
</button>
</div>
<div className="mx-auto flex w-full max-w-md flex-1 flex-col items-center justify-center overflow-hidden px-6 py-6">
{showLyrics ? (
<div className="h-full w-full overflow-y-auto rounded-2xl bg-neutral-900/50 p-5">
{currentSong.lyrics ? (
<p className="whitespace-pre-wrap text-[15px] leading-relaxed text-neutral-200">
{currentSong.lyrics}
</p>
) : (
<p className="text-sm text-neutral-500">No lyrics available for this track.</p>
)}
</div>
) : currentSong.coverart ? (
<img
src={currentSong.coverart}
alt=""
className="aspect-square w-full max-w-sm rounded-2xl object-cover shadow-2xl shadow-black/40"
/>
) : (
<div className="flex aspect-square w-full max-w-sm items-center justify-center rounded-2xl bg-neutral-900 text-neutral-700">
<Music2 size={64} strokeWidth={1.25} />
</div>
)}
</div>
<div
className="mx-auto w-full max-w-md px-6 pb-6 sm:pb-8"
style={{ paddingBottom: 'calc(env(safe-area-inset-bottom) + 1.5rem)' }}
>
<div className="mb-6">
<p className="truncate text-xl font-semibold">{currentSong.title}</p>
<p className="truncate text-sm text-neutral-400">
{currentSong.artist}
{currentSong.album ? ` · ${currentSong.album}` : ''}
</p>
</div>
<input
type="range"
min={0}
max={duration || 0}
value={Math.min(progress, duration || 0)}
step={0.1}
onChange={(e) => seek(Number(e.target.value))}
disabled={!duration}
aria-label="Seek"
className="w-full accent-emerald-400 disabled:opacity-40"
/>
<div className="mt-1 flex justify-between text-xs text-neutral-500">
<span>{formatTime(progress)}</span>
<span>{formatTime(duration)}</span>
</div>
<div className="mt-6 flex items-center justify-center gap-8">
<button
onClick={previous}
aria-label="Previous"
className="text-neutral-300 transition-colors hover:text-white"
>
<SkipBack size={26} strokeWidth={2} fill="currentColor" />
</button>
<button
onClick={() => toggle(currentSong)}
disabled={isLoading}
aria-label={isPlaying ? 'Pause' : 'Play'}
className="flex h-16 w-16 items-center justify-center rounded-full bg-white text-neutral-950 transition-transform active:scale-90 disabled:opacity-50"
>
{isLoading ? (
<span className="h-5 w-5 animate-spin rounded-full border-2 border-neutral-400 border-t-neutral-950" />
) : isPlaying ? (
<Pause size={24} strokeWidth={2} fill="currentColor" />
) : (
<Play size={24} strokeWidth={2} fill="currentColor" className="ml-1" />
)}
</button>
<button
onClick={next}
disabled={!hasNext}
aria-label="Next"
className="text-neutral-300 transition-colors hover:text-white disabled:opacity-30"
>
<SkipForward size={26} strokeWidth={2} fill="currentColor" />
</button>
</div>
</div>
</div>
)
}
......@@ -5,6 +5,7 @@ import { useAuth } from '../context/AuthContext'
import { usePlayer } from '../context/PlayerContext'
import { Button } from './ui/Button'
import { NowPlayingBar } from './NowPlayingBar'
import { FullPlayer } from './FullPlayer'
const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/library', label: 'Library', icon: Library },
......@@ -72,6 +73,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
</main>
<NowPlayingBar />
<FullPlayer />
{/* Bottom tab bar: mobile only, fixed, thumb-reachable. Hidden entirely at sm+ where
the top nav takes over instead. */}
......
......@@ -5,7 +5,7 @@ import { usePlayer } from '../context/PlayerContext'
* 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()
const { currentSong, isPlaying, isLoading, toggle, expand } = usePlayer()
if (!currentSong) return null
......@@ -15,6 +15,13 @@ export function NowPlayingBar() {
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">
{/* Separate <button> from the play/pause control below - two sibling buttons rather
than nesting one inside the other, which isn't valid HTML. */}
<button
onClick={expand}
aria-label={`Open player - ${currentSong.title}`}
className="flex min-w-0 flex-1 items-center gap-3 text-left"
>
{currentSong.coverart ? (
<img src={currentSong.coverart} alt="" className="h-10 w-10 shrink-0 rounded-md object-cover" />
) : (
......@@ -26,6 +33,7 @@ export function NowPlayingBar() {
<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>
<button
onClick={() => toggle(currentSong)}
disabled={isLoading}
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PlayerProvider, usePlayer, type PlayableSong } from './PlayerContext'
import * as streamApi from '../api/stream'
const SONG_A: PlayableSong = { id: 1, title: 'Song A', artist: 'Artist A' }
const SONG_B: PlayableSong = { id: 2, title: 'Song B', artist: 'Artist B' }
const SONG_C: PlayableSong = { id: 3, title: 'Song C', artist: 'Artist C' }
const QUEUE = [SONG_A, SONG_B, SONG_C]
function Probe() {
const { currentSong, hasNext, hasPrevious, toggle, next, previous } = usePlayer()
return (
<div>
<span data-testid="current">{currentSong?.title ?? 'none'}</span>
<span data-testid="has-next">{String(hasNext)}</span>
<span data-testid="has-previous">{String(hasPrevious)}</span>
<button onClick={() => toggle(SONG_A, QUEUE)}>Play A</button>
<button onClick={next}>Next</button>
<button onClick={previous}>Previous</button>
</div>
)
}
function renderProbe() {
return render(
<PlayerProvider>
<Probe />
</PlayerProvider>,
)
}
describe('PlayerContext queue navigation', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('steps forward through the queue passed to toggle', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
expect(screen.getByTestId('has-previous')).toHaveTextContent('false')
expect(screen.getByTestId('has-next')).toHaveTextContent('true')
await userEvent.click(screen.getByText('Next'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song B'))
await userEvent.click(screen.getByText('Next'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song C'))
expect(screen.getByTestId('has-next')).toHaveTextContent('false')
// Already at the end of the queue - clicking Next again is a no-op, not an error.
await userEvent.click(screen.getByText('Next'))
expect(screen.getByTestId('current')).toHaveTextContent('Song C')
})
it('steps backward through the queue', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
await userEvent.click(screen.getByText('Next'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song B'))
await userEvent.click(screen.getByText('Previous'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
expect(screen.getByTestId('has-previous')).toHaveTextContent('false')
})
})
......@@ -9,37 +9,118 @@ export interface PlayableSong {
id: number
title: string
artist: string
album?: string | null
coverart?: string | null
lyrics?: string | null
}
interface PlayerContextValue {
currentSong: PlayableSong | null
queue: PlayableSong[]
isPlaying: boolean
isLoading: boolean
/** Toggles play/pause if this song is already current, otherwise starts playing it fresh. */
toggle: (song: PlayableSong) => void
isExpanded: boolean
/** Seconds. `duration` is 0 until the browser has metadata for the current track. */
progress: number
duration: number
hasNext: boolean
hasPrevious: boolean
/** Toggles play/pause if this song is already current, otherwise starts playing it fresh.
* `queue` sets what `next`/`previous` step through - pass the full list a song was played
* from (e.g. the whole library) so skipping stays within that context. Defaults to a
* single-song queue when omitted. */
toggle: (song: PlayableSong, queue?: PlayableSong[]) => void
pause: () => void
next: () => void
/** Restarts the current track if more than a few seconds in (Spotify convention),
* otherwise jumps to the previous song in the queue. */
previous: () => void
seek: (time: number) => void
expand: () => void
collapse: () => void
}
const PlayerContext = createContext<PlayerContextValue | null>(null)
export function PlayerProvider({ children }: { children: ReactNode }) {
const [currentSong, setCurrentSong] = useState<PlayableSong | null>(null)
const [queue, setQueue] = useState<PlayableSong[]>([])
const [isPlaying, setIsPlaying] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [isExpanded, setIsExpanded] = useState(false)
const [progress, setProgress] = useState(0)
const [duration, setDuration] = useState(0)
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)
const playSong = useCallback((song: PlayableSong) => {
const audio = audioRef.current
if (!audio) return
const requestId = ++requestIdRef.current
setCurrentSong(song)
setIsLoading(true)
setIsPlaying(false)
setProgress(0)
setDuration(0)
fetchStreamUrl(song.id)
.then((url) => {
if (requestId !== requestIdRef.current) {
URL.revokeObjectURL(url) // a newer play request 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)
})
}, [])
const currentIndex = currentSong ? queue.findIndex((s) => s.id === currentSong.id) : -1
const hasNext = currentIndex >= 0 && currentIndex < queue.length - 1
const hasPrevious = currentIndex > 0
const next = useCallback(() => {
if (currentIndex >= 0 && currentIndex < queue.length - 1) {
playSong(queue[currentIndex + 1])
} else {
setIsPlaying(false)
}
}, [currentIndex, queue, playSong])
// Kept fresh via a ref (rather than depending on `next` directly) so the mount effect below
// can stay a one-time [] effect instead of tearing down/recreating the audio element - and
// its listeners - every time the queue changes.
const nextRef = useRef(next)
useEffect(() => {
nextRef.current = next
}, [next])
useEffect(() => {
const audio = new Audio()
audioRef.current = audio
const onEnded = () => setIsPlaying(false)
const onEnded = () => nextRef.current()
const onTimeUpdate = () => setProgress(audio.currentTime)
const onLoadedMetadata = () => setDuration(audio.duration || 0)
audio.addEventListener('ended', onEnded)
audio.addEventListener('timeupdate', onTimeUpdate)
audio.addEventListener('loadedmetadata', onLoadedMetadata)
return () => {
audio.removeEventListener('ended', onEnded)
audio.removeEventListener('timeupdate', onTimeUpdate)
audio.removeEventListener('loadedmetadata', onLoadedMetadata)
audio.pause()
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
}
......@@ -50,8 +131,30 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
setIsPlaying(false)
}, [])
const previous = useCallback(() => {
const audio = audioRef.current
if (audio && audio.currentTime > 3) {
audio.currentTime = 0
setProgress(0)
return
}
if (currentIndex > 0) {
playSong(queue[currentIndex - 1])
}
}, [currentIndex, queue, playSong])
const seek = useCallback((time: number) => {
const audio = audioRef.current
if (!audio) return
audio.currentTime = time
setProgress(time)
}, [])
const expand = useCallback(() => setIsExpanded(true), [])
const collapse = useCallback(() => setIsExpanded(false), [])
const toggle = useCallback(
(song: PlayableSong) => {
(song: PlayableSong, songQueue?: PlayableSong[]) => {
const audio = audioRef.current
if (!audio) return
......@@ -65,36 +168,33 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
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)
})
setQueue(songQueue && songQueue.length > 0 ? songQueue : [song])
playSong(song)
},
[currentSong, isPlaying, pause],
[currentSong, isPlaying, pause, playSong],
)
return (
<PlayerContext.Provider value={{ currentSong, isPlaying, isLoading, toggle, pause }}>
<PlayerContext.Provider
value={{
currentSong,
queue,
isPlaying,
isLoading,
isExpanded,
progress,
duration,
hasNext,
hasPrevious,
toggle,
pause,
next,
previous,
seek,
expand,
collapse,
}}
>
{children}
</PlayerContext.Provider>
)
......
......@@ -6,7 +6,18 @@ 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'
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 Library() {
const [songs, setSongs] = useState<LibrarySong[]>([])
......@@ -57,7 +68,7 @@ export function Library() {
<Button
variant="secondary"
size="icon"
onClick={() => toggle({ id: song.id, title: song.title, artist: song.artist, coverart: song.coverart })}
onClick={() => toggle(toPlayable(song), songs.map(toPlayable))}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
>
......
......@@ -95,7 +95,9 @@ export function Upload() {
id: result.metadata.library_song_id,
title: result.metadata.title,
artist: result.metadata.artist,
album: result.metadata.album,
coverart: result.metadata.cover_art,
lyrics: result.metadata.lyrics,
})
}
disabled={isCurrent && streamLoading}
......
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