Merge pull request 'feat(web): volume control in the player' (#78) from feat/volume into main

This commit is contained in:
squidd 2026-11-12 15:29:36 +01:00
commit 8339b043b7
13 changed files with 318 additions and 4 deletions

View file

@ -328,7 +328,7 @@ npm install
SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda
```
What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The bulk jobs screen and serving the app from the binary come later.

View file

@ -0,0 +1,61 @@
import { act, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import VolumeControl from './VolumeControl'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
localStorage.clear()
usePlayer.setState({ volume: 0.5, muted: false })
})
const slider = () => screen.getByRole('slider', { name: 'Volume' })
test('it has a mute button and a slider that shows the level in percent', () => {
render(<VolumeControl />)
expect(screen.getByRole('button', { name: 'Mute' })).toBeInTheDocument()
expect(slider()).toHaveValue('50')
expect(slider()).toHaveAttribute('aria-valuetext', '50%')
expect(slider()).toHaveAttribute('min', '0')
expect(slider()).toHaveAttribute('max', '100')
})
test('moving the slider sets the volume', () => {
render(<VolumeControl />)
fireEvent.change(slider(), { target: { value: '30' } })
expect(usePlayer.getState().volume).toBe(0.3)
})
test('the slider follows the volume when it is changed elsewhere', () => {
render(<VolumeControl />)
act(() => usePlayer.getState().setVolume(0.8))
expect(slider()).toHaveValue('80')
})
test('the mute button mutes, says so, and the slider falls to zero without losing the level', async () => {
render(<VolumeControl />)
await userEvent.click(screen.getByRole('button', { name: 'Mute' }))
expect(usePlayer.getState()).toMatchObject({ muted: true, volume: 0.5 })
expect(screen.getByRole('button', { name: 'Unmute' })).toBeInTheDocument()
expect(slider()).toHaveValue('0')
expect(slider()).toHaveAttribute('aria-valuetext', '0%')
await userEvent.click(screen.getByRole('button', { name: 'Unmute' }))
expect(usePlayer.getState()).toMatchObject({ muted: false, volume: 0.5 })
expect(slider()).toHaveValue('50')
})
test('moving the slider while muted unmutes', () => {
usePlayer.setState({ muted: true })
render(<VolumeControl />)
fireEvent.change(slider(), { target: { value: '70' } })
expect(usePlayer.getState()).toMatchObject({ muted: false, volume: 0.7 })
})
test('on a phone the slider is hidden, since the device has its own volume, and the button stays', () => {
render(<VolumeControl />)
expect(slider().className).toContain('max-sm:hidden')
expect(screen.getByRole('button', { name: 'Mute' }).className).not.toContain('max-sm:hidden')
})

View file

@ -0,0 +1,38 @@
import { Volume1, Volume2, VolumeX } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { usePlayer } from '@/player/store'
/**
* A mute button and a volume slider. While muted the slider shows zero, and moving it unmutes. On a phone
* the slider is hidden (the device has its own volume) and the button stays.
*/
export default function VolumeControl({ className }: { className?: string }) {
const { t } = useTranslation()
const volume = usePlayer((s) => s.volume)
const muted = usePlayer((s) => s.muted)
const setVolume = usePlayer((s) => s.setVolume)
const toggleMute = usePlayer((s) => s.toggleMute)
const percent = muted ? 0 : Math.round(volume * 100)
const Icon = percent === 0 ? VolumeX : percent < 50 ? Volume1 : Volume2
return (
<div className={cn('flex items-center gap-1', className)}>
<Button variant="ghost" className="size-11 text-muted-foreground" aria-label={muted ? t('player.unmute') : t('player.mute')} onClick={toggleMute}>
<Icon aria-hidden="true" />
</Button>
<input
type="range"
min={0}
max={100}
step={1}
value={percent}
aria-label={t('player.volume')}
aria-valuetext={`${percent}%`}
onChange={(e) => setVolume(Number(e.target.value) / 100)}
className="h-11 w-24 cursor-pointer accent-primary max-sm:hidden"
/>
</div>
)
}

View file

@ -6,6 +6,7 @@ import Cover from '@/components/Cover'
import FullscreenButton from '@/components/FullscreenButton'
import Scrubber from '@/components/Scrubber'
import TrackRow from '@/components/TrackRow'
import VolumeControl from '@/components/VolumeControl'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
import { formatTime } from '@/lib/time'
@ -92,6 +93,7 @@ export default function NowPlaying() {
</div>
<PlayerControls large />
<VolumeControl className="-mt-3" />
{upNext.length > 0 && (
<section aria-label={t('player.upNext')} className="flex flex-col gap-1 border-t pt-4">

View file

@ -263,6 +263,19 @@ test('the bar and the full-screen player both have a button for browser full scr
}
})
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()

View file

@ -5,6 +5,7 @@ import { Link } from 'react-router-dom'
import Cover from '@/components/Cover'
import FullscreenButton from '@/components/FullscreenButton'
import Scrubber from '@/components/Scrubber'
import VolumeControl from '@/components/VolumeControl'
import { Button } from '@/components/ui/button'
import { formatTime } from '@/lib/time'
import { currentTrack, usePlayer } from '@/player/store'
@ -85,7 +86,8 @@ export default function PlayerBar() {
</div>
</div>
<div className="flex flex-[1_1_120px] justify-end">
<div className="flex flex-[1_1_120px] items-center justify-end">
<VolumeControl />
<FullscreenButton />
<Button
variant="ghost"

View file

@ -43,7 +43,10 @@
"close": "Close",
"upNext": "Up next",
"queue": "Queue",
"nowPlaying": "Now playing"
"nowPlaying": "Now playing",
"volume": "Volume",
"mute": "Mute",
"unmute": "Unmute"
},
"settings": {
"account": "Account",

View file

@ -43,7 +43,10 @@
"close": "Chiudi",
"upNext": "Prossimi brani",
"queue": "Coda",
"nowPlaying": "In riproduzione"
"nowPlaying": "In riproduzione",
"volume": "Volume",
"mute": "Silenzia",
"unmute": "Riattiva l'audio"
},
"settings": {
"account": "Account",

View file

@ -12,6 +12,8 @@ class FakeAudio implements AudioLike {
currentTime = 0
duration = Number.NaN
paused = true
volume = 1
muted = false
playCalls = 0
private url = ''
private handlers = new Map<string, Set<() => void>>()
@ -87,6 +89,8 @@ beforeEach(async () => {
seekMs: null,
seekId: 0,
playId: 0,
volume: 1,
muted: false,
})
sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null })
hooks.onStart.mockClear()
@ -102,6 +106,38 @@ afterEach(() => {
engine.destroy()
})
test('the audio starts at the volume of the player, muted or not', () => {
usePlayer.setState({ volume: 0.3, muted: true })
const other = new FakeAudio()
const second = createEngine(other, hooks)
expect(other.volume).toBe(0.3)
expect(other.muted).toBe(true)
second.destroy()
})
test('moving the volume changes the audio at once, also while it plays', () => {
usePlayer.getState().playTracks([t1])
usePlayer.getState().setVolume(0.2)
expect(audio.volume).toBe(0.2)
expect(audio.muted).toBe(false)
})
test('mute silences the audio and keeps its level, and unmute brings it back', () => {
usePlayer.getState().setVolume(0.6)
usePlayer.getState().toggleMute()
expect(audio.muted).toBe(true)
expect(audio.volume).toBe(0.6)
usePlayer.getState().toggleMute()
expect(audio.muted).toBe(false)
expect(audio.volume).toBe(0.6)
})
test('once the engine is gone the audio is left alone', () => {
engine.destroy()
usePlayer.getState().setVolume(0.1)
expect(audio.volume).toBe(1)
})
test('the current track is loaded from its stream URL with the token and played', () => {
usePlayer.getState().playTracks([t1, t2])
expect(audio.src).toBe('/api/v1/tracks/1/stream?access_token=tok1')

View file

@ -9,6 +9,9 @@ export interface AudioLike {
currentTime: number
duration: number
paused: boolean
/** From 0 to 1. */
volume: number
muted: boolean
play(): Promise<void>
pause(): void
addEventListener(type: AudioEvent, fn: () => void): void
@ -86,6 +89,8 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
}
function sync(state: PlayerState, previous: PlayerState) {
if (state.volume !== previous.volume) audio.volume = state.volume
if (state.muted !== previous.muted) audio.muted = state.muted
const track = currentTrack(state)
if ((track?.id ?? null) !== loadedId || state.playId !== loadedPlayId) {
load(state)
@ -98,6 +103,9 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
}
}
// The audio starts at the volume the player remembers; after that it follows every change.
audio.volume = initial.volume
audio.muted = initial.muted
const unsubscribeStore = usePlayer.subscribe(sync)
sync(initial, { ...initial, queue: [], playId: initial.playId - 1 })

View file

@ -1,5 +1,6 @@
import { create } from 'zustand'
import type { Track } from '@/api/catalog'
import { loadVolume, saveVolume } from './volume'
export type Repeat = 'off' | 'all' | 'one'
@ -17,6 +18,9 @@ export interface PlayerState {
seekId: number
/** Changes every time a new list is started, so that playing the same track again restarts it. */
playId: number
/** From 0 to 1. Kept while muted, so that unmuting brings it back. Remembered in the browser. */
volume: number
muted: boolean
playTracks(tracks: Track[], start?: number): void
togglePlay(): void
@ -32,8 +36,14 @@ export interface PlayerState {
cycleRepeat(): void
/** Plays the track at this position of the queue from the start. */
jumpTo(i: number): void
/** Sets the volume (brought into 0 to 1; a number that is not one is ignored) and unmutes. */
setVolume(volume: number): void
toggleMute(): void
}
/** The level that comes back when mute is pressed on a volume that is already zero. */
const RESTORED_VOLUME = 0.5
let random: () => number = Math.random
/** Tests replace the random source to get a known shuffle. */
@ -71,6 +81,7 @@ export const usePlayer = create<PlayerState>()((set, get) => ({
seekMs: null,
seekId: 0,
playId: 0,
...loadVolume(),
playTracks(tracks, start = 0) {
set((s) => {
@ -189,4 +200,19 @@ export const usePlayer = create<PlayerState>()((set, get) => ({
return { index: i, playing: true, positionMs: 0 }
})
},
setVolume(volume) {
if (Number.isNaN(volume)) return
set({ volume: Math.min(Math.max(volume, 0), 1), muted: false })
saveVolume(get())
},
toggleMute() {
set((s) => {
// Pressing mute on silence would change nothing: bring the sound back instead.
if (s.volume === 0) return { volume: RESTORED_VOLUME, muted: false }
return { muted: !s.muted }
})
saveVolume(get())
},
}))

View file

@ -0,0 +1,91 @@
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { usePlayer } from './store'
import { loadVolume, saveVolume } from './volume'
const KEY = 'sonda.volume'
beforeEach(() => {
localStorage.clear()
usePlayer.setState({ volume: 1, muted: false })
})
afterEach(() => vi.restoreAllMocks())
// --- what is remembered in the browser --------------------------------------------------------
test('with nothing remembered the volume is full and not muted', () => {
expect(loadVolume()).toEqual({ volume: 1, muted: false })
})
test('what was saved is read back', () => {
saveVolume({ volume: 0.4, muted: true })
expect(loadVolume()).toEqual({ volume: 0.4, muted: true })
})
test.each([
['not JSON', 'nope'],
['not an object', '3'],
['a volume that is not a number', '{"volume":"loud","muted":false}'],
['a volume above 1', '{"volume":7,"muted":false}'],
['a negative volume', '{"volume":-1,"muted":false}'],
['a mute that is not a boolean', '{"volume":0.5,"muted":"yes"}'],
])('%s is ignored and the defaults are used', (_what, stored) => {
localStorage.setItem(KEY, stored)
expect(loadVolume()).toEqual({ volume: 1, muted: false })
})
test('a browser that refuses to read or write storage does not break the player', () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked')
})
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('blocked')
})
expect(loadVolume()).toEqual({ volume: 1, muted: false })
expect(() => saveVolume({ volume: 0.2, muted: false })).not.toThrow()
expect(() => usePlayer.getState().setVolume(0.3)).not.toThrow()
})
// --- the rules of volume and mute ------------------------------------------------------------
test('setting the volume keeps it and remembers it', () => {
usePlayer.getState().setVolume(0.35)
expect(usePlayer.getState().volume).toBe(0.35)
expect(JSON.parse(localStorage.getItem(KEY) ?? '{}')).toEqual({ volume: 0.35, muted: false })
})
test('a volume outside 0 to 1 is brought back into it, and a number that is not one is ignored', () => {
usePlayer.getState().setVolume(2)
expect(usePlayer.getState().volume).toBe(1)
usePlayer.getState().setVolume(-0.5)
expect(usePlayer.getState().volume).toBe(0)
usePlayer.getState().setVolume(0.6)
usePlayer.getState().setVolume(Number.NaN)
expect(usePlayer.getState().volume).toBe(0.6)
})
test('moving the volume while muted unmutes', () => {
usePlayer.setState({ muted: true, volume: 0.5 })
usePlayer.getState().setVolume(0.7)
expect(usePlayer.getState()).toMatchObject({ volume: 0.7, muted: false })
})
test('mute keeps the level, and unmute brings it back', () => {
usePlayer.setState({ volume: 0.8, muted: false })
usePlayer.getState().toggleMute()
expect(usePlayer.getState()).toMatchObject({ volume: 0.8, muted: true })
expect(JSON.parse(localStorage.getItem(KEY) ?? '{}')).toEqual({ volume: 0.8, muted: true })
usePlayer.getState().toggleMute()
expect(usePlayer.getState()).toMatchObject({ volume: 0.8, muted: false })
})
test('pressing mute on a volume that is already zero raises it instead, so the button never does nothing', () => {
usePlayer.setState({ volume: 0, muted: false })
usePlayer.getState().toggleMute()
expect(usePlayer.getState()).toMatchObject({ volume: 0.5, muted: false })
})
test('unmuting a volume that was dragged to zero while muted restores a level too', () => {
usePlayer.setState({ volume: 0, muted: true })
usePlayer.getState().toggleMute()
expect(usePlayer.getState()).toMatchObject({ volume: 0.5, muted: false })
})

31
web/src/player/volume.ts Normal file
View file

@ -0,0 +1,31 @@
const KEY = 'sonda.volume'
export interface VolumeState {
/** From 0 (silence) to 1 (full). */
volume: number
muted: boolean
}
const DEFAULTS: VolumeState = { volume: 1, muted: false }
/** What the volume was last time, from this browser. Anything missing or odd gives full volume, not muted. */
export function loadVolume(): VolumeState {
try {
const stored: unknown = JSON.parse(localStorage.getItem(KEY) ?? 'null')
if (typeof stored !== 'object' || stored === null) return DEFAULTS
const { volume, muted } = stored as Record<string, unknown>
if (typeof volume !== 'number' || !(volume >= 0 && volume <= 1) || typeof muted !== 'boolean') return DEFAULTS
return { volume, muted }
} catch {
return DEFAULTS
}
}
/** Remembers the volume in this browser. A browser that refuses storage just forgets it next time. */
export function saveVolume(state: VolumeState): void {
try {
localStorage.setItem(KEY, JSON.stringify({ volume: state.volume, muted: state.muted }))
} catch {
// Private window, blocked site data: the volume works, it is only not remembered.
}
}