Commit 3578ac25 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add queue view, shuffle/repeat, playback error feedback, visual polish

Verified against a real headless browser this round (Playwright) -
several of these were found by actually looking at the rendered UI,
not just reasoning about the code:

- Failed plays (bad stream, network error, blocked autoplay) now
  surface a dismissible toast instead of silently clearing the song
  with no feedback. Caught and fixed a real bug here: the toast's
  first version rendered on top of the page header, hiding it - it
  now sits just below it.
- FullPlayer gains a third "Queue" tab (tap any track to jump to it),
  plus shuffle and repeat (off/all/one) controls in the transport row.
  Repeat-one only affects natural track-end, not the Next button,
  matching standard player behavior.
- Loading state gets real visual feedback: a pulsing cover art and a
  "Loading…" label in place of the time readout.
- Visual composition pass: a blurred, dimmed cover-art backdrop fills
  the dead space around the centered album art (Spotify/Apple Music
  convention), the Cover/Lyrics/Queue tab icons are now symmetric, and
  a hairline border separates the scrollable lyrics panel from the
  title block below it so the fade-out text no longer visually bleeds
  into it.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 867aa9c8
Pipeline #1046 canceled with stage
import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { ChevronDown, Music2, Pause, Play, ScrollText, SkipBack, SkipForward } from 'lucide-react'
import { usePlayer } from '../context/PlayerContext'
import {
AudioLines,
ChevronDown,
Disc3,
ListMusic,
Music2,
Pause,
Play,
Repeat,
Repeat1,
ScrollText,
Shuffle,
SkipBack,
SkipForward,
type LucideIcon,
} from 'lucide-react'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { EmptyState } from './ui/EmptyState'
import { useMountTransition } from '../hooks/useMountTransition'
......@@ -13,31 +28,37 @@ function formatTime(seconds: number): string {
return `${mins}:${secs.toString().padStart(2, '0')}`
}
const TABS = [
{ id: 'cover', label: 'Cover' },
{ id: 'lyrics', label: 'Lyrics' },
] as const
const TABS: { id: 'cover' | 'lyrics' | 'queue'; label: string; icon: LucideIcon }[] = [
{ id: 'cover', label: 'Cover', icon: Disc3 },
{ id: 'lyrics', label: 'Lyrics', icon: ScrollText },
{ id: 'queue', label: 'Queue', icon: ListMusic },
]
type TabId = (typeof TABS)[number]['id']
/** 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 Cover/Lyrics view switcher. Stays mounted for one extra animation frame
* after closing so the exit transition can play (see useMountTransition), and is otherwise
* absent from the DOM - no hidden-but-focusable controls left behind. */
* a seek bar, and Cover/Lyrics/Queue views. Stays mounted for one extra animation frame after
* closing so the exit transition can play (see useMountTransition), and is otherwise absent
* from the DOM - no hidden-but-focusable controls left behind. */
export function FullPlayer() {
const {
currentSong,
queue,
isPlaying,
isLoading,
isExpanded,
progress,
duration,
hasNext,
isShuffled,
repeatMode,
toggle,
next,
previous,
seek,
collapse,
toggleShuffle,
cycleRepeat,
} = usePlayer()
const [activeTab, setActiveTab] = useState<TabId>('cover')
const { mounted, visible } = useMountTransition(isExpanded && !!currentSong, ANIMATION_MS)
......@@ -84,26 +105,45 @@ export function FullPlayer() {
}
}
function jumpTo(song: PlayableSong) {
toggle(song, queue)
}
const pct = duration > 0 ? Math.min(100, (progress / duration) * 100) : 0
const RepeatIcon = repeatMode === 'one' ? Repeat1 : Repeat
return (
<div
role="dialog"
aria-modal="true"
aria-label={`Now playing: ${currentSong.title} by ${currentSong.artist}`}
className={`fixed inset-0 z-30 flex flex-col bg-neutral-950 text-white transition-all duration-300 ease-out motion-reduce:transition-none ${
className={`fixed inset-0 z-30 flex flex-col overflow-hidden bg-neutral-950 text-white transition-all duration-300 ease-out motion-reduce:transition-none ${
visible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
}`}
>
{/* Large, blurred backdrop of the current cover art - fills the otherwise-empty space
around a centered album cover with something alive, rather than flat black (the
Spotify/Apple Music "now playing" convention). Purely decorative. */}
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
{currentSong.coverart && (
<img
src={currentSong.coverart}
alt=""
className="absolute inset-0 h-full w-full scale-110 object-cover opacity-20 blur-3xl"
/>
)}
<div className="absolute inset-0 bg-neutral-950/75" />
</div>
<div
className="flex items-center justify-between px-4 pt-4 sm:px-6"
className="relative flex items-center justify-between px-4 pt-4 sm:px-6"
style={{ paddingTop: 'calc(env(safe-area-inset-top) + 1rem)' }}
>
<button
ref={collapseButtonRef}
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 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
className="flex h-10 w-10 items-center justify-center rounded-full 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"
>
<ChevronDown size={22} strokeWidth={2} />
</button>
......@@ -111,13 +151,10 @@ export function FullPlayer() {
<div className="h-10 w-10" aria-hidden="true" />
</div>
<div
role="tablist"
aria-label="Now playing view"
className="mx-auto mt-4 flex gap-1 rounded-full bg-neutral-900 p-1"
>
<div role="tablist" aria-label="Now playing view" className="relative mx-auto mt-3 flex gap-1 rounded-full bg-white/5 p-1">
{TABS.map((tab, index) => {
const active = activeTab === tab.id
const Icon = tab.icon
return (
<button
key={tab.id}
......@@ -131,28 +168,28 @@ export function FullPlayer() {
tabIndex={active ? 0 : -1}
onClick={() => setActiveTab(tab.id)}
onKeyDown={(e) => onTabKeyDown(e, index)}
className={`flex items-center gap-1.5 rounded-full px-4 py-1.5 text-sm font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 ${
className={`flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 ${
active ? 'bg-neutral-100 text-neutral-950' : 'text-neutral-400 hover:text-white'
}`}
>
{tab.id === 'lyrics' && <ScrollText size={14} strokeWidth={2} />}
<Icon size={14} strokeWidth={2} />
{tab.label}
</button>
)
})}
</div>
<div className="relative mx-auto w-full max-w-md flex-1 overflow-hidden px-6 py-6">
{/* Neither panel below contains focusable content (the cover is a decorative image,
the lyrics are plain text), so it's safe to keep both mounted and crossfade opacity
rather than snap-toggling with the `hidden` attribute - aria-hidden still keeps the
inactive one out of the accessibility tree. */}
<div className="relative mx-auto w-full max-w-md flex-1 overflow-hidden px-6 py-5">
{/* None of the three panels below contain focusable content (decorative image, plain
lyrics text, or a queue list that's only rendered while its own tab is active), so
it's safe to crossfade Cover/Lyrics with opacity instead of snap-toggling via the
`hidden` attribute - aria-hidden keeps the inactive one out of the a11y tree. */}
<div
id="player-panel-cover"
role="tabpanel"
aria-labelledby="player-tab-cover"
aria-hidden={activeTab !== 'cover'}
className={`absolute inset-6 flex items-center justify-center transition-opacity duration-300 ease-out motion-reduce:transition-none ${
className={`absolute inset-4 flex items-center justify-center transition-opacity duration-300 ease-out motion-reduce:transition-none ${
activeTab === 'cover' ? 'opacity-100' : 'pointer-events-none opacity-0'
}`}
>
......@@ -160,10 +197,16 @@ export function FullPlayer() {
<img
src={currentSong.coverart}
alt=""
className="aspect-square w-full max-w-sm rounded-2xl object-cover shadow-2xl shadow-black/40"
className={`aspect-square w-full max-w-sm rounded-2xl object-cover shadow-2xl shadow-black/40 transition-opacity duration-300 ${
isLoading ? 'animate-pulse opacity-60' : 'opacity-100'
}`}
/>
) : (
<div className="flex aspect-square w-full max-w-sm items-center justify-center rounded-2xl bg-neutral-900 text-neutral-700">
<div
className={`flex aspect-square w-full max-w-sm items-center justify-center rounded-2xl bg-neutral-900 text-neutral-700 ${
isLoading ? 'animate-pulse' : ''
}`}
>
<Music2 size={64} strokeWidth={1.25} />
</div>
)}
......@@ -174,7 +217,7 @@ export function FullPlayer() {
role="tabpanel"
aria-labelledby="player-tab-lyrics"
aria-hidden={activeTab !== 'lyrics'}
className={`absolute inset-0 overflow-y-auto rounded-2xl bg-neutral-900/50 px-5 py-8 transition-opacity duration-300 ease-out motion-reduce:transition-none ${
className={`absolute inset-0 overflow-y-auto rounded-2xl bg-white/5 px-5 py-8 transition-opacity duration-300 ease-out motion-reduce:transition-none ${
activeTab === 'lyrics' ? 'opacity-100' : 'pointer-events-none opacity-0'
}`}
style={{
......@@ -189,13 +232,59 @@ export function FullPlayer() {
<EmptyState icon={ScrollText} message="No lyrics available for this track." />
)}
</div>
<div
id="player-panel-queue"
role="tabpanel"
aria-labelledby="player-tab-queue"
aria-hidden={activeTab !== 'queue'}
className={`absolute inset-0 overflow-y-auto transition-opacity duration-300 ease-out motion-reduce:transition-none ${
activeTab === 'queue' ? 'opacity-100' : 'pointer-events-none opacity-0'
}`}
>
{queue.length === 0 ? (
<EmptyState icon={ListMusic} message="Nothing queued." />
) : (
<ul>
{queue.map((song, index) => {
const isCurrent = song.id === currentSong.id
return (
<li key={song.id}>
<button
onClick={() => jumpTo(song)}
aria-current={isCurrent ? 'true' : undefined}
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 ${
isCurrent ? 'text-emerald-400' : 'text-neutral-300 hover:bg-white/5 hover:text-white'
}`}
>
<span className="flex w-5 shrink-0 items-center justify-center text-xs text-neutral-500">
{isCurrent ? <AudioLines size={15} strokeWidth={2} /> : index + 1}
</span>
{song.coverart ? (
<img src={song.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={15} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{song.title}</p>
<p className="truncate text-xs text-neutral-500">{song.artist}</p>
</div>
</button>
</li>
)
})}
</ul>
)}
</div>
</div>
<div
className="mx-auto w-full max-w-md px-6 pb-6 sm:pb-8"
className="relative mx-auto w-full max-w-md border-t border-white/5 px-6 pt-5 pb-6 sm:pb-8"
style={{ paddingBottom: 'calc(env(safe-area-inset-bottom) + 1.5rem)' }}
>
<div className="mb-6">
<div className="mb-5">
<p className="truncate text-xl font-semibold">{currentSong.title}</p>
<p className="truncate text-sm text-neutral-400">
{currentSong.artist}
......@@ -217,39 +306,69 @@ export function FullPlayer() {
style={{ background: `linear-gradient(to right, white ${pct}%, #262626 ${pct}%)` }}
/>
<div className="mt-1 flex justify-between text-xs text-neutral-500">
<span>{formatTime(progress)}</span>
<span>{formatTime(duration)}</span>
{isLoading ? (
<span className="mx-auto">Loading…</span>
) : (
<>
<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="rounded-full p-1 text-neutral-300 transition-colors hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<SkipBack size={26} strokeWidth={2} fill="currentColor" />
</button>
<div className="mt-5 flex items-center justify-between">
<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 duration-150 ease-out active:scale-90 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950"
onClick={toggleShuffle}
aria-label="Shuffle"
aria-pressed={isShuffled}
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 ${
isShuffled ? 'text-emerald-400' : 'text-neutral-400 hover:text-white'
}`}
>
{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" />
)}
<Shuffle size={18} strokeWidth={2} />
</button>
<div className="flex items-center gap-8">
<button
onClick={previous}
aria-label="Previous"
className="rounded-full p-1 text-neutral-300 transition-colors hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<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 duration-150 ease-out active:scale-90 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950"
>
{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="rounded-full p-1 text-neutral-300 transition-colors hover:text-white disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<SkipForward size={26} strokeWidth={2} fill="currentColor" />
</button>
</div>
<button
onClick={next}
disabled={!hasNext}
aria-label="Next"
className="rounded-full p-1 text-neutral-300 transition-colors hover:text-white disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
onClick={cycleRepeat}
aria-label={`Repeat: ${repeatMode}`}
aria-pressed={repeatMode !== 'off'}
className={`rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 ${
repeatMode !== 'off' ? 'text-emerald-400' : 'text-neutral-400 hover:text-white'
}`}
>
<SkipForward size={26} strokeWidth={2} fill="currentColor" />
<RepeatIcon size={18} strokeWidth={2} />
</button>
</div>
</div>
......
......@@ -6,6 +6,7 @@ import { usePlayer } from '../context/PlayerContext'
import { Button } from './ui/Button'
import { NowPlayingBar } from './NowPlayingBar'
import { FullPlayer } from './FullPlayer'
import { PlaybackErrorToast } from './PlaybackErrorToast'
const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/library', label: 'Library', icon: Library },
......@@ -74,6 +75,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
<NowPlayingBar />
<FullPlayer />
<PlaybackErrorToast />
{/* Bottom tab bar: mobile only, fixed, thumb-reachable. Hidden entirely at sm+ where
the top nav takes over instead. */}
......
import { useEffect } from 'react'
import { AlertCircle, X } from 'lucide-react'
import { usePlayer } from '../context/PlayerContext'
import { useMountTransition } from '../hooks/useMountTransition'
const AUTO_DISMISS_MS = 5000
/** Surfaces playback failures (bad stream, network error, blocked autoplay, ...) as a toast -
* without this, a failed play attempt just silently clears the current song with no feedback.
* Rendered globally in Layout so it's visible regardless of which page or player state the
* error happened in. */
export function PlaybackErrorToast() {
const { playbackError, dismissError } = usePlayer()
const { mounted, visible } = useMountTransition(!!playbackError, 200)
useEffect(() => {
if (!playbackError) return
const timeout = setTimeout(dismissError, AUTO_DISMISS_MS)
return () => clearTimeout(timeout)
}, [playbackError, dismissError])
if (!mounted || !playbackError) return null
return (
<div
role="alert"
aria-live="assertive"
className="fixed inset-x-4 z-40 flex justify-center"
// Sits just below the sticky header (h-14 = 56px) rather than at the very top of the
// viewport, which would otherwise overlap and hide the header entirely.
style={{ top: 'calc(env(safe-area-inset-top) + 3.75rem)' }}
>
<div
className={`flex w-full max-w-sm items-start gap-2.5 rounded-xl border border-red-900/50 bg-neutral-900 px-4 py-3 shadow-lg shadow-black/40 transition-all duration-200 ease-out motion-reduce:transition-none ${
visible ? 'translate-y-0 opacity-100' : '-translate-y-2 opacity-0'
}`}
>
<AlertCircle size={18} strokeWidth={2} className="mt-0.5 shrink-0 text-red-400" />
<p className="flex-1 text-sm text-neutral-200">{playbackError}</p>
<button
onClick={dismissError}
aria-label="Dismiss"
className="shrink-0 rounded-full p-0.5 text-neutral-500 transition-colors hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<X size={16} strokeWidth={2} />
</button>
</div>
</div>
)
}
......@@ -10,15 +10,37 @@ 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()
const {
currentSong,
queue,
hasNext,
hasPrevious,
isShuffled,
repeatMode,
playbackError,
toggle,
next,
previous,
toggleShuffle,
cycleRepeat,
dismissError,
} = usePlayer()
return (
<div>
<span data-testid="current">{currentSong?.title ?? 'none'}</span>
<span data-testid="queue-order">{queue.map((s) => s.title).join(',')}</span>
<span data-testid="has-next">{String(hasNext)}</span>
<span data-testid="has-previous">{String(hasPrevious)}</span>
<span data-testid="is-shuffled">{String(isShuffled)}</span>
<span data-testid="repeat-mode">{repeatMode}</span>
<span data-testid="playback-error">{playbackError ?? 'none'}</span>
<button onClick={() => toggle(SONG_A, QUEUE)}>Play A</button>
<button onClick={() => toggle(SONG_C, QUEUE)}>Play C</button>
<button onClick={next}>Next</button>
<button onClick={previous}>Previous</button>
<button onClick={toggleShuffle}>Toggle Shuffle</button>
<button onClick={cycleRepeat}>Cycle Repeat</button>
<button onClick={dismissError}>Dismiss Error</button>
</div>
)
}
......@@ -71,3 +93,95 @@ describe('PlayerContext queue navigation', () => {
expect(screen.getByTestId('has-previous')).toHaveTextContent('false')
})
})
describe('PlayerContext shuffle', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('reorders the upcoming queue but keeps the currently playing song in place, and restores order when turned off', 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('Toggle Shuffle'))
expect(screen.getByTestId('is-shuffled')).toHaveTextContent('true')
expect(screen.getByTestId('current')).toHaveTextContent('Song A')
// Current song moves to the front of the shuffled queue, so there's nothing "before" it.
expect(screen.getByTestId('has-previous')).toHaveTextContent('false')
const shuffledTitles = screen.getByTestId('queue-order').textContent?.split(',')
expect(shuffledTitles?.slice().sort()).toEqual(['Song A', 'Song B', 'Song C'])
await userEvent.click(screen.getByText('Toggle Shuffle'))
expect(screen.getByTestId('is-shuffled')).toHaveTextContent('false')
expect(screen.getByTestId('queue-order')).toHaveTextContent('Song A,Song B,Song C')
})
})
describe('PlayerContext repeat', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('cycles off -> all -> one -> off', async () => {
renderProbe()
expect(screen.getByTestId('repeat-mode')).toHaveTextContent('off')
await userEvent.click(screen.getByText('Cycle Repeat'))
expect(screen.getByTestId('repeat-mode')).toHaveTextContent('all')
await userEvent.click(screen.getByText('Cycle Repeat'))
expect(screen.getByTestId('repeat-mode')).toHaveTextContent('one')
await userEvent.click(screen.getByText('Cycle Repeat'))
expect(screen.getByTestId('repeat-mode')).toHaveTextContent('off')
})
it('wraps Next back to the start of the queue when repeat-all is on', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderProbe()
await userEvent.click(screen.getByText('Cycle Repeat')) // -> 'all'
await userEvent.click(screen.getByText('Play C')) // last song in the queue
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song C'))
expect(screen.getByTestId('has-next')).toHaveTextContent('true') // wraps, so still has a "next"
await userEvent.click(screen.getByText('Next'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
})
})
describe('PlayerContext playback errors', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('surfaces a message when the stream fails to load, and clears it on dismiss', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockRejectedValue(new Error('Stream unavailable'))
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('playback-error')).toHaveTextContent('Stream unavailable'))
expect(screen.getByTestId('current')).toHaveTextContent('none')
await userEvent.click(screen.getByText('Dismiss Error'))
expect(screen.getByTestId('playback-error')).toHaveTextContent('none')
})
it('clears a stale error once a subsequent play succeeds', async () => {
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl')
fetchStreamUrl.mockRejectedValueOnce(new Error('Stream unavailable'))
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('playback-error')).toHaveTextContent('Stream unavailable'))
fetchStreamUrl.mockResolvedValueOnce('blob:fake-url')
await userEvent.click(screen.getByText('Play C'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song C'))
expect(screen.getByTestId('playback-error')).toHaveTextContent('none')
})
})
......@@ -14,6 +14,8 @@ export interface PlayableSong {
lyrics?: string | null
}
export type RepeatMode = 'off' | 'all' | 'one'
interface PlayerContextValue {
currentSong: PlayableSong | null
queue: PlayableSong[]
......@@ -25,6 +27,11 @@ interface PlayerContextValue {
duration: number
hasNext: boolean
hasPrevious: boolean
isShuffled: boolean
repeatMode: RepeatMode
/** Set when the most recent play attempt failed (bad stream, network error, browser
* blocked autoplay, ...) - cleared automatically as soon as another track starts loading. */
playbackError: string | null
/** 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
......@@ -38,10 +45,18 @@ interface PlayerContextValue {
seek: (time: number) => void
expand: () => void
collapse: () => void
toggleShuffle: () => void
cycleRepeat: () => void
dismissError: () => void
}
const PlayerContext = createContext<PlayerContextValue | null>(null)
function extractErrorMessage(err: unknown): string {
if (err instanceof Error && err.message) return err.message
return "Couldn't play this track. Please try again."
}
export function PlayerProvider({ children }: { children: ReactNode }) {
const [currentSong, setCurrentSong] = useState<PlayableSong | null>(null)
const [queue, setQueue] = useState<PlayableSong[]>([])
......@@ -50,8 +65,14 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const [isExpanded, setIsExpanded] = useState(false)
const [progress, setProgress] = useState(0)
const [duration, setDuration] = useState(0)
const [isShuffled, setIsShuffled] = useState(false)
const [repeatMode, setRepeatMode] = useState<RepeatMode>('off')
const [playbackError, setPlaybackError] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const objectUrlRef = useRef<string | null>(null)
// The queue as originally handed to toggle(), before any shuffling - restored when shuffle
// is turned back off.
const originalQueueRef = useRef<PlayableSong[]>([])
// 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)
......@@ -66,6 +87,7 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
setIsPlaying(false)
setProgress(0)
setDuration(0)
setPlaybackError(null)
fetchStreamUrl(song.id)
.then((url) => {
......@@ -80,8 +102,11 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
if (requestId === requestIdRef.current) setIsPlaying(true)
})
})
.catch(() => {
if (requestId === requestIdRef.current) setCurrentSong(null)
.catch((err) => {
if (requestId === requestIdRef.current) {
setCurrentSong(null)
setPlaybackError(extractErrorMessage(err))
}
})
.finally(() => {
if (requestId === requestIdRef.current) setIsLoading(false)
......@@ -89,29 +114,47 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
}, [])
const currentIndex = currentSong ? queue.findIndex((s) => s.id === currentSong.id) : -1
const hasNext = currentIndex >= 0 && currentIndex < queue.length - 1
const hasNext = (currentIndex >= 0 && currentIndex < queue.length - 1) || (repeatMode === 'all' && queue.length > 1)
const hasPrevious = currentIndex > 0
const next = useCallback(() => {
if (currentIndex >= 0 && currentIndex < queue.length - 1) {
playSong(queue[currentIndex + 1])
} else if (repeatMode === 'all' && queue.length > 0) {
playSong(queue[0])
} else {
setIsPlaying(false)
}
}, [currentIndex, queue, playSong])
}, [currentIndex, queue, repeatMode, 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.
// Kept fresh via refs (rather than depending on them 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 or repeat mode changes.
const nextRef = useRef(next)
useEffect(() => {
nextRef.current = next
}, [next])
const repeatModeRef = useRef(repeatMode)
useEffect(() => {
repeatModeRef.current = repeatMode
}, [repeatMode])
useEffect(() => {
const audio = new Audio()
audioRef.current = audio
const onEnded = () => nextRef.current()
const onEnded = () => {
// "Repeat one" only affects what happens when a track finishes on its own - the Next
// button (nextRef) always advances regardless of repeat mode, matching Spotify.
if (repeatModeRef.current === 'one') {
audio.currentTime = 0
audio.play().then(
() => setIsPlaying(true),
() => setIsPlaying(false),
)
return
}
nextRef.current()
}
const onTimeUpdate = () => setProgress(audio.currentTime)
const onLoadedMetadata = () => setDuration(audio.duration || 0)
audio.addEventListener('ended', onEnded)
......@@ -152,6 +195,29 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const expand = useCallback(() => setIsExpanded(true), [])
const collapse = useCallback(() => setIsExpanded(false), [])
const dismissError = useCallback(() => setPlaybackError(null), [])
const cycleRepeat = useCallback(() => {
setRepeatMode((prev) => (prev === 'off' ? 'all' : prev === 'all' ? 'one' : 'off'))
}, [])
const toggleShuffle = useCallback(() => {
setIsShuffled((prev) => {
const turningOn = !prev
if (turningOn) {
// Shuffle everything except the song currently playing, which stays put - shuffle
// reorders what's still upcoming, not history.
const rest = originalQueueRef.current.filter((s) => s.id !== currentSong?.id)
for (let i = rest.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[rest[i], rest[j]] = [rest[j], rest[i]]
}
setQueue(currentSong ? [currentSong, ...rest] : rest)
} else {
setQueue(originalQueueRef.current)
}
return turningOn
})
}, [currentSong])
const toggle = useCallback(
(song: PlayableSong, songQueue?: PlayableSong[]) => {
......@@ -168,7 +234,10 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
return
}
setQueue(songQueue && songQueue.length > 0 ? songQueue : [song])
const newQueue = songQueue && songQueue.length > 0 ? songQueue : [song]
originalQueueRef.current = newQueue
setIsShuffled(false)
setQueue(newQueue)
playSong(song)
},
[currentSong, isPlaying, pause, playSong],
......@@ -186,6 +255,9 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
duration,
hasNext,
hasPrevious,
isShuffled,
repeatMode,
playbackError,
toggle,
pause,
next,
......@@ -193,6 +265,9 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
seek,
expand,
collapse,
toggleShuffle,
cycleRepeat,
dismissError,
}}
>
{children}
......
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