Commit 867aa9c8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Smooth player transitions, better lyrics view, accessibility pass

- FullPlayer and NowPlayingBar now animate in/out (slide + fade) via
  a shared useMountTransition hook instead of snapping in/out, with
  motion-reduce fallbacks for users who've asked for less motion.
- Lyrics moved from a small icon toggle into a proper Cover/Lyrics
  tab switcher (real tablist/tab/tabpanel roles, arrow-key navigation,
  crossfade between panels), with larger type, a scroll fade mask, and
  a real empty state for tracks with no lyrics.
- FullPlayer is now a proper dialog: aria-modal, focus moves to it on
  open and back to the control that opened it on close, Escape closes
  it, and background scroll is locked while it's open.
- Seek bar reskinned as a real <input type="range"> (keeps native
  keyboard/pointer/AT support) with a progress-fill gradient and a
  hover-revealed thumb, plus aria-valuetext with formatted times.
- Added a visible focus-visible ring to the shared Button component
  and to the player's own raw buttons (WCAG 2.4.7).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 54d3c423
Pipeline #1045 failed with stage
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 '../context/PlayerContext'
import { NowPlayingBar } from './NowPlayingBar'
import { FullPlayer } from './FullPlayer'
import * as streamApi from '../api/stream'
const SONG: PlayableSong = {
id: 1,
title: 'Test Song',
artist: 'Test Artist',
album: 'Test Album',
lyrics: 'Line one\nLine two',
}
function Probe() {
const { toggle } = usePlayer()
return <button onClick={() => toggle(SONG)}>Start Playback</button>
}
function renderPlayer() {
return render(
<PlayerProvider>
<Probe />
<NowPlayingBar />
<FullPlayer />
</PlayerProvider>,
)
}
describe('FullPlayer', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('opens from the mini player, focuses the minimize button, and shows lyrics on the Lyrics tab', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderPlayer()
await userEvent.click(screen.getByText('Start Playback'))
const openButton = await screen.findByRole('button', { name: /Open player/ })
await userEvent.click(openButton)
await screen.findByRole('dialog', { name: /Now playing: Test Song by Test Artist/ })
await waitFor(() => expect(screen.getByRole('button', { name: 'Minimize player' })).toHaveFocus())
expect(screen.getByRole('tab', { name: /Cover/ })).toHaveAttribute('aria-selected', 'true')
await userEvent.click(screen.getByRole('tab', { name: /Lyrics/ }))
expect(screen.getByRole('tab', { name: /Lyrics/ })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByText(/Line one/)).toBeInTheDocument()
})
it('shows a clear empty state when a track has no lyrics', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
function ProbeNoLyrics() {
const { toggle } = usePlayer()
return <button onClick={() => toggle({ ...SONG, lyrics: null })}>Start Playback</button>
}
render(
<PlayerProvider>
<ProbeNoLyrics />
<NowPlayingBar />
<FullPlayer />
</PlayerProvider>,
)
await userEvent.click(screen.getByText('Start Playback'))
const openButton = await screen.findByRole('button', { name: /Open player/ })
await userEvent.click(openButton)
await waitFor(() => expect(screen.getByRole('button', { name: 'Minimize player' })).toHaveFocus())
await userEvent.click(screen.getByRole('tab', { name: /Lyrics/ }))
expect(screen.getByText('No lyrics available for this track.')).toBeInTheDocument()
})
it('closes on Escape and returns focus to the control that opened it', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderPlayer()
await userEvent.click(screen.getByText('Start Playback'))
const openButton = await screen.findByRole('button', { name: /Open player/ })
await userEvent.click(openButton)
await waitFor(() => expect(screen.getByRole('button', { name: 'Minimize player' })).toHaveFocus())
await userEvent.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() => expect(openButton).toHaveFocus())
})
})
import { useState } from 'react'
import { ChevronDown, ListMusic, Music2, Pause, Play, SkipBack, SkipForward } from 'lucide-react'
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 { EmptyState } from './ui/EmptyState'
import { useMountTransition } from '../hooks/useMountTransition'
const ANIMATION_MS = 300
function formatTime(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return '0:00'
......@@ -9,9 +13,17 @@ function formatTime(seconds: number): string {
return `${mins}:${secs.toString().padStart(2, '0')}`
}
const TABS = [
{ id: 'cover', label: 'Cover' },
{ id: 'lyrics', label: 'Lyrics' },
] as const
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 lyrics toggle. Renders nothing when collapsed or when nothing is loaded. */
* 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. */
export function FullPlayer() {
const {
currentSong,
......@@ -27,58 +39,156 @@ export function FullPlayer() {
seek,
collapse,
} = usePlayer()
const [showLyrics, setShowLyrics] = useState(false)
const [activeTab, setActiveTab] = useState<TabId>('cover')
const { mounted, visible } = useMountTransition(isExpanded && !!currentSong, ANIMATION_MS)
const collapseButtonRef = useRef<HTMLButtonElement>(null)
const tabRefs = useRef<(HTMLButtonElement | null)[]>([])
useEffect(() => {
if (visible) collapseButtonRef.current?.focus()
}, [visible])
useEffect(() => {
if (!visible) return
function onKeyDown(e: globalThis.KeyboardEvent) {
if (e.key === 'Escape') collapse()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [visible, collapse])
useEffect(() => {
if (!visible) return
const previousOverflow = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = previousOverflow
}
}, [visible])
if (!mounted || !currentSong) return null
if (!isExpanded || !currentSong) return null
function focusTab(index: number) {
const wrapped = (index + TABS.length) % TABS.length
setActiveTab(TABS[wrapped].id)
tabRefs.current[wrapped]?.focus()
}
function onTabKeyDown(e: KeyboardEvent<HTMLButtonElement>, index: number) {
if (e.key === 'ArrowRight') {
e.preventDefault()
focusTab(index + 1)
} else if (e.key === 'ArrowLeft') {
e.preventDefault()
focusTab(index - 1)
}
}
const pct = duration > 0 ? Math.min(100, (progress / duration) * 100) : 0
return (
<div className="fixed inset-0 z-30 flex flex-col bg-neutral-950 text-white">
<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 ${
visible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
}`}
>
<div
className="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"
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"
>
<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'
<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"
>
{TABS.map((tab, index) => {
const active = activeTab === tab.id
return (
<button
key={tab.id}
ref={(el) => {
tabRefs.current[index] = el
}}
role="tab"
id={`player-tab-${tab.id}`}
aria-selected={active}
aria-controls={`player-panel-${tab.id}`}
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 ${
active ? 'bg-neutral-100 text-neutral-950' : 'text-neutral-400 hover:text-white'
}`}
>
{tab.id === 'lyrics' && <ScrollText 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
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 ${
activeTab === 'cover' ? 'opacity-100' : 'pointer-events-none opacity-0'
}`}
>
<ListMusic size={19} strokeWidth={2} />
</button>
</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 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
id="player-panel-lyrics"
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 ${
activeTab === 'lyrics' ? 'opacity-100' : 'pointer-events-none opacity-0'
}`}
style={{
maskImage: 'linear-gradient(to bottom, transparent, black 24px, black calc(100% - 24px), transparent)',
WebkitMaskImage:
'linear-gradient(to bottom, transparent, black 24px, black calc(100% - 24px), transparent)',
}}
>
{currentSong.lyrics ? (
<p className="whitespace-pre-wrap text-[17px] leading-loose text-neutral-200">{currentSong.lyrics}</p>
) : (
<EmptyState icon={ScrollText} message="No lyrics available for this track." />
)}
</div>
</div>
<div
......@@ -102,7 +212,9 @@ export function FullPlayer() {
onChange={(e) => seek(Number(e.target.value))}
disabled={!duration}
aria-label="Seek"
className="w-full accent-emerald-400 disabled:opacity-40"
aria-valuetext={`${formatTime(progress)} of ${formatTime(duration)}`}
className="seek-range w-full disabled:opacity-40"
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>
......@@ -113,7 +225,7 @@ export function FullPlayer() {
<button
onClick={previous}
aria-label="Previous"
className="text-neutral-300 transition-colors hover:text-white"
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>
......@@ -121,7 +233,7 @@ export function FullPlayer() {
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"
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" />
......@@ -135,7 +247,7 @@ export function FullPlayer() {
onClick={next}
disabled={!hasNext}
aria-label="Next"
className="text-neutral-300 transition-colors hover:text-white disabled:opacity-30"
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>
......
......@@ -66,7 +66,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
</header>
<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'}`}
className={`mx-auto max-w-2xl px-4 py-6 transition-[padding] duration-300 ease-out motion-reduce:transition-none 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}
......
import { useEffect, useRef } from 'react'
import { Music2, Pause, Play } from 'lucide-react'
import { usePlayer } from '../context/PlayerContext'
import { useMountTransition } from '../hooks/useMountTransition'
/** 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, expand } = usePlayer()
const { currentSong, isPlaying, isLoading, isExpanded, toggle, expand } = usePlayer()
const { mounted, visible } = useMountTransition(!!currentSong, 300)
const openButtonRef = useRef<HTMLButtonElement>(null)
const wasExpandedRef = useRef(isExpanded)
if (!currentSong) return null
// FullPlayer moves focus to its own close button on open; when it closes again, hand
// keyboard focus back to the control that opened it instead of dropping it to <body>.
useEffect(() => {
if (wasExpandedRef.current && !isExpanded) {
openButtonRef.current?.focus()
}
wasExpandedRef.current = isExpanded
}, [isExpanded])
if (!mounted || !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"
className={`fixed inset-x-0 bottom-14 z-20 border-t border-neutral-800 bg-neutral-900/95 backdrop-blur transition-all duration-300 ease-out motion-reduce:transition-none sm:bottom-0 ${
visible ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-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">
{/* Separate <button> from the play/pause control below - two sibling buttons rather
than nesting one inside the other, which isn't valid HTML. */}
<button
ref={openButtonRef}
onClick={expand}
aria-label={`Open player - ${currentSong.title}`}
className="flex min-w-0 flex-1 items-center gap-3 text-left"
className="flex min-w-0 flex-1 items-center gap-3 rounded-lg text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
{currentSong.coverart ? (
<img src={currentSong.coverart} alt="" className="h-10 w-10 shrink-0 rounded-md object-cover" />
......@@ -38,7 +55,7 @@ export function NowPlayingBar() {
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"
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white 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"
>
{isLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
......
......@@ -27,7 +27,7 @@ export const Button = forwardRef<HTMLButtonElement, Props>(function Button(
return (
<button
ref={ref}
className={`inline-flex items-center justify-center gap-1.5 rounded-full font-medium transition-all duration-150 ease-out active:scale-[0.96] disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100 ${VARIANT_CLASSES[variant]} ${SIZE_CLASSES[size]} ${className}`}
className={`inline-flex items-center justify-center gap-1.5 rounded-full font-medium transition-all duration-150 ease-out active:scale-[0.96] disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950 ${VARIANT_CLASSES[variant]} ${SIZE_CLASSES[size]} ${className}`}
{...props}
/>
)
......
import { useEffect, useState } from 'react'
/** Keeps a component mounted long enough to play its exit transition instead of vanishing
* instantly. Flip `active` on/off and drive enter/exit CSS classes off `visible`; `mounted`
* gates whether to render at all - it stays true for `durationMs` after `active` goes false so
* the exit transition has time to finish before the DOM node (and its focusable children) are
* actually removed. */
export function useMountTransition(active: boolean, durationMs: number) {
const [mounted, setMounted] = useState(active)
const [visible, setVisible] = useState(false)
useEffect(() => {
if (active) {
setMounted(true)
// Mounting with the "hidden" classes already applied, then flipping to visible one
// frame later, is what makes the enter transition actually animate instead of
// snapping straight to its end state.
const raf = requestAnimationFrame(() => setVisible(true))
return () => cancelAnimationFrame(raf)
}
setVisible(false)
const timeout = setTimeout(() => setMounted(false), durationMs)
return () => clearTimeout(timeout)
}, [active, durationMs])
return { mounted, visible }
}
......@@ -23,3 +23,64 @@
transform: translateX(300%);
}
}
/* Reskin the native range input used for the player's seek bar - kept as a real
<input type="range"> rather than a custom div-based slider so keyboard stepping, pointer
dragging, and screen reader announcements all come for free from the platform. The filled
portion is painted via an inline background gradient (see FullPlayer.tsx); this stylesheet
only strips the default track chrome and styles the thumb. */
.seek-range {
-webkit-appearance: none;
appearance: none;
height: 4px;
border-radius: 9999px;
background-color: transparent;
}
.seek-range::-webkit-slider-runnable-track {
height: 4px;
border-radius: 9999px;
}
.seek-range::-moz-range-track {
height: 4px;
border-radius: 9999px;
background: transparent;
}
.seek-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 13px;
height: 13px;
margin-top: -4.5px;
border-radius: 9999px;
background: white;
opacity: 0;
transition: opacity 150ms ease-out;
}
.seek-range::-moz-range-thumb {
width: 13px;
height: 13px;
border: none;
border-radius: 9999px;
background: white;
opacity: 0;
transition: opacity 150ms ease-out;
}
.seek-range:hover::-webkit-slider-thumb,
.seek-range:focus-visible::-webkit-slider-thumb {
opacity: 1;
}
.seek-range:hover::-moz-range-thumb,
.seek-range:focus-visible::-moz-range-thumb {
opacity: 1;
}
.seek-range:focus-visible {
outline: 2px solid #34d399;
outline-offset: 4px;
border-radius: 9999px;
}
.seek-range:disabled::-webkit-slider-thumb {
display: none;
}
.seek-range:disabled::-moz-range-thumb {
display: none;
}
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