sonda/web/src/components/layout/Player.test.tsx
tgiachi 7243fe7a04 feat: the seek bar shows the waveform of a friend's track
A friend's server works out the peaks of a track in a shared library and gives
them to a signed friend (GET /peer/tracks/{id}/peaks). This server asks for them
and passes them on to the listener after checking them: 1 to 1000 levels from 0
to 255, as many as the count says (GET /friends/{friend}/tracks/{id}/peaks). The
player uses it for a friend's track, so its bar is no longer flat.
2026-11-13 19:46:37 +01:00

449 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Profiler } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor, 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 TrackList from '@/components/TrackList'
import TrackRow from '@/components/TrackRow'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import { fakeFullscreen } from '@/test/fullscreen'
import { mockFetch } from '@/test/mockFetch'
import PlayerBar from './PlayerBar'
import PlayerControls from './PlayerControls'
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, email: 'tom@example.org', 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 })
})
let calls: { key: string }[] = []
function renderBar(extra?: React.ReactNode) {
calls = mockFetch({
'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }),
...Object.fromEntries([1, 2, 3, 4, 5].map((n) => [`GET /api/v1/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])),
...Object.fromEntries([1, 2, 3, 4, 5].map((n) => [`GET /api/v1/friends/3/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])),
}).calls
return render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<MemoryRouter>
<PlayerBar />
{extra}
</MemoryRouter>
</QueryClientProvider>,
)
}
// --- Scrubber ----------------------------------------------------------------------------------
test.each(['bar', 'big'] as const)('the %s scrubber seeks to the position that was chosen', (size) => {
const onSeek = vi.fn()
render(<Scrubber positionMs={0} durationMs={200_000} onSeek={onSeek} size={size} />)
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={() => {}} size="bar" />)
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={() => {}} size="bar" />)
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('the bar and the full-screen player both have a button for browser full screen, where the browser has one', async () => {
const env = fakeFullscreen()
try {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
expect(screen.getByRole('button', { name: 'Enter full screen' })).toBeInTheDocument()
const { dialog } = await openNowPlaying()
expect(within(dialog).getByRole('button', { name: 'Enter full screen' })).toBeInTheDocument()
} finally {
env.restore()
}
})
test('the bar and the full-screen player both have a volume control, and they move the same volume', async () => {
usePlayer.setState({ volume: 0.5, muted: false })
act(() => usePlayer.getState().playTracks([a]))
renderBar()
expect(within(screen.getByRole('contentinfo')).getByRole('slider', { name: 'Volume' })).toHaveValue('50')
expect(screen.getByRole('button', { name: 'Mute' })).toBeInTheDocument()
const { dialog } = await openNowPlaying()
fireEvent.change(within(dialog).getByRole('slider', { name: 'Volume' }), { target: { value: '20' } })
expect(usePlayer.getState().volume).toBe(0.2)
await userEvent.click(within(dialog).getByRole('button', { name: 'Mute' }))
expect(usePlayer.getState().muted).toBe(true)
})
test('without the Fullscreen API neither the bar nor the full-screen player shows the button', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
const { dialog } = await openNowPlaying()
expect(screen.queryByRole('button', { name: 'Enter full screen' })).not.toBeInTheDocument()
expect(within(dialog).queryByRole('button', { name: 'Enter full screen' })).not.toBeInTheDocument()
})
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)
}
})
test('the controls and the title do not render again when only the position moves', () => {
usePlayer.getState().playTracks([a, b], 0)
let commits = 0
render(
<MemoryRouter>
<Profiler id="controls" onRender={() => commits++}>
<PlayerControls />
</Profiler>
</MemoryRouter>,
)
const before = commits
act(() => usePlayer.getState().tick(5_000))
act(() => usePlayer.getState().tick(6_000))
expect(commits).toBe(before)
})
test('the seek bar of the player bar is 44 pixels high to take a thumb', () => {
render(<Scrubber positionMs={0} durationMs={1000} onSeek={() => {}} size="bar" />)
expect(screen.getByRole('slider').parentElement).toHaveClass('h-11')
})
const theirs = (n: number) => ({ ...track(n), friend: 3, album: { id: 10, title: 'Their Album' }, artists: [{ id: 5, name: 'Their Band' }] })
test('the bar shows a friend’s track with its cover and links to the music of the friend, not to a local page', () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
const { container } = renderBar()
expect(container.querySelector('img')!.getAttribute('src')).toContain('/api/v1/friends/3/albums/10/cover')
expect(screen.getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
})
test('the full-screen player links a friend’s track to the music of the friend', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const dialog = screen.getByRole('dialog')
expect(within(dialog).getByRole('link', { name: 'Their Album' })).toHaveAttribute('href', '/friends/3?tab=songs&album=10&of=Their+Album')
expect(within(dialog).getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
})
test('on a phone the full-screen player has the friend on top, and says the audio passes through this server', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const dialog = screen.getByRole('dialog')
const top = dialog.querySelector('[data-phone-top]') as HTMLElement
expect(await within(top).findByLabelText('From Anna’s server')).toBeInTheDocument()
expect(within(dialog).getByText('The audio passes through your server. Anna does not see who listens.')).toBeInTheDocument()
})
test('a track of this server has no note about a friend in the full-screen player', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
const { dialog } = await openNowPlaying()
expect(within(dialog).queryByText(/passes through your server/)).not.toBeInTheDocument()
})
test('on a phone the queue button takes me to what comes next', async () => {
const scroll = vi.fn()
Element.prototype.scrollIntoView = scroll
act(() => usePlayer.getState().playTracks([a, b, c]))
renderBar()
const { dialog } = await openNowPlaying()
await userEvent.click(within(dialog).getByRole('button', { name: 'Queue' }))
expect(scroll).toHaveBeenCalled()
expect(scroll.mock.contexts[0]).toBe(within(dialog).getByRole('region', { name: 'Up next' }))
})
test('a local list does not mark a row because a friend’s track with the same id is playing', () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
render(
<MemoryRouter>
<TrackList tracks={[a]} />
</MemoryRouter>,
)
expect(screen.getByRole('button', { name: /Song 1/ })).not.toHaveAttribute('aria-current')
})
test('the play button is round, and teal for this server’s music', () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
const play = screen.getByRole('button', { name: 'Pause' })
expect(play).toHaveClass('rounded-full', 'bg-primary')
expect(play).not.toHaveClass('bg-friend')
})
test('a friend’s music has the play button of the friend colour and says whose it is', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
renderBar()
expect(screen.getByRole('button', { name: 'Pause' })).toHaveClass('bg-friend')
expect(await screen.findByLabelText('From Anna’s server')).toHaveTextContent('Anna')
})
test('this server’s own music carries no name of a friend', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
await screen.findByText('Song 1')
expect(screen.queryByLabelText(/server/)).not.toBeInTheDocument()
})
test('the bar and the full-screen player both show the spectrogram of what plays', async () => {
act(() => usePlayer.getState().playTracks([a]))
renderBar()
expect(screen.getAllByRole('img', { name: 'Spectrogram of what is playing' })).toHaveLength(1)
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
// The full-screen player covers the page: what is behind it is not reachable while it is open.
expect(within(screen.getByRole('dialog')).getAllByRole('img', { name: 'Spectrogram of what is playing' })).toHaveLength(1)
})
test('the full-screen player says whose music a friend’s track is', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
expect((await screen.findAllByLabelText('From Anna’s server')).length).toBeGreaterThanOrEqual(2)
})
test('the seek bar of a track of this server is the shape of the track', async () => {
act(() => usePlayer.getState().playTracks([a]))
const { container } = renderBar()
await waitFor(() => expect(container.querySelectorAll('footer [data-bar]').length).toBe(120))
expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(true)
})
test('the seek bar of a friend’s track is its shape too, asked of the friend', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
const { container } = renderBar()
await waitFor(() => expect(container.querySelectorAll('footer [data-bar]').length).toBe(120))
expect(calls.some((c) => c.key === 'GET /api/v1/friends/3/tracks/1/peaks')).toBe(true)
expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(false)
})