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
This diff is collapsed.
......@@ -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