From 394208de752d4b128808f5170baca477166b5cd7 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:21:41 +0100 Subject: [PATCH 1/5] feat(web): volume and mute in the player state, remembered in the browser The level is kept while muted so unmuting brings it back, moving it unmutes, pressing mute on silence raises it instead of doing nothing, and a browser that refuses storage just forgets it. --- web/src/player/store.ts | 26 ++++++++++ web/src/player/volume.test.ts | 91 +++++++++++++++++++++++++++++++++++ web/src/player/volume.ts | 31 ++++++++++++ 3 files changed, 148 insertions(+) create mode 100644 web/src/player/volume.test.ts create mode 100644 web/src/player/volume.ts diff --git a/web/src/player/store.ts b/web/src/player/store.ts index ab2c131..61d56db 100644 --- a/web/src/player/store.ts +++ b/web/src/player/store.ts @@ -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()((set, get) => ({ seekMs: null, seekId: 0, playId: 0, + ...loadVolume(), playTracks(tracks, start = 0) { set((s) => { @@ -189,4 +200,19 @@ export const usePlayer = create()((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()) + }, })) diff --git a/web/src/player/volume.test.ts b/web/src/player/volume.test.ts new file mode 100644 index 0000000..158b428 --- /dev/null +++ b/web/src/player/volume.test.ts @@ -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 }) +}) diff --git a/web/src/player/volume.ts b/web/src/player/volume.ts new file mode 100644 index 0000000..0b845c4 --- /dev/null +++ b/web/src/player/volume.ts @@ -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 + 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. + } +} From edab170d3f6f68c4cf22334af2529b441725de05 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:22:23 +0100 Subject: [PATCH 2/5] feat(web): the audio follows the volume and mute of the player The audio starts at the remembered level and follows every change, also while a track plays; once the engine is gone it is left alone. --- web/src/player/engine.test.ts | 36 +++++++++++++++++++++++++++++++++++ web/src/player/engine.ts | 8 ++++++++ 2 files changed, 44 insertions(+) diff --git a/web/src/player/engine.test.ts b/web/src/player/engine.test.ts index b7ed7c4..da4f969 100644 --- a/web/src/player/engine.test.ts +++ b/web/src/player/engine.test.ts @@ -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 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') diff --git a/web/src/player/engine.ts b/web/src/player/engine.ts index 370e9a2..f7d7ead 100644 --- a/web/src/player/engine.ts +++ b/web/src/player/engine.ts @@ -9,6 +9,9 @@ export interface AudioLike { currentTime: number duration: number paused: boolean + /** From 0 to 1. */ + volume: number + muted: boolean play(): Promise 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 }) From 606845ae7250d075aadb7fcc6d2a64212becbf97 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:22:57 +0100 Subject: [PATCH 3/5] feat(web): a volume control with a mute button and a slider The slider shows zero while muted and moving it unmutes; on a phone the slider is hidden, since the device has its own volume, and the button stays. --- web/src/components/VolumeControl.test.tsx | 61 +++++++++++++++++++++++ web/src/components/VolumeControl.tsx | 38 ++++++++++++++ web/src/i18n/locales/en.json | 5 +- web/src/i18n/locales/it.json | 5 +- 4 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 web/src/components/VolumeControl.test.tsx create mode 100644 web/src/components/VolumeControl.tsx diff --git a/web/src/components/VolumeControl.test.tsx b/web/src/components/VolumeControl.test.tsx new file mode 100644 index 0000000..ebf7a8f --- /dev/null +++ b/web/src/components/VolumeControl.test.tsx @@ -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() + 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() + 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() + 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() + 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() + 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() + expect(slider().className).toContain('max-sm:hidden') + expect(screen.getByRole('button', { name: 'Mute' }).className).not.toContain('max-sm:hidden') +}) diff --git a/web/src/components/VolumeControl.tsx b/web/src/components/VolumeControl.tsx new file mode 100644 index 0000000..7eb1311 --- /dev/null +++ b/web/src/components/VolumeControl.tsx @@ -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 ( +
+ + setVolume(Number(e.target.value) / 100)} + className="h-11 w-24 cursor-pointer accent-primary max-sm:hidden" + /> +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index f395c88..a407f7b 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 589427b..f08d7aa 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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", From 99d25acd9abfa5f36ccb26eca97e8045925f3d64 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:23:50 +0100 Subject: [PATCH 4/5] feat(web): the volume control in the player bar and the full-screen player Both places move the same volume. README mentions it. --- README.md | 2 +- web/src/components/layout/NowPlaying.tsx | 2 ++ web/src/components/layout/Player.test.tsx | 13 +++++++++++++ web/src/components/layout/PlayerBar.tsx | 4 +++- 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b7292a6..a96751f 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx index 8376960..24f2294 100644 --- a/web/src/components/layout/NowPlaying.tsx +++ b/web/src/components/layout/NowPlaying.tsx @@ -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() { + {upNext.length > 0 && (
diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index 2fa5d13..141ff21 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -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() diff --git a/web/src/components/layout/PlayerBar.tsx b/web/src/components/layout/PlayerBar.tsx index 7e30540..5843761 100644 --- a/web/src/components/layout/PlayerBar.tsx +++ b/web/src/components/layout/PlayerBar.tsx @@ -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() { -
+
+
- + {upNext.length > 0 && (