From 20856f2ec654ec31e395207c169e35c002e29883 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 11:32:29 +0100 Subject: [PATCH] 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 --- web/src/components/Cover.tsx | 14 +- web/src/components/Scrubber.tsx | 55 ++++ web/src/components/TrackRow.tsx | 37 +++ web/src/components/layout/NowPlaying.tsx | 117 ++++++++ web/src/components/layout/Player.test.tsx | 270 +++++++++++++++++++ web/src/components/layout/PlayerBar.tsx | 102 +++++++ web/src/components/layout/PlayerControls.tsx | 52 ++++ web/src/components/layout/Shell.tsx | 8 +- web/src/components/ui/dialog.tsx | 158 +++++++++++ web/src/i18n/locales/en.json | 19 ++ web/src/i18n/locales/it.json | 19 ++ web/src/lib/time.test.ts | 22 ++ web/src/lib/time.ts | 9 + web/src/player/store.test.ts | 25 ++ web/src/player/store.ts | 10 + web/src/player/ui.ts | 7 + web/src/test/setup.ts | 5 + 17 files changed, 926 insertions(+), 3 deletions(-) create mode 100644 web/src/components/Scrubber.tsx create mode 100644 web/src/components/TrackRow.tsx create mode 100644 web/src/components/layout/NowPlaying.tsx create mode 100644 web/src/components/layout/Player.test.tsx create mode 100644 web/src/components/layout/PlayerBar.tsx create mode 100644 web/src/components/layout/PlayerControls.tsx create mode 100644 web/src/components/ui/dialog.tsx create mode 100644 web/src/lib/time.test.ts create mode 100644 web/src/lib/time.ts create mode 100644 web/src/player/ui.ts diff --git a/web/src/components/Cover.tsx b/web/src/components/Cover.tsx index cc95c35..9690c9b 100644 --- a/web/src/components/Cover.tsx +++ b/web/src/components/Cover.tsx @@ -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 ( -
+
{showImage ? ( 0) + const max = disabled ? 1 : durationMs + const value = Math.min(Math.max(positionMs, 0), max) + const filled = (value / max) * BARS + + const input = ( + 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 ( +
+ {Array.from({ length: BARS }, (_, i) => ( +
+ ) +} diff --git a/web/src/components/TrackRow.tsx b/web/src/components/TrackRow.tsx new file mode 100644 index 0000000..90da7ff --- /dev/null +++ b/web/src/components/TrackRow.tsx @@ -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 ( + + ) +} diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx new file mode 100644 index 0000000..a9008d3 --- /dev/null +++ b/web/src/components/layout/NowPlaying.tsx @@ -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 ( + + + {track && ( + <> + + {t('player.nowPlaying')} + +
+
+ +
+ +
+
+ + {track.title} + +

+ {track.artists.length === 0 + ? '—' + : track.artists.map((a, i) => ( + + {i > 0 && ', '} + setOpen(false)} className="hover:underline"> + {a.name} + + + ))} +

+ {track.album && ( + setOpen(false)} + className="text-muted-foreground hover:underline" + > + {track.album.title} + + )} +
+ +
+ +
+ {formatTime(player.positionMs)} + {formatTime(track.duration_ms)} +
+
+ + + + {upNext.length > 0 && ( +
+

{t('player.upNext')}

+ {upNext.map((next, k) => ( + player.jumpTo(player.index + 1 + k)} + /> + ))} +
+ )} +
+
+ + )} +
+
+ ) +} diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx new file mode 100644 index 0000000..ff4fb48 --- /dev/null +++ b/web/src/components/layout/Player.test.tsx @@ -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 { + 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( + + + {extra} + , + ) +} + +// --- Scrubber ---------------------------------------------------------------------------------- + +test.each(['line', 'bars'] as const)('the %s scrubber seeks to the position that was chosen', (variant) => { + const onSeek = vi.fn() + render() + 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( {}} 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( {}} 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( + + + , + ) + 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( + + {}} /> + , + ) + expect(screen.getByRole('button', { name: /Song 3/ })).toHaveTextContent('5') +}) + +test('a row of a track with no album and no artists still renders', () => { + render( + + {}} /> + , + ) + expect(screen.getByRole('button', { name: /Song 3/ })).toHaveTextContent('—') +}) + +test('the row of the track that is playing is marked', () => { + render( + + {}} active /> + , + ) + 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() + + 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) + } +}) diff --git a/web/src/components/layout/PlayerBar.tsx b/web/src/components/layout/PlayerBar.tsx new file mode 100644 index 0000000..91ea5a3 --- /dev/null +++ b/web/src/components/layout/PlayerBar.tsx @@ -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 ( +
+
+ {track ? ( + <> + +
+ + + {track.artists.length === 0 + ? '—' + : track.artists.map((a, i) => ( + + {i > 0 && ', '} + + {a.name} + + + ))} + +
+ + ) : ( + {t('player.nothingPlaying')} + )} +
+ +
+ +
+ {formatTime(track ? player.positionMs : 0)} +
+ +
+ {formatTime(track?.duration_ms ?? 0)} +
+
+ +
+ +
+ + +
+ ) +} diff --git a/web/src/components/layout/PlayerControls.tsx b/web/src/components/layout/PlayerControls.tsx new file mode 100644 index 0000000..cc1da10 --- /dev/null +++ b/web/src/components/layout/PlayerControls.tsx @@ -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 ( +
+ + + + + +
+ ) +} diff --git a/web/src/components/layout/Shell.tsx b/web/src/components/layout/Shell.tsx index bdb1b25..9f2a55f 100644 --- a/web/src/components/layout/Shell.tsx +++ b/web/src/components/layout/Shell.tsx @@ -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 (
@@ -11,6 +14,9 @@ export default function Shell() {
+
+ +
) } diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx new file mode 100644 index 0000000..c962a2d --- /dev/null +++ b/web/src/components/ui/dialog.tsx @@ -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 +} + +function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) { + return +} + +function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) { + return +} + +function DialogClose({ ...props }: DialogPrimitive.Close.Props) { + return +} + +function DialogOverlay({ + className, + ...props +}: DialogPrimitive.Backdrop.Props) { + return ( + + ) +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: DialogPrimitive.Popup.Props & { + showCloseButton?: boolean +}) { + return ( + + + + {children} + {showCloseButton && ( + + } + > + + Close + + )} + + + ) +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function DialogFooter({ + className, + showCloseButton = false, + children, + ...props +}: React.ComponentProps<"div"> & { + showCloseButton?: boolean +}) { + return ( +
+ {children} + {showCloseButton && ( + }> + Close + + )} +
+ ) +} + +function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) { + return ( + + ) +} + +function DialogDescription({ + className, + ...props +}: DialogPrimitive.Description.Props) { + return ( + + ) +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 8689d8c..0d18426 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index eb35cae..15d8133 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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", diff --git a/web/src/lib/time.test.ts b/web/src/lib/time.test.ts new file mode 100644 index 0000000..eaed80e --- /dev/null +++ b/web/src/lib/time.test.ts @@ -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') +}) diff --git a/web/src/lib/time.ts b/web/src/lib/time.ts new file mode 100644 index 0000000..d388d0a --- /dev/null +++ b/web/src/lib/time.ts @@ -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}` +} diff --git a/web/src/player/store.test.ts b/web/src/player/store.test.ts index a73db96..5a53897 100644 --- a/web/src/player/store.test.ts +++ b/web/src/player/store.test.ts @@ -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() diff --git a/web/src/player/store.ts b/web/src/player/store.ts index eaefd76..ab2c131 100644 --- a/web/src/player/store.ts +++ b/web/src/player/store.ts @@ -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()((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 } + }) + }, })) diff --git a/web/src/player/ui.ts b/web/src/player/ui.ts new file mode 100644 index 0000000..de28b27 --- /dev/null +++ b/web/src/player/ui.ts @@ -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 }), +})) diff --git a/web/src/test/setup.ts b/web/src/test/setup.ts index a2b254e..407244c 100644 --- a/web/src/test/setup.ts +++ b/web/src/test/setup.ts @@ -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()