diff --git a/ui/src/share/SharePlayer.jsx b/ui/src/share/SharePlayer.jsx
index 2384866ea..0f9311424 100644
--- a/ui/src/share/SharePlayer.jsx
+++ b/ui/src/share/SharePlayer.jsx
@@ -2,6 +2,7 @@ import ReactJkMusicPlayer from 'navidrome-music-player'
import { useCallback, useEffect, useRef, useState } from 'react'
import config, { shareInfo } from '../config'
import { shareCoverUrl, shareDownloadUrl, shareStreamUrl } from '../utils'
+import VolumeControl from './VolumeControl'
import { makeStyles } from '@material-ui/core/styles'
@@ -19,14 +20,27 @@ const useStyle = makeStyles({
pointerEvents: (props) => props.downloading && 'none',
opacity: (props) => props.downloading && 0.65,
},
+ // Free space goes evenly around the volume and icon rows, so the volume
+ // row sits halfway between the play buttons and the icons
+ '& .react-jinke-music-player-mobile-toggle': {
+ flexGrow: 0,
+ paddingBottom: 0,
+ },
+ '& .react-jinke-music-player-mobile-operation': {
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ '& .react-jinke-music-player-mobile-operation .items': {
+ flex: '1 1 auto',
+ flexWrap: 'wrap',
+ alignContent: 'space-evenly',
+ },
'@media (min-width: 768px)': {
- '& .react-jinke-music-player-mobile > div': {
- width: 768,
- margin: 'auto',
- },
- '& .react-jinke-music-player-mobile-cover': {
- width: 'auto !important',
- },
+ '& .react-jinke-music-player-mobile > div:not(.react-jinke-music-player-mobile-cover)':
+ {
+ width: 768,
+ margin: 'auto',
+ },
},
},
})
@@ -34,6 +48,7 @@ const useStyle = makeStyles({
const SharePlayer = () => {
const [downloading, setDownloading] = useState(false)
const timer = useRef(null)
+ const player = useRef(null)
const classes = useStyle({
single: shareInfo?.tracks.length === 1,
downloading,
@@ -67,6 +82,14 @@ const SharePlayer = () => {
DOWNLOAD_FEEDBACK_MS,
)
}, [])
+ // Not audio.volume: the player would keep a stale volume and restore it after a pause
+ const setVolume = useCallback(
+ (volume) => player.current?.setAudioVolume(volume),
+ [],
+ )
+ const setMuted = useCallback((muted) => {
+ if (player.current) player.current.audio.muted = muted
+ }, [])
const options = {
audioLists: list,
mode: 'full',
@@ -82,10 +105,14 @@ const SharePlayer = () => {
spaceBar: true,
volumeFade: { fadeIn: 200, fadeOut: 200 },
sortableOptions: { delay: 200, delayOnTouchOnly: true },
+ extendsContent: (
+
+ ),
}
return (
diff --git a/ui/src/share/SharePlayer.test.jsx b/ui/src/share/SharePlayer.test.jsx
index 68d1eff59..b1ce4584e 100644
--- a/ui/src/share/SharePlayer.test.jsx
+++ b/ui/src/share/SharePlayer.test.jsx
@@ -1,15 +1,28 @@
+import { createRef, forwardRef, useImperativeHandle } from 'react'
import { render, act } from '@testing-library/react'
import SharePlayer, { DOWNLOAD_FEEDBACK_MS } from './SharePlayer'
let playerProps
let renderCount
+let setAudioVolume
+let audio
vi.mock('navidrome-music-player', () => ({
- default: (props) => {
+ default: forwardRef(function MockPlayer(props, ref) {
playerProps = props
renderCount++
+ useImperativeHandle(ref, () => ({ setAudioVolume, audio }))
return
+ }),
+}))
+
+// jsdom resolves the sortablejs build that has no Swap plugin.
+vi.mock('sortablejs', () => ({
+ default: class {
+ static mount() {}
+ destroy() {}
},
+ Swap: class {},
}))
vi.mock('../config', () => ({
@@ -34,6 +47,8 @@ describe('SharePlayer', () => {
vi.useFakeTimers()
playerProps = null
renderCount = 0
+ setAudioVolume = vi.fn()
+ audio = document.createElement('audio')
// Downloading for real would navigate the jsdom window.
clickSpy = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
@@ -46,6 +61,26 @@ describe('SharePlayer', () => {
vi.restoreAllMocks()
})
+ it('sets the volume through the player, so the player keeps it after a pause', () => {
+ render()
+
+ act(() => {
+ playerProps.extendsContent.props.onVolumeChange(0.5)
+ })
+
+ expect(setAudioVolume).toHaveBeenCalledWith(0.5)
+ })
+
+ it('mutes the player audio element', () => {
+ render()
+
+ act(() => {
+ playerProps.extendsContent.props.onMutedChange(true)
+ })
+
+ expect(audio.muted).toBe(true)
+ })
+
it('downloads via an anchor so the service worker does not intercept it', () => {
render()
@@ -137,3 +172,36 @@ describe('SharePlayer', () => {
expect(errorSpy).not.toHaveBeenCalled()
})
})
+
+// SharePlayer depends on this internal player method. This test fails if a
+// player upgrade removes or changes it.
+describe('navidrome-music-player setAudioVolume', () => {
+ let RealPlayer
+
+ beforeEach(async () => {
+ ;({ default: RealPlayer } = await vi.importActual(
+ 'navidrome-music-player/es/index.js',
+ ))
+ window.matchMedia ??= () => ({
+ matches: true,
+ addListener: () => {},
+ removeListener: () => {},
+ })
+ })
+
+ it('keeps the volume the player restores after a fade', () => {
+ const ref = createRef()
+ render(
+ ,
+ )
+
+ act(() => ref.current.setAudioVolume(0.5))
+
+ expect(ref.current.state.soundValue).toBe(0.5)
+ expect(ref.current.audio.volume).toBe(0.25)
+ })
+})
diff --git a/ui/src/share/VolumeControl.jsx b/ui/src/share/VolumeControl.jsx
new file mode 100644
index 000000000..d3119e2df
--- /dev/null
+++ b/ui/src/share/VolumeControl.jsx
@@ -0,0 +1,162 @@
+import { useEffect, useRef, useState } from 'react'
+import PropTypes from 'prop-types'
+import clsx from 'clsx'
+import { makeStyles } from '@material-ui/core/styles'
+import Slider from '@material-ui/core/Slider'
+import { GoMute, GoUnmute } from 'react-icons/go'
+
+const LIGHT = '.react-jinke-music-player-main.light-theme &'
+const muted = { color: 'hsla(0,0%,100%,.6)', [LIGHT]: { color: '#444' } }
+
+// Sizes mirror the player's progress row, so both bars line up
+const useStyle = makeStyles({
+ row: {
+ order: -1,
+ flex: '0 0 100%',
+ display: 'flex',
+ alignItems: 'center',
+ // Doubled to beat the player's `li { padding: 0 }` reset
+ '&&': { padding: '10px 0 14px' },
+ },
+ side: {
+ width: 55,
+ display: 'inline-flex',
+ },
+ button: {
+ cursor: 'pointer',
+ background: 'none',
+ border: 0,
+ padding: 0,
+ color: 'inherit',
+ },
+ mute: {
+ marginRight: 5,
+ ...muted,
+ },
+ level: {
+ marginLeft: 5,
+ justifyContent: 'flex-end',
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ ...muted,
+ },
+ slider: {
+ flex: '1 1 auto',
+ height: 4,
+ padding: '13px 0',
+ color: '#31c27c',
+ },
+ rail: {
+ height: 4,
+ opacity: 1,
+ backgroundColor: 'hsla(0,0%,100%,.6)',
+ [LIGHT]: { backgroundColor: '#e9e9e9' },
+ },
+ track: {
+ height: 4,
+ },
+ thumb: {
+ width: 14,
+ height: 14,
+ marginTop: -5,
+ marginLeft: -7,
+ border: '2px solid #fff',
+ },
+})
+
+const SPACE_KEY_CODE = 32
+
+// iPhone Safari locks audio.volume: it keeps a new value only until a later
+// task reverts it, so the check must read it back asynchronously.
+export const VOLUME_PROBE_MS = 100
+
+const VolumeControl = ({ onVolumeChange, onMutedChange }) => {
+ const classes = useStyle()
+ const [adjustable, setAdjustable] = useState(true)
+ const [volume, setVolume] = useState(1)
+ const [isMuted, setMuted] = useState(false)
+ const button = useRef(null)
+
+ useEffect(() => {
+ const probe = document.createElement('audio')
+ probe.volume = 0.5
+ const timer = setTimeout(
+ () => setAdjustable(probe.volume === 0.5),
+ VOLUME_PROBE_MS,
+ )
+ return () => clearTimeout(timer)
+ }, [])
+
+ // The player toggles play on Space with a native listener on its root, which
+ // a React handler cannot stop in time.
+ useEffect(() => {
+ const el = button.current
+ const stopSpace = (e) => e.keyCode === SPACE_KEY_CODE && e.stopPropagation()
+ el.addEventListener('keydown', stopSpace)
+ return () => el.removeEventListener('keydown', stopSpace)
+ }, [])
+
+ const applyMuted = (value) => {
+ setMuted(value)
+ onMutedChange(value)
+ }
+
+ const handleChange = (_, value) => {
+ setVolume(value)
+ onVolumeChange(value)
+ if (isMuted) applyMuted(false)
+ }
+
+ const label = isMuted ? 'Unmute' : 'Mute'
+ const level = isMuted ? 0 : volume
+
+ const muteButton = (
+
+ )
+
+ if (!adjustable) {
+ return {muteButton}
+ }
+
+ return (
+
+ {muteButton}
+
+
+ {Math.round(level * 100)}%
+
+
+ )
+}
+
+VolumeControl.propTypes = {
+ onVolumeChange: PropTypes.func.isRequired,
+ onMutedChange: PropTypes.func.isRequired,
+}
+
+export default VolumeControl
diff --git a/ui/src/share/VolumeControl.test.jsx b/ui/src/share/VolumeControl.test.jsx
new file mode 100644
index 000000000..6ef24f49d
--- /dev/null
+++ b/ui/src/share/VolumeControl.test.jsx
@@ -0,0 +1,113 @@
+import { render, screen, fireEvent, act } from '@testing-library/react'
+import VolumeControl, { VOLUME_PROBE_MS } from './VolumeControl'
+
+describe('VolumeControl', () => {
+ let onVolumeChange
+ let onMutedChange
+
+ const renderControl = () =>
+ render(
+ ,
+ )
+
+ beforeEach(() => {
+ onVolumeChange = vi.fn()
+ onMutedChange = vi.fn()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('starts at full volume', () => {
+ renderControl()
+
+ expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '1')
+ expect(screen.getByText('100%')).toBeInTheDocument()
+ })
+
+ it('sends slider values to the player', () => {
+ renderControl()
+ const slider = screen.getByRole('slider')
+
+ fireEvent.keyDown(slider, { key: 'PageDown' })
+ fireEvent.keyDown(slider, { key: 'Home' })
+ fireEvent.keyDown(slider, { key: 'End' })
+
+ expect(onVolumeChange.mock.calls).toEqual([[0.9], [0], [1]])
+ })
+
+ it('mutes without losing the volume', () => {
+ renderControl()
+ fireEvent.keyDown(screen.getByRole('slider'), { key: 'PageDown' })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Mute' }))
+ expect(onMutedChange).toHaveBeenLastCalledWith(true)
+ expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '0')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Unmute' }))
+ expect(onMutedChange).toHaveBeenLastCalledWith(false)
+ expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '0.9')
+ expect(onVolumeChange).toHaveBeenCalledTimes(1)
+ })
+
+ it('unmutes when the slider moves', () => {
+ renderControl()
+ fireEvent.click(screen.getByRole('button', { name: 'Mute' }))
+
+ fireEvent.keyDown(screen.getByRole('slider'), { key: 'End' })
+
+ expect(onMutedChange).toHaveBeenLastCalledWith(false)
+ expect(onVolumeChange).toHaveBeenLastCalledWith(1)
+ expect(screen.getByRole('button', { name: 'Mute' })).toBeInTheDocument()
+ })
+
+ it('keeps Space on the mute button away from the player play/pause key', () => {
+ const { container } = renderControl()
+ const playerKeyDown = vi.fn()
+ container.addEventListener('keydown', playerKeyDown)
+
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Mute' }), {
+ key: ' ',
+ keyCode: 32,
+ })
+
+ expect(playerKeyDown).not.toHaveBeenCalled()
+ })
+
+ it('keeps the slider where the browser keeps the volume', () => {
+ vi.useFakeTimers()
+ renderControl()
+
+ act(() => vi.advanceTimersByTime(VOLUME_PROBE_MS))
+
+ expect(screen.getByRole('slider')).toBeInTheDocument()
+ })
+
+ it('shows only the mute button where the browser reverts the volume', () => {
+ vi.useFakeTimers()
+ let volume = 1
+ vi.spyOn(HTMLMediaElement.prototype, 'volume', 'get').mockImplementation(
+ () => volume,
+ )
+ vi.spyOn(HTMLMediaElement.prototype, 'volume', 'set').mockImplementation(
+ (v) => {
+ volume = v
+ setTimeout(() => (volume = 1))
+ },
+ )
+ renderControl()
+
+ act(() => vi.advanceTimersByTime(VOLUME_PROBE_MS))
+
+ expect(screen.queryByRole('slider')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Mute' }))
+ expect(onMutedChange).toHaveBeenLastCalledWith(true)
+ })
+})