feat(web): player bar and full-screen player

- bar at the bottom of every page with cover, artists, controls, seek and time
- full-screen player in a dialog: big cover, bar-style seek control, up next, focus kept inside, Escape closes
- Space plays and pauses unless the key belongs to a field, a button or a link
- songs list row, seek control and time formatting
- jumpTo in the queue store for a click on an upcoming track
This commit is contained in:
tgiachi 2026-11-12 11:32:29 +01:00
commit 20856f2ec6
17 changed files with 926 additions and 3 deletions

View file

@ -1,8 +1,15 @@
import { useState } from 'react'
import { mediaUrl, useAccessToken } from '@/auth/session'
interface CoverProps {
albumId: number | null
/** Pixels. With `fluid` it is the largest size: the cover shrinks to fit a narrow screen. */
size: number
fluid?: boolean
}
/** The cover of an album, or concentric rings when there is none (or it cannot be loaded). */
export default function Cover({ albumId, size }: { albumId: number | null; size: number }) {
export default function Cover({ albumId, size, fluid = false }: CoverProps) {
useAccessToken() // the URL carries the token, so it has to follow a renewal
const src = albumId === null ? null : mediaUrl(`/albums/${albumId}/cover`)
// A failure is remembered for this URL only: a renewed token makes a new URL, which is tried again.
@ -10,7 +17,10 @@ export default function Cover({ albumId, size }: { albumId: number | null; size:
const showImage = src !== null && failed !== src
return (
<div style={{ width: size, height: size }} className="relative shrink-0 overflow-hidden rounded-md bg-muted">
<div
style={fluid ? { width: '100%', maxWidth: size, aspectRatio: '1 / 1' } : { width: size, height: size }}
className="relative shrink-0 overflow-hidden rounded-md bg-muted"
>
{showImage ? (
<img
src={src}

View file

@ -0,0 +1,55 @@
import { useTranslation } from 'react-i18next'
import { formatTime } from '@/lib/time'
import { cn } from '@/lib/utils'
const BARS = 64
interface ScrubberProps {
positionMs: number
durationMs: number
onSeek(ms: number): void
/** `line` is a thin bar; `bars` is a row of equal segments (a progress control, not a waveform). */
variant: 'line' | 'bars'
}
/** The seek control of the player: always a native range input, so the keyboard and screen readers work. */
export default function Scrubber({ positionMs, durationMs, onSeek, variant }: ScrubberProps) {
const { t } = useTranslation()
const disabled = !(durationMs > 0)
const max = disabled ? 1 : durationMs
const value = Math.min(Math.max(positionMs, 0), max)
const filled = (value / max) * BARS
const input = (
<input
type="range"
min={0}
max={max}
step={1}
value={value}
disabled={disabled}
aria-label={t('player.seek')}
aria-valuetext={t('player.seekValue', { position: formatTime(value), duration: formatTime(durationMs) })}
onChange={(e) => onSeek(Number(e.target.value))}
className={cn(
'cursor-pointer disabled:cursor-default',
variant === 'line' ? 'h-1 w-full accent-primary' : 'absolute inset-0 h-full w-full opacity-0',
)}
/>
)
if (variant === 'line') return input
return (
<div className="relative flex h-8 items-center gap-[3px] rounded-sm focus-within:outline-2 focus-within:outline-offset-2 focus-within:outline-ring">
{Array.from({ length: BARS }, (_, i) => (
<span
key={i}
aria-hidden="true"
className={cn('h-full min-w-px flex-1 rounded-[2px]', i + 0.5 <= filled ? 'bg-primary' : 'bg-input/50')}
/>
))}
{input}
</div>
)
}

View file

@ -0,0 +1,37 @@
import type { Track } from '@/api/catalog'
import { formatTime } from '@/lib/time'
import { cn } from '@/lib/utils'
interface TrackRowProps {
track: Track
/** Position in the list, shown when the track has no number of its own. */
index: number
onPlay(): void
/** The track that is playing now. */
active?: boolean
}
/** One song in a list: number, title, artists and length. Clicking it plays it. */
export default function TrackRow({ track, index, onPlay, active = false }: TrackRowProps) {
const artists = track.artists.map((a) => a.name).join(', ') || '—'
return (
<button
type="button"
onClick={onPlay}
aria-current={active ? 'true' : undefined}
className={cn(
'grid min-h-13 w-full grid-cols-[2.5rem_minmax(0,1fr)_4.5rem] items-center gap-3 rounded-lg px-4 text-left hover:bg-secondary',
active && 'bg-secondary',
)}
>
<span className={cn('tabular-nums', active ? 'font-bold text-primary' : 'text-muted-foreground')}>
{track.track_no > 0 ? track.track_no : index + 1}
</span>
<span className="min-w-0">
<span className={cn('block truncate font-semibold', active && 'text-primary')}>{track.title}</span>
<span className="block truncate text-sm text-muted-foreground">{artists}</span>
</span>
<span className="text-right text-sm tabular-nums text-muted-foreground">{formatTime(track.duration_ms)}</span>
</button>
)
}

View file

@ -0,0 +1,117 @@
import { X } from 'lucide-react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import Cover from '@/components/Cover'
import Scrubber from '@/components/Scrubber'
import TrackRow from '@/components/TrackRow'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
import { formatTime } from '@/lib/time'
import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import PlayerControls from './PlayerControls'
const UP_NEXT = 3
/** The full-screen player: a big cover, the controls and what comes next. */
export default function NowPlaying() {
const { t } = useTranslation()
const { open, setOpen } = useNowPlayingUi()
const player = usePlayer()
const track = currentTrack(player)
// Nothing left to show (the queue was emptied): close.
useEffect(() => {
if (open && !track) setOpen(false)
}, [open, track, setOpen])
const upNext = player.queue.slice(player.index + 1, player.index + 1 + UP_NEXT)
return (
<Dialog open={open && track !== null} onOpenChange={setOpen}>
<DialogContent
showCloseButton={false}
className="inset-0 h-dvh w-screen max-w-none translate-x-0 translate-y-0 content-start overflow-y-auto rounded-none bg-background p-6 sm:max-w-none md:p-12 motion-reduce:data-closed:animate-none motion-reduce:data-open:animate-none"
>
{track && (
<>
<Button
variant="ghost"
className="absolute top-4 right-4 size-11"
aria-label={t('player.close')}
onClick={() => setOpen(false)}
>
<X />
</Button>
<DialogDescription className="sr-only">{t('player.nowPlaying')}</DialogDescription>
<div className="mx-auto flex w-full max-w-5xl flex-wrap items-center justify-center gap-x-16 gap-y-8 pt-10">
<div className="flex min-w-0 flex-[1_1_320px] justify-center">
<Cover albumId={track.album?.id ?? null} size={520} fluid />
</div>
<div className="flex min-w-0 flex-[1_1_380px] flex-col gap-7">
<div className="flex flex-col gap-2">
<DialogTitle className="font-display text-4xl leading-tight font-semibold tracking-tight md:text-6xl">
{track.title}
</DialogTitle>
<p className="text-xl font-semibold">
{track.artists.length === 0
? '—'
: track.artists.map((a, i) => (
<span key={a.id}>
{i > 0 && ', '}
<Link to={`/artists/${a.id}`} onClick={() => setOpen(false)} className="hover:underline">
{a.name}
</Link>
</span>
))}
</p>
{track.album && (
<Link
to={`/albums/${track.album.id}`}
onClick={() => setOpen(false)}
className="text-muted-foreground hover:underline"
>
{track.album.title}
</Link>
)}
</div>
<div className="flex flex-col gap-1">
<Scrubber
positionMs={player.positionMs}
durationMs={track.duration_ms}
onSeek={player.seek}
variant="bars"
/>
<div className="flex justify-between text-sm text-muted-foreground tabular-nums">
<span>{formatTime(player.positionMs)}</span>
<span>{formatTime(track.duration_ms)}</span>
</div>
</div>
<PlayerControls large />
{upNext.length > 0 && (
<section aria-label={t('player.upNext')} className="flex flex-col gap-1 border-t pt-4">
<h2 className="pb-2 font-bold">{t('player.upNext')}</h2>
{upNext.map((next, k) => (
<TrackRow
key={`${next.id}-${k}`}
track={next}
index={player.index + 1 + k}
onPlay={() => player.jumpTo(player.index + 1 + k)}
/>
))}
</section>
)}
</div>
</div>
</>
)}
</DialogContent>
</Dialog>
)
}

View file

@ -0,0 +1,270 @@
import { act, fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import type { Track } from '@/api/catalog'
import { sessionStore } from '@/auth/session'
import Scrubber from '@/components/Scrubber'
import TrackRow from '@/components/TrackRow'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import PlayerBar from './PlayerBar'
function track(n: number, over: Partial<Track> = {}): Track {
return {
id: n,
title: `Song ${n}`,
duration_ms: 200_000,
track_no: n,
disc_no: 1,
album: { id: 10, title: 'Album' },
artists: [{ id: 5, name: 'Radiohead' }],
format: 'flac',
...over,
}
}
const [a, b, c, d, e] = [1, 2, 3, 4, 5].map((n) => track(n))
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
usePlayer.setState({
queue: [],
original: [],
index: 0,
playing: false,
positionMs: 0,
shuffle: false,
repeat: 'off',
seekMs: null,
seekId: 0,
playId: 0,
})
useNowPlayingUi.setState({ open: false })
})
function renderBar(extra?: React.ReactNode) {
return render(
<MemoryRouter>
<PlayerBar />
{extra}
</MemoryRouter>,
)
}
// --- Scrubber ----------------------------------------------------------------------------------
test.each(['line', 'bars'] as const)('the %s scrubber seeks to the position that was chosen', (variant) => {
const onSeek = vi.fn()
render(<Scrubber positionMs={0} durationMs={200_000} onSeek={onSeek} variant={variant} />)
fireEvent.change(screen.getByRole('slider', { name: 'Seek' }), { target: { value: '100000' } })
expect(onSeek).toHaveBeenCalledWith(100_000)
})
test('the scrubber says where it is in words', () => {
render(<Scrubber positionMs={147_000} durationMs={387_000} onSeek={() => {}} variant="line" />)
expect(screen.getByRole('slider', { name: 'Seek' })).toHaveAttribute('aria-valuetext', '2:27 of 6:27')
})
test('a scrubber with no known length cannot be moved', () => {
render(<Scrubber positionMs={0} durationMs={0} onSeek={() => {}} variant="line" />)
expect(screen.getByRole('slider', { name: 'Seek' })).toBeDisabled()
})
// --- TrackRow ----------------------------------------------------------------------------------
test('a row shows the track number, title, artists and length, and plays when clicked', async () => {
const onPlay = vi.fn()
render(
<MemoryRouter>
<TrackRow track={track(3, { track_no: 7, duration_ms: 147_000 })} index={0} onPlay={onPlay} />
</MemoryRouter>,
)
const row = screen.getByRole('button', { name: /Song 3/ })
expect(row).toHaveTextContent('7')
expect(row).toHaveTextContent('Radiohead')
expect(row).toHaveTextContent('2:27')
await userEvent.click(row)
expect(onPlay).toHaveBeenCalledTimes(1)
})
test('a row of a track with no number shows its position in the list', () => {
render(
<MemoryRouter>
<TrackRow track={track(3, { track_no: 0 })} index={4} onPlay={() => {}} />
</MemoryRouter>,
)
expect(screen.getByRole('button', { name: /Song 3/ })).toHaveTextContent('5')
})
test('a row of a track with no album and no artists still renders', () => {
render(
<MemoryRouter>
<TrackRow track={track(3, { album: null, artists: [] })} index={0} onPlay={() => {}} />
</MemoryRouter>,
)
expect(screen.getByRole('button', { name: /Song 3/ })).toHaveTextContent('—')
})
test('the row of the track that is playing is marked', () => {
render(
<MemoryRouter>
<TrackRow track={a} index={0} onPlay={() => {}} active />
</MemoryRouter>,
)
expect(screen.getByRole('button', { name: /Song 1/ })).toHaveAttribute('aria-current', 'true')
})
// --- PlayerBar ---------------------------------------------------------------------------------
test('with nothing in the queue the bar says so and its controls are disabled', () => {
renderBar()
expect(screen.getByText('Nothing playing')).toBeInTheDocument()
for (const name of ['Previous', 'Play', 'Next', 'Shuffle', 'Repeat: off']) {
expect(screen.getByRole('button', { name })).toBeDisabled()
}
expect(screen.getByRole('slider', { name: 'Seek' })).toBeDisabled()
})
test('the play button says Pause while playing and Play while paused', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Pause' }))
expect(usePlayer.getState().playing).toBe(false)
expect(screen.getByRole('button', { name: 'Play' })).toBeInTheDocument()
})
test('the bar shows the track, links to its artists, and the time', () => {
act(() => {
usePlayer.getState().playTracks([a])
usePlayer.getState().tick(147_000)
})
renderBar()
expect(screen.getByText('Song 1')).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Radiohead' })).toHaveAttribute('href', '/artists/5')
expect(screen.getByText('2:27')).toBeInTheDocument()
expect(screen.getByText('3:20')).toBeInTheDocument()
})
test('next and previous move through the queue', async () => {
act(() => usePlayer.getState().playTracks([a, b, c]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Next' }))
expect(usePlayer.getState().index).toBe(1)
await userEvent.click(screen.getByRole('button', { name: 'Previous' }))
expect(usePlayer.getState().index).toBe(0)
})
test('dragging the scrubber to the middle seeks to half of the track', () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
fireEvent.change(screen.getByRole('slider', { name: 'Seek' }), { target: { value: '100000' } })
expect(usePlayer.getState().positionMs).toBe(100_000)
expect(usePlayer.getState().seekMs).toBe(100_000)
})
test('shuffle is a toggle and repeat goes through off, all and one', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const shuffle = screen.getByRole('button', { name: 'Shuffle' })
expect(shuffle).toHaveAttribute('aria-pressed', 'false')
await userEvent.click(shuffle)
expect(shuffle).toHaveAttribute('aria-pressed', 'true')
await userEvent.click(screen.getByRole('button', { name: 'Repeat: off' }))
await userEvent.click(screen.getByRole('button', { name: 'Repeat: all' }))
expect(screen.getByRole('button', { name: 'Repeat: one' })).toBeInTheDocument()
})
test('a track with no album and no artists plays without breaking the bar', () => {
act(() => usePlayer.getState().playTracks([track(9, { album: null, artists: [] })]))
expect(() => renderBar()).not.toThrow()
expect(screen.getByText('Song 9')).toBeInTheDocument()
})
test('Space plays and pauses, except while typing in a field', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar(<input aria-label="Search box" />)
await userEvent.click(screen.getByLabelText('Search box'))
await userEvent.keyboard(' ')
expect(usePlayer.getState().playing).toBe(true)
await userEvent.click(document.body)
await userEvent.keyboard(' ')
expect(usePlayer.getState().playing).toBe(false)
await userEvent.keyboard(' ')
expect(usePlayer.getState().playing).toBe(true)
})
// --- Full-screen player ------------------------------------------------------------------------
async function openNowPlaying() {
const opener = screen.getByRole('button', { name: 'Open the full-screen player' })
await userEvent.click(opener)
return { opener, dialog: await screen.findByRole('dialog') }
}
test('the full-screen player opens on the current track and Escape closes it and gives focus back', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const { opener, dialog } = await openNowPlaying()
expect(within(dialog).getByRole('heading', { name: 'Song 1' })).toBeInTheDocument()
expect(within(dialog).getByRole('link', { name: 'Radiohead' })).toBeInTheDocument()
expect(within(dialog).getByRole('link', { name: 'Album' })).toHaveAttribute('href', '/albums/10')
await userEvent.keyboard('{Escape}')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(opener).toHaveFocus()
})
test('the full-screen player has a close button', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
const { dialog } = await openNowPlaying()
await userEvent.click(within(dialog).getByRole('button', { name: 'Close' }))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
test('the full-screen player controls the same player', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const { dialog } = await openNowPlaying()
await userEvent.click(within(dialog).getByRole('button', { name: 'Next' }))
expect(usePlayer.getState().index).toBe(1)
expect(within(dialog).getByRole('heading', { name: 'Song 2' })).toBeInTheDocument()
})
test('Up next shows the next three tracks and a click plays one of them', async () => {
act(() => usePlayer.getState().playTracks([a, b, c, d, e]))
renderBar()
const { dialog } = await openNowPlaying()
const upNext = within(dialog).getByRole('region', { name: 'Up next' })
expect(within(upNext).getAllByRole('button')).toHaveLength(3)
expect(within(upNext).queryByText('Song 5')).not.toBeInTheDocument()
await userEvent.click(within(upNext).getByRole('button', { name: /Song 3/ }))
expect(usePlayer.getState().index).toBe(2)
})
test('a track with no album and no artists opens in the full-screen player', async () => {
act(() => usePlayer.getState().playTracks([track(9, { album: null, artists: [] })]))
renderBar()
const { dialog } = await openNowPlaying()
expect(within(dialog).getByRole('heading', { name: 'Song 9' })).toBeInTheDocument()
})
test('Tab stays inside the full-screen player', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const { dialog } = await openNowPlaying()
const outside = [screen.queryByRole('navigation'), document.body.querySelector('footer')]
for (let i = 0; i < 25; i++) {
await userEvent.tab()
// The dialog hands focus on through invisible guard elements; once it has done so, focus is inside it.
await vi.waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement))
for (const el of outside) if (el) expect(el.contains(document.activeElement)).toBe(false)
}
})

View file

@ -0,0 +1,102 @@
import { ListMusic } from 'lucide-react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import Cover from '@/components/Cover'
import Scrubber from '@/components/Scrubber'
import { Button } from '@/components/ui/button'
import { formatTime } from '@/lib/time'
import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import NowPlaying from './NowPlaying'
import PlayerControls from './PlayerControls'
/** Space plays and pauses, unless the keypress belongs to a field, a button or a link. */
function usePlayPauseKey() {
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.code !== 'Space' || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return
const target = e.target instanceof HTMLElement ? e.target : null
if (target?.closest('input, textarea, select, button, a, summary, [contenteditable="true"]')) return
e.preventDefault()
usePlayer.getState().togglePlay()
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [])
}
/** The bar at the bottom of every page: what is playing, the controls and the position. */
export default function PlayerBar() {
const { t } = useTranslation()
const player = usePlayer()
const setOpen = useNowPlayingUi((s) => s.setOpen)
const track = currentTrack(player)
usePlayPauseKey()
return (
<footer
aria-label={t('player.label')}
className="sticky bottom-0 z-10 flex flex-wrap items-center gap-x-6 gap-y-3 bg-card px-5 py-3 text-card-foreground"
>
<div className="flex min-w-0 flex-[1_1_240px] items-center gap-3">
{track ? (
<>
<button type="button" aria-label={t('player.open')} onClick={() => setOpen(true)} className="rounded-md">
<Cover albumId={track.album?.id ?? null} size={56} />
</button>
<div className="flex min-w-0 flex-col">
<button type="button" onClick={() => setOpen(true)} className="truncate text-left font-bold">
{track.title}
</button>
<span className="truncate text-sm text-muted-foreground">
{track.artists.length === 0
? '—'
: track.artists.map((a, i) => (
<span key={a.id}>
{i > 0 && ', '}
<Link to={`/artists/${a.id}`} className="hover:underline">
{a.name}
</Link>
</span>
))}
</span>
</div>
</>
) : (
<span className="text-muted-foreground">{t('player.nothingPlaying')}</span>
)}
</div>
<div className="flex flex-[2_1_400px] flex-col items-center gap-1">
<PlayerControls />
<div className="flex w-full max-w-xl items-center gap-3 text-xs text-muted-foreground tabular-nums">
<span>{formatTime(track ? player.positionMs : 0)}</span>
<div className="flex-1">
<Scrubber
positionMs={player.positionMs}
durationMs={track?.duration_ms ?? 0}
onSeek={player.seek}
variant="line"
/>
</div>
<span>{formatTime(track?.duration_ms ?? 0)}</span>
</div>
</div>
<div className="flex flex-[1_1_120px] justify-end">
<Button
variant="ghost"
className="size-11 text-muted-foreground"
aria-label={t('player.queue')}
disabled={!track}
onClick={() => setOpen(true)}
>
<ListMusic />
</Button>
</div>
<NowPlaying />
</footer>
)
}

View file

@ -0,0 +1,52 @@
import { Pause, Play, Repeat, Repeat1, Shuffle, SkipBack, SkipForward } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { currentTrack, usePlayer } from '@/player/store'
/** Shuffle, previous, play/pause, next and repeat. Used by the player bar and the full-screen player. */
export default function PlayerControls({ large = false }: { large?: boolean }) {
const { t } = useTranslation()
const player = usePlayer()
const none = currentTrack(player) === null
const small = large ? 'size-12' : 'size-11'
const repeatLabel = { off: 'player.repeatOff', all: 'player.repeatAll', one: 'player.repeatOne' }[player.repeat]
return (
<div className="flex items-center gap-1 sm:gap-3">
<Button
variant="ghost"
className={cn(small, player.shuffle ? 'text-primary' : 'text-muted-foreground')}
aria-label={t('player.shuffle')}
aria-pressed={player.shuffle}
disabled={none}
onClick={player.toggleShuffle}
>
<Shuffle />
</Button>
<Button variant="ghost" className={small} aria-label={t('player.previous')} disabled={none} onClick={player.prev}>
<SkipBack />
</Button>
<Button
className={cn(large ? 'size-16' : 'size-11', 'rounded-full')}
aria-label={player.playing ? t('player.pause') : t('player.play')}
disabled={none}
onClick={player.togglePlay}
>
{player.playing ? <Pause /> : <Play />}
</Button>
<Button variant="ghost" className={small} aria-label={t('player.next')} disabled={none} onClick={player.next}>
<SkipForward />
</Button>
<Button
variant="ghost"
className={cn(small, player.repeat === 'off' ? 'text-muted-foreground' : 'text-primary')}
aria-label={t(repeatLabel)}
disabled={none}
onClick={player.cycleRepeat}
>
{player.repeat === 'one' ? <Repeat1 /> : <Repeat />}
</Button>
</div>
)
}

View file

@ -1,8 +1,11 @@
import { Outlet } from 'react-router-dom'
import { usePlayerEngine } from '@/player/usePlayer'
import PlayerBar from './PlayerBar'
import Sidebar from './Sidebar'
/** The frame of the app: the sidebar, the page, and (from the player task on) the player bar. */
/** The frame of the app: the sidebar, the page, and the player bar. */
export default function Shell() {
usePlayerEngine()
return (
<div className="flex min-h-screen flex-col bg-background text-foreground">
<div className="flex flex-1 flex-wrap gap-2 p-2">
@ -11,6 +14,9 @@ export default function Shell() {
<Outlet />
</main>
</div>
<div className="px-2 pb-2">
<PlayerBar />
</div>
</div>
)
}

View file

@ -0,0 +1,158 @@
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View file

@ -19,6 +19,25 @@
"notFound": "This page does not exist",
"backHome": "Back to Home"
},
"player": {
"label": "Player",
"play": "Play",
"pause": "Pause",
"next": "Next",
"previous": "Previous",
"shuffle": "Shuffle",
"repeatOff": "Repeat: off",
"repeatAll": "Repeat: all",
"repeatOne": "Repeat: one",
"seek": "Seek",
"seekValue": "{{position}} of {{duration}}",
"nothingPlaying": "Nothing playing",
"open": "Open the full-screen player",
"close": "Close",
"upNext": "Up next",
"queue": "Queue",
"nowPlaying": "Now playing"
},
"theme": {
"sonda": "Sonda",
"tokyo-night": "Tokyo Night",

View file

@ -19,6 +19,25 @@
"notFound": "Questa pagina non esiste",
"backHome": "Torna alla Home"
},
"player": {
"label": "Player",
"play": "Riproduci",
"pause": "Pausa",
"next": "Avanti",
"previous": "Indietro",
"shuffle": "Casuale",
"repeatOff": "Ripeti: no",
"repeatAll": "Ripeti: tutto",
"repeatOne": "Ripeti: un brano",
"seek": "Posizione",
"seekValue": "{{position}} di {{duration}}",
"nothingPlaying": "Niente in riproduzione",
"open": "Apri il player a schermo intero",
"close": "Chiudi",
"upNext": "Prossimi brani",
"queue": "Coda",
"nowPlaying": "In riproduzione"
},
"theme": {
"sonda": "Sonda",
"tokyo-night": "Tokyo Night",

22
web/src/lib/time.test.ts Normal file
View file

@ -0,0 +1,22 @@
import { expect, test } from 'vitest'
import { formatTime } from './time'
test.each([
[0, '0:00'],
[999, '0:00'],
[1000, '0:01'],
[59_999, '0:59'],
[147_000, '2:27'],
[387_000, '6:27'],
[3_599_000, '59:59'],
[3_600_000, '1:00:00'],
[4_000_000, '1:06:40'],
])('%i ms is written %s', (ms, text) => {
expect(formatTime(ms)).toBe(text)
})
test('a negative or unknown time is written as zero', () => {
expect(formatTime(-5)).toBe('0:00')
expect(formatTime(Number.NaN)).toBe('0:00')
expect(formatTime(Number.POSITIVE_INFINITY)).toBe('0:00')
})

9
web/src/lib/time.ts Normal file
View file

@ -0,0 +1,9 @@
/** Minutes and seconds ("2:27"), with hours when there are any ("1:06:40"). Anything that is not a time is "0:00". */
export function formatTime(ms: number): string {
if (!Number.isFinite(ms) || ms < 0) return '0:00'
const total = Math.floor(ms / 1000)
const hours = Math.floor(total / 3600)
const minutes = Math.floor((total % 3600) / 60)
const seconds = String(total % 60).padStart(2, '0')
return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${seconds}` : `${minutes}:${seconds}`
}

View file

@ -239,6 +239,31 @@ test('removing a position that does not exist changes nothing', () => {
expect(ids()).toEqual([1, 2, 3, 4, 5])
})
test('jumpTo plays the track at that position from the start', () => {
usePlayer.getState().playTracks(all, 0)
usePlayer.getState().togglePlay() // paused
usePlayer.getState().tick(7000)
usePlayer.getState().jumpTo(3)
expect(current()).toBe(t4)
expect(usePlayer.getState().playing).toBe(true)
expect(usePlayer.getState().positionMs).toBe(0)
})
test('jumpTo the track already playing starts it over', () => {
usePlayer.getState().playTracks(all, 1)
const before = usePlayer.getState().seekId
usePlayer.getState().jumpTo(1)
expect(current()).toBe(t2)
expect(usePlayer.getState().seekId).toBe(before + 1)
})
test('jumpTo a position that does not exist changes nothing', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().jumpTo(9)
usePlayer.getState().jumpTo(-1)
expect(current()).toBe(t2)
})
test('turning shuffle on reorders only the tracks after the current one', () => {
usePlayer.getState().playTracks(all, 1)
usePlayer.getState().toggleShuffle()

View file

@ -30,6 +30,8 @@ export interface PlayerState {
removeAt(i: number): void
toggleShuffle(): void
cycleRepeat(): void
/** Plays the track at this position of the queue from the start. */
jumpTo(i: number): void
}
let random: () => number = Math.random
@ -179,4 +181,12 @@ export const usePlayer = create<PlayerState>()((set, get) => ({
cycleRepeat() {
set((s) => ({ repeat: s.repeat === 'off' ? 'all' : s.repeat === 'all' ? 'one' : 'off' }))
},
jumpTo(i) {
set((s) => {
if (i < 0 || i >= s.queue.length) return s
if (i === s.index) return { playing: true, ...restart(s) }
return { index: i, playing: true, positionMs: 0 }
})
},
}))

7
web/src/player/ui.ts Normal file
View file

@ -0,0 +1,7 @@
import { create } from 'zustand'
/** Whether the full-screen player is open. */
export const useNowPlayingUi = create<{ open: boolean; setOpen(open: boolean): void }>()((set) => ({
open: false,
setOpen: (open) => set({ open }),
}))

View file

@ -2,6 +2,11 @@ import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach, vi } from 'vitest'
// jsdom has no media playback: its play, pause and load only print "not implemented".
Object.defineProperty(window.HTMLMediaElement.prototype, 'play', { configurable: true, value: () => Promise.resolve() })
Object.defineProperty(window.HTMLMediaElement.prototype, 'pause', { configurable: true, value: () => {} })
Object.defineProperty(window.HTMLMediaElement.prototype, 'load', { configurable: true, value: () => {} })
afterEach(() => {
cleanup()
vi.unstubAllGlobals()