Compare commits

..
38 changed files with 91 additions and 906 deletions

View file

@ -1,15 +1,5 @@
# Changelog
## [0.4.0](https://git.kmalloc.org/squid/sonda/compare/v0.3.0...v0.4.0) (2026-11-16)
### Features
* **web:** make Sonda feel like an app on a phone ([75a7898](https://git.kmalloc.org/squid/sonda/commit/75a7898c68ca65c8c4efa0f51b72d62ac9a4db6e))
### Documentation
* note that this repo moved to git.kmalloc.org ([ee31e0e](https://git.kmalloc.org/squid/sonda/commit/ee31e0ee7caf9e7510b7cfde1f4e096721966e90))
## [0.3.0](https://git.kmalloc.org/squid/sonda/compare/v0.2.0...v0.3.0) (2026-11-16)
### Features

View file

@ -1,9 +1,5 @@
# Sonda
**This repository has moved.** Development continues at
[git.kmalloc.org/squid/sonda](https://git.kmalloc.org/squid/sonda); this
Codeberg mirror is archived and read-only.
Sonda is a privacy-first, self-hosted music server written in Go. It streams the music you already own, from your own disks, and keeps everything it knows about you on your own machine.
It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account.
@ -394,7 +390,7 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it.
## Web app
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. The player draws a live picture of what is playing, in the browser, from the sound itself (Web Audio). Settings has a choice for it, kept on the device: a spectrogram (the last seconds, low notes at the bottom, the default), the classic bars with falling caps, an oscilloscope, Milkdrop, or nothing. The bars, the oscilloscope and the spectrogram take the colour of this server or, for a friend's song, the colour of the friend. Milkdrop fills the background of the full-screen player with the pictures Winamp made famous, drawn on the device with [butterchurn](https://github.com/jberg/butterchurn) (MIT) and its presets, which are part of the app: nothing is fetched from outside. It is loaded only when chosen, and anyone who asked the system for less motion gets the spectrogram instead, because the pictures flash. The player listens to the sound and changes nothing of it, and draws only while something plays. On a phone the player is one row at the foot of the page (and is not there while nothing plays); a tap or a swipe up opens the full-screen player, a swipe down or the Back gesture closes it, and the lock screen shows the song with its seek bar and follows play and pause. The queue is kept in the browser, so a page that is reloaded, or a tab that Android throws away, comes back paused on the same song at the same second.
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. The player draws a live picture of what is playing, in the browser, from the sound itself (Web Audio). Settings has a choice for it, kept on the device: a spectrogram (the last seconds, low notes at the bottom, the default), the classic bars with falling caps, an oscilloscope, Milkdrop, or nothing. The bars, the oscilloscope and the spectrogram take the colour of this server or, for a friend's song, the colour of the friend. Milkdrop fills the background of the full-screen player with the pictures Winamp made famous, drawn on the device with [butterchurn](https://github.com/jberg/butterchurn) (MIT) and its presets, which are part of the app: nothing is fetched from outside. It is loaded only when chosen, and anyone who asked the system for less motion gets the spectrogram instead, because the pictures flash. The player listens to the sound and changes nothing of it, and draws only while something plays.
To work on the interface itself, run the Vite dev server next to a running `sondad` (set `SONDA_URL` to where it listens: the default is `http://127.0.0.1:8080`):

View file

@ -9,7 +9,7 @@
<link rel="manifest" href="/manifest.webmanifest" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Sonda" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Your own music, on your own server." />
<title>Sonda</title>
</head>

View file

@ -9,7 +9,7 @@ export default function AuthGate({ children }: { children: ReactNode }) {
const { t } = useTranslation()
if (status === 'loading') {
return <div role="status" aria-label={t('common.loading')} className="min-h-dvh bg-background" />
return <div role="status" aria-label={t('common.loading')} className="min-h-screen bg-background" />
}
if (status === 'anonymous') return <LoginPage />
return <>{children}</>

View file

@ -31,7 +31,7 @@ export default function LoginPage() {
}
return (
<main className="flex min-h-dvh items-center justify-center bg-background p-4">
<main className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="flex w-full max-w-sm flex-col gap-6 rounded-xl bg-card p-8 text-card-foreground">
<Logo name={t('app.name')} className="h-9 w-auto self-start" />
<h1 className="text-xl font-bold">{creating ? t('auth.registerTitle') : t('auth.signInTitle')}</h1>

View file

@ -16,7 +16,7 @@ function placeholder(container: HTMLElement) {
test('a cover asks for the album cover of the API', () => {
const { container } = render(<Cover albumId={12} size={64} />)
const img = container.querySelector('img')!
expect(img.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small')
expect(img.getAttribute('src')).toBe('/api/v1/albums/12/cover')
expect(img).toHaveAttribute('loading', 'lazy')
expect(img).toHaveAttribute('alt', '')
expect(placeholder(container)).toBeNull()
@ -25,9 +25,9 @@ test('a cover asks for the album cover of the API', () => {
test('the cover URL carries the access token and follows it when it changes', () => {
sessionStore.setState({ accessToken: 'tok1' })
const { container } = render(<Cover albumId={12} size={64} />)
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small&access_token=tok1')
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?access_token=tok1')
act(() => sessionStore.setState({ accessToken: 'tok2' }))
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small&access_token=tok2')
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?access_token=tok2')
})
test('a cover that fails to load is replaced by the placeholder', () => {
@ -116,10 +116,3 @@ test('a cover that cannot be loaded falls back to the rings, and the picture hid
expect(placeholder(container)).not.toBeNull()
expect(container.querySelector('img')).toBeNull()
})
test('a big cover asks for the full picture, a friend’s cover for the only one the friend has', () => {
const big = render(<Cover albumId={12} size={520} />)
expect(big.container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover')
const friend = render(<Cover albumId={12} friend={3} size={56} />)
expect(friend.container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/friends/3/albums/12/cover')
})

View file

@ -19,14 +19,10 @@ const RINGS = [
{ size: '68%', opacity: 0.3 },
] as const
/** Up to this size (CSS pixels) a cover is drawn from the small picture. */
const SMALL_UP_TO = 150
/** The cover of an album, or the rings of Sonda when there is none (or it cannot be loaded). */
export default function Cover({ albumId, friend, size, fluid = false }: CoverProps) {
useAccessToken() // the URL carries the token, so it has to follow a renewal
// A thumbnail asks for the small picture: a phone does not need to fetch 1000 pixels to draw 56.
const src = albumId === null ? null : mediaUrl(coverPath(friend, albumId, size <= SMALL_UP_TO))
const src = albumId === null ? null : mediaUrl(coverPath(friend, albumId))
// A failure is remembered for this URL only: a renewed token makes a new URL, which is tried again.
const [failed, setFailed] = useState<string | null>(null)
const showImage = src !== null && failed !== src
@ -40,16 +36,7 @@ export default function Cover({ albumId, friend, size, fluid = false }: CoverPro
className="relative shrink-0 overflow-hidden rounded-sm bg-muted"
>
{showImage ? (
<img
src={src}
alt=""
loading="lazy"
draggable={false}
// Holding a finger on a cover must not open the browser menu of an image; a mouse keeps its right-click.
onContextMenu={(e) => window.matchMedia?.('(pointer: coarse)').matches && e.preventDefault()}
className="size-full object-cover"
onError={() => setFailed(src)}
/>
<img src={src} alt="" loading="lazy" className="size-full object-cover" onError={() => setFailed(src)} />
) : (
<div data-placeholder aria-hidden="true" className="size-full">
{RINGS.map((r) => (

View file

@ -11,5 +11,5 @@ test('it is the heading of the page, the largest text on it', () => {
test('a greeting is larger still', () => {
render(<PageTitle large>Good evening</PageTitle>)
expect(screen.getByRole('heading', { level: 1 }).className).toContain('text-[2.5rem]')
expect(screen.getByRole('heading', { level: 1 }).className).toContain('text-5xl')
})

View file

@ -4,7 +4,7 @@ import { cn } from '@/lib/utils'
/** The title of a page: the largest text on it. A greeting (`large`) is larger still. */
export default function PageTitle({ children, large = false, className }: { children: ReactNode; large?: boolean; className?: string }) {
return (
<h1 className={cn('font-extrabold tracking-tight', large ? 'text-[2.5rem] leading-none sm:text-7xl' : 'text-4xl leading-tight sm:text-5xl', className)}>
<h1 className={cn('font-extrabold tracking-tight', large ? 'text-5xl leading-none sm:text-7xl' : 'text-4xl leading-tight sm:text-5xl', className)}>
{children}
</h1>
)

View file

@ -3,5 +3,5 @@ import { useTranslation } from 'react-i18next'
/** What is on screen while the first page of a lazy route is being fetched. */
export default function RouteLoading() {
const { t } = useTranslation()
return <div role="status" aria-label={t('common.loading')} className="min-h-dvh bg-background" />
return <div role="status" aria-label={t('common.loading')} className="min-h-screen bg-background" />
}

View file

@ -29,12 +29,11 @@ export default function TrackRow({ track, index, onPlay, active = false, disable
disabled={disabled}
aria-current={active ? 'true' : undefined}
className={cn(
'grid min-h-13 min-w-0 flex-1 grid-cols-[minmax(0,1fr)_3rem] items-center gap-2 rounded-lg px-3 text-left sm:grid-cols-[2.5rem_minmax(0,1fr)_4.5rem] sm:gap-3 sm:px-4',
'grid min-h-13 min-w-0 flex-1 grid-cols-[2.5rem_minmax(0,1fr)_4.5rem] items-center gap-3 rounded-lg px-4 text-left',
disabled && 'opacity-60',
)}
>
{/* On a phone the number goes: two buttons and the length follow the title, and it needs the room. */}
<span className={cn('tabular-nums max-sm:hidden', active ? 'font-bold text-primary' : 'text-muted-foreground')}>
<span className={cn('tabular-nums', active ? 'font-bold text-primary' : 'text-muted-foreground')}>
{track.track_no > 0 ? track.track_no : index + 1}
</span>
<span className="min-w-0">

View file

@ -16,7 +16,6 @@ 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'
import { useSwipe } from '@/lib/useSwipe'
import { albumHref, artistHref, type QueuedTrack } from '@/player/media'
import { useMilkdrop } from '@/player/milkdrop'
import { useVisualizerPref } from '@/player/prefs'
@ -24,9 +23,7 @@ import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import PlayerControls from './PlayerControls'
/** How many of the next tracks a wide screen lists; a phone lists them all, up to MAX_UP_NEXT. */
const UP_NEXT = 3
const MAX_UP_NEXT = 100
/** The big seek bar and the times. The part of this screen that follows the playback every moment. */
function NowPlayingSeek({ track }: { track: QueuedTrack }) {
@ -72,15 +69,11 @@ export default function NowPlaying() {
if (open && !track) setOpen(false)
}, [open, track, setOpen])
// A swipe down from the top of the page closes the player, as the arrow does.
const swipe = useSwipe({ onDown: () => setOpen(false), allow: (e) => e.currentTarget.scrollTop === 0 })
const upNext = queue.slice(index + 1, index + 1 + MAX_UP_NEXT)
const upNext = queue.slice(index + 1, index + 1 + UP_NEXT)
return (
<Dialog open={open && track !== null} onOpenChange={setOpen}>
<DialogContent
{...swipe}
showCloseButton={false}
className="inset-0 h-dvh w-screen max-w-none translate-x-0 translate-y-0 grid-cols-[minmax(0,1fr)] content-start overflow-y-auto sm:content-center rounded-none bg-background p-6 sm:max-w-none md:p-12 motion-reduce:data-closed:animate-none motion-reduce:data-open:animate-none"
>
@ -165,15 +158,14 @@ export default function NowPlaying() {
{upNext.length > 0 && (
<section ref={upNextRef} aria-label={t('player.upNext')} className="flex scroll-mt-4 flex-col gap-1 border-t pt-4">
<h2 className="pb-2 font-bold">{t('player.upNext')}</h2>
{upNext.map((next, k) => {
const row = <TrackRow track={next} index={index + 1 + k} onPlay={() => jumpTo(index + 1 + k)} />
// Past the first few, only a phone has the rows: `contents` leaves the row where it was.
return k < UP_NEXT ? (
<div key={`${next.id}-${k}`} className="contents">{row}</div>
) : (
<div key={`${next.id}-${k}`} className="contents sm:hidden">{row}</div>
)
})}
{upNext.map((next, k) => (
<TrackRow
key={`${next.id}-${k}`}
track={next}
index={index + 1 + k}
onPlay={() => jumpTo(index + 1 + k)}
/>
))}
</section>
)}

View file

@ -80,12 +80,3 @@ test('the bar of the current tab is the colour of this server', () => {
const nav = renderTabs('/')
expect(within(nav).getByRole('link', { name: 'Home' }).querySelector('[data-bar]')).toHaveClass('bg-primary')
})
test('each tab has an icon above its name, which the screen reader does not read twice', () => {
const nav = renderTabs('/', [{ id: 3, name: 'Anna' }])
for (const link of within(nav).getAllByRole('link')) {
const icon = link.querySelector('svg')
expect(icon).not.toBeNull()
expect(icon).toHaveAttribute('aria-hidden', 'true')
}
})

View file

@ -1,4 +1,3 @@
import { Ellipsis, House, Library, Search, Users, type LucideIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation } from 'react-router-dom'
import { useFriends } from '@/api/friends'
@ -21,32 +20,31 @@ export default function PhoneTabs() {
const { t } = useTranslation()
const { pathname } = useLocation()
const hasFriends = (useFriends().data?.length ?? 0) > 0
const tabs: { to: string; icon: LucideIcon; label: string; current: boolean; friend?: boolean }[] = [
{ to: '/', icon: House, label: t('nav.home'), current: pathname === '/' || under(pathname, HOME) },
{ to: '/search', icon: Search, label: t('nav.search'), current: under(pathname, ['/search']) },
{ to: '/library', icon: Library, label: t('nav.library'), current: under(pathname, LIBRARY) },
...(hasFriends ? [{ to: '/friends', icon: Users, label: t('nav.friends'), current: under(pathname, ['/friends']), friend: true }] : []),
{ to: '/more', icon: Ellipsis, label: t('nav.more'), current: under(pathname, MORE) },
const tabs = [
{ to: '/', label: t('nav.home'), current: pathname === '/' || under(pathname, HOME) },
{ to: '/search', label: t('nav.search'), current: under(pathname, ['/search']) },
{ to: '/library', label: t('nav.library'), current: under(pathname, LIBRARY) },
...(hasFriends ? [{ to: '/friends', label: t('nav.friends'), current: under(pathname, ['/friends']), friend: true }] : []),
{ to: '/more', label: t('nav.more'), current: under(pathname, MORE) },
]
return (
<nav aria-label={t('nav.tabs')} className="flex border-t border-border bg-background pb-[env(safe-area-inset-bottom)] sm:hidden">
<nav aria-label={t('nav.tabs')} className="flex border-t border-border bg-background sm:hidden">
{tabs.map((tab) => (
<Link
key={tab.to}
to={tab.to}
aria-current={tab.current ? 'page' : undefined}
className={cn(
'flex min-h-14 flex-1 flex-col items-center justify-center gap-1 text-[13px] focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-ring',
'flex min-h-14 flex-1 flex-col items-center justify-center gap-1.5 text-[13px] focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-ring',
tab.current ? 'font-bold text-foreground' : 'font-medium text-muted-foreground',
)}
>
<span
data-bar
aria-hidden="true"
className={cn('h-[3px] w-6', tab.current ? (tab.friend ? 'bg-friend' : 'bg-primary') : 'bg-transparent')}
className={cn('h-[3px] w-6', tab.current ? ('friend' in tab ? 'bg-friend' : 'bg-primary') : 'bg-transparent')}
/>
<tab.icon aria-hidden="true" className="size-5" />
<span>{tab.label}</span>
</Link>
))}

View file

@ -112,15 +112,6 @@ test('a row shows the track number, title, artists and length, and plays when cl
expect(onPlay).toHaveBeenCalledTimes(1)
})
test('on a phone a row gives its room to the title: the number is only for wider screens', () => {
render(
<MemoryRouter>
<TrackRow track={track(3, { track_no: 7 })} index={0} onPlay={() => {}} />
</MemoryRouter>,
)
expect(screen.getByText('7')).toHaveClass('max-sm:hidden')
})
test('a row of a track with no number shows its position in the list', () => {
render(
<MemoryRouter>
@ -273,10 +264,8 @@ test('Up next shows the next three tracks and a click plays one of them', async
renderBar()
const { dialog } = await openNowPlaying()
const upNext = within(dialog).getByRole('region', { name: 'Up next' })
// A wide screen lists three: the fourth is there for a phone only.
const shown = within(upNext).getAllByRole('button').filter((b) => b.closest('.sm\\:hidden') === null)
expect(shown).toHaveLength(3)
expect(within(upNext).getByText('Song 5').closest('.sm\\:hidden')).not.toBeNull()
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)
})
@ -545,92 +534,3 @@ test('the full-screen player says which station is playing, and says nothing for
act(() => usePlayer.getState().playTracks([a, b]))
expect(within(dialog).queryByText(/^Radio:/)).not.toBeInTheDocument()
})
// --- The bar on a phone ------------------------------------------------------------------------
test('on a phone the bar is not there while nothing plays, and is there once something does', () => {
renderBar()
expect(screen.getByRole('contentinfo')).toHaveClass('max-sm:hidden')
act(() => usePlayer.getState().playTracks([a, b]))
expect(screen.getByRole('contentinfo')).not.toHaveClass('max-sm:hidden')
})
test('on a phone the bar keeps play and next, and leaves shuffle, previous and repeat to the full-screen player', () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const bar = within(screen.getByRole('contentinfo'))
for (const name of ['Shuffle', 'Previous', 'Repeat: off']) expect(bar.getByRole('button', { name })).toHaveClass('max-sm:hidden')
for (const name of ['Pause', 'Next']) expect(bar.getByRole('button', { name })).not.toHaveClass('max-sm:hidden')
})
test('on a phone the seek row is a thin line of progress that is not for touching', () => {
act(() => {
usePlayer.getState().playTracks([a, b])
usePlayer.setState({ positionMs: 50_000 })
})
renderBar()
const bar = screen.getByRole('contentinfo')
expect(within(bar).getByRole('slider', { name: 'Seek' }).closest('.player-seek')).toHaveClass('max-sm:hidden')
const line = within(bar).getByTestId('phone-progress')
expect(line).toHaveAttribute('aria-hidden', 'true')
expect(line.firstElementChild).toHaveStyle({ width: '25%' })
})
test('the full-screen player controls come in full: shuffle, previous and repeat are not hidden there', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const dialog = within(screen.getByRole('dialog'))
for (const name of ['Shuffle', 'Previous', 'Repeat: off']) expect(dialog.getByRole('button', { name })).not.toHaveClass('max-sm:hidden')
})
// --- Gestures on a phone -----------------------------------------------------------------------
const touch = (x: number, y: number) => ({ clientX: x, clientY: y })
test('a swipe up on the bar opens the full-screen player, a small movement does not', () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const bar = screen.getByRole('contentinfo')
fireEvent.touchStart(bar, { touches: [touch(100, 500)] })
fireEvent.touchEnd(bar, { changedTouches: [touch(100, 470)] })
expect(useNowPlayingUi.getState().open).toBe(false)
fireEvent.touchStart(bar, { touches: [touch(100, 500)] })
fireEvent.touchEnd(bar, { changedTouches: [touch(100, 400)] })
expect(useNowPlayingUi.getState().open).toBe(true)
})
test('a sideways swipe on the bar does not open the full-screen player', () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
const bar = screen.getByRole('contentinfo')
fireEvent.touchStart(bar, { touches: [touch(300, 500)] })
fireEvent.touchEnd(bar, { changedTouches: [touch(100, 410)] })
expect(useNowPlayingUi.getState().open).toBe(false)
})
test('a swipe down closes the full-screen player, unless its page is scrolled', async () => {
act(() => usePlayer.getState().playTracks([a, b]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const dialog = screen.getByRole('dialog')
Object.defineProperty(dialog, 'scrollTop', { configurable: true, value: 120 })
fireEvent.touchStart(dialog, { touches: [touch(100, 200)] })
fireEvent.touchEnd(dialog, { changedTouches: [touch(100, 420)] })
expect(useNowPlayingUi.getState().open).toBe(true)
Object.defineProperty(dialog, 'scrollTop', { configurable: true, value: 0 })
fireEvent.touchStart(dialog, { touches: [touch(100, 200)] })
fireEvent.touchEnd(dialog, { changedTouches: [touch(100, 420)] })
expect(useNowPlayingUi.getState().open).toBe(false)
})
test('on a phone the full-screen player lists the whole queue, a wide screen keeps three', async () => {
const many = [1, 2, 3, 4, 5, 6].map((n) => track(n))
act(() => usePlayer.getState().playTracks(many))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const list = within(screen.getByRole('region', { name: 'Up next' }))
for (const n of [2, 3, 4, 5, 6]) expect(list.getByRole('button', { name: new RegExp(`Song ${n}`) })).toBeInTheDocument()
for (const n of [2, 3, 4]) expect(list.getByRole('button', { name: new RegExp(`Song ${n}`) }).closest('.sm\\:hidden')).toBeNull()
for (const n of [5, 6]) expect(list.getByRole('button', { name: new RegExp(`Song ${n}`) }).closest('.sm\\:hidden')).not.toBeNull()
})

View file

@ -12,9 +12,7 @@ import VolumeControl from '@/components/VolumeControl'
import { Button } from '@/components/ui/button'
import { usePeaks } from '@/api/peaks'
import { formatTime } from '@/lib/time'
import { cn } from '@/lib/utils'
import { artistHref, type QueuedTrack } from '@/player/media'
import { useSwipe } from '@/lib/useSwipe'
import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import NowPlaying from './NowPlaying'
@ -42,7 +40,7 @@ function PlayerSeek({ track }: { track: QueuedTrack | null }) {
// A friend's track has its shape from the friend's server, which works it out the first time.
const peaks = usePeaks(track?.id ?? null, { friend: track?.friend })
return (
<div className="player-seek flex w-full max-w-xl items-center gap-3 justify-self-center text-[13px] text-muted-foreground tabular-nums max-sm:hidden">
<div className="player-seek flex w-full max-w-xl items-center gap-3 justify-self-center text-[13px] text-muted-foreground tabular-nums">
<span>{formatTime(track ? positionMs : 0)}</span>
<div className="flex-1">
<Scrubber
@ -59,40 +57,18 @@ function PlayerSeek({ track }: { track: QueuedTrack | null }) {
)
}
/** On a phone the position is a thin line along the top of the bar: it shows how far the song is and cannot be touched. */
function PhoneProgress({ track }: { track: QueuedTrack | null }) {
const positionMs = usePlayer((s) => s.positionMs)
const duration = track?.duration_ms ?? 0
const share = duration > 0 ? Math.min(100, Math.max(0, (positionMs / duration) * 100)) : 0
return (
<div data-testid="phone-progress" aria-hidden="true" className="absolute inset-x-0 top-0 h-0.5 bg-border sm:hidden">
<div className={track?.friend !== undefined ? 'h-full bg-friend' : 'h-full bg-primary'} style={{ width: `${share}%` }} />
</div>
)
}
/**
* The bar at the bottom of every page: what is playing, the controls and the position. On a phone it is one row, and
* it is not there at all while nothing plays; the full-screen player has the rest.
*/
/** The bar at the bottom of every page: what is playing, the controls and the position. */
export default function PlayerBar() {
const { t } = useTranslation()
const setOpen = useNowPlayingUi((s) => s.setOpen)
const track = usePlayer(currentTrack)
usePlayPauseKey()
// A swipe up on a phone opens the full-screen player, as the cover does.
const swipe = useSwipe({ onUp: () => track && setOpen(true) })
return (
<footer
{...swipe}
aria-label={t('player.label')}
className={cn(
'player-bar relative gap-x-4 gap-y-1 border-t border-border bg-card px-4 py-2 text-card-foreground sm:gap-x-6 sm:px-8 sm:py-3',
!track && 'max-sm:hidden',
)}
className="player-bar gap-x-4 gap-y-1 border-t border-border bg-card px-4 py-2 text-card-foreground sm:gap-x-6 sm:px-8 sm:py-3"
>
<PhoneProgress track={track} />
<div className="player-info flex min-w-0 items-center gap-3">
{track ? (
<>
@ -126,7 +102,7 @@ export default function PlayerBar() {
</div>
<div className="player-controls flex justify-end sm:justify-center">
<PlayerControls phoneMini />
<PlayerControls />
</div>
<PlayerSeek track={track} />

View file

@ -5,16 +5,7 @@ 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,
phoneMini = false,
className,
}: {
large?: boolean
/** On a phone keep only play and next: the rest is in the full-screen player. */
phoneMini?: boolean
className?: string
}) {
export default function PlayerControls({ large = false, className }: { large?: boolean; className?: string }) {
const { t } = useTranslation()
const none = usePlayer((s) => currentTrack(s) === null)
// A friend's track has the play button of the friend colour, so that what comes from elsewhere is told apart.
@ -28,14 +19,13 @@ export default function PlayerControls({
const next = usePlayer((s) => s.next)
const cycleRepeat = usePlayer((s) => s.cycleRepeat)
const small = large ? 'size-12' : 'size-11'
const extra = phoneMini && 'max-sm:hidden'
const repeatLabel = { off: 'player.repeatOff', all: 'player.repeatAll', one: 'player.repeatOne' }[repeat]
return (
<div className={cn('flex items-center gap-1 sm:gap-3', className)}>
<Button
variant="ghost"
className={cn(small, extra, shuffle ? 'text-primary' : 'text-muted-foreground')}
className={cn(small, shuffle ? 'text-primary' : 'text-muted-foreground')}
aria-label={t('player.shuffle')}
aria-pressed={shuffle}
disabled={none}
@ -43,7 +33,7 @@ export default function PlayerControls({
>
<Shuffle />
</Button>
<Button variant="ghost" className={cn(small, extra)} aria-label={t('player.previous')} disabled={none} onClick={prev}>
<Button variant="ghost" className={small} aria-label={t('player.previous')} disabled={none} onClick={prev}>
<SkipBack />
</Button>
<Button
@ -63,7 +53,7 @@ export default function PlayerControls({
</Button>
<Button
variant="ghost"
className={cn(small, extra, repeat === 'off' ? 'text-muted-foreground' : 'text-primary')}
className={cn(small, repeat === 'off' ? 'text-muted-foreground' : 'text-primary')}
aria-label={t(repeatLabel)}
disabled={none}
onClick={cycleRepeat}

View file

@ -1,6 +1,6 @@
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Outlet, ScrollRestoration, useLocation } from 'react-router-dom'
import { Outlet, useLocation } from 'react-router-dom'
import SearchBox from '@/components/SearchBox'
import { useRadioRefill } from '@/player/radio'
import { usePlayerEngine } from '@/player/usePlayer'
@ -8,7 +8,6 @@ import UpdateNotice from '@/pwa/UpdateNotice'
import PhoneTabs from './PhoneTabs'
import PlayerBar from './PlayerBar'
import Sidebar from './Sidebar'
import { useBackClosesPlayer } from './useBackClosesPlayer'
/** The frame of the app: the sidebar, the page, and the player bar. */
export default function Shell() {
@ -18,9 +17,8 @@ export default function Shell() {
const searching = useLocation().pathname.startsWith('/search')
usePlayerEngine()
useRadioRefill()
useBackClosesPlayer()
return (
<div className="flex min-h-dvh flex-col bg-background text-foreground">
<div className="flex min-h-screen flex-col bg-background text-foreground">
{/* The first stop of the Tab key: it jumps over the sidebar. It moves the focus itself, so the address does not change. */}
<a
href="#main"
@ -54,8 +52,6 @@ export default function Shell() {
<PhoneTabs />
</div>
<UpdateNotice />
{/* A new page starts at its top, and back goes to where the list was. */}
<ScrollRestoration />
</div>
)
}

View file

@ -1,81 +0,0 @@
import { act, render } from '@testing-library/react'
import { useEffect } from 'react'
import { MemoryRouter, useLocation, useNavigate, type Location, type NavigateFunction } from 'react-router-dom'
import { beforeEach, expect, test } from 'vitest'
import { useNowPlayingUi } from '@/player/ui'
import { useBackClosesPlayer } from './useBackClosesPlayer'
const seen = {} as { where: Location; go: NavigateFunction }
function Probe() {
useBackClosesPlayer()
const where = useLocation()
const go = useNavigate()
useEffect(() => {
seen.where = where
seen.go = go
})
return null
}
function mount(initial: Parameters<typeof MemoryRouter>[0]['initialEntries'] = ['/albums/1']) {
render(
<MemoryRouter initialEntries={initial}>
<Probe />
</MemoryRouter>,
)
}
beforeEach(() => useNowPlayingUi.setState({ open: false }))
test('opening the full-screen player adds a place in the history, on the same page', () => {
mount()
act(() => useNowPlayingUi.getState().setOpen(true))
expect(seen.where.pathname).toBe('/albums/1')
expect(seen.where.state).toEqual({ player: true })
expect(useNowPlayingUi.getState().open).toBe(true)
})
test('back closes the full-screen player and stays on the page', () => {
mount()
act(() => useNowPlayingUi.getState().setOpen(true))
act(() => void seen.go(-1))
expect(useNowPlayingUi.getState().open).toBe(false)
expect(seen.where.pathname).toBe('/albums/1')
expect(seen.where.state).toBeNull()
})
test('closing the player with its own button takes the place out of the history again', () => {
mount()
act(() => useNowPlayingUi.getState().setOpen(true))
act(() => useNowPlayingUi.getState().setOpen(false))
expect(seen.where.state).toBeNull()
expect(seen.where.pathname).toBe('/albums/1')
// One more back leaves the page, it does not land on a ghost of the player.
act(() => void seen.go(-1))
expect(useNowPlayingUi.getState().open).toBe(false)
})
test('following a link while the player is open closes it and goes there', () => {
mount()
act(() => useNowPlayingUi.getState().setOpen(true))
act(() => void seen.go('/artists/5'))
expect(useNowPlayingUi.getState().open).toBe(false)
expect(seen.where.pathname).toBe('/artists/5')
})
test('a reload on the player place does not open it, and does not leave a ghost in the history', () => {
mount([{ pathname: '/albums/1', state: { player: true } }])
expect(useNowPlayingUi.getState().open).toBe(false)
expect(seen.where.pathname).toBe('/albums/1')
expect(seen.where.state).toBeNull()
})
test('the player can be opened again after it was closed by back', () => {
mount()
act(() => useNowPlayingUi.getState().setOpen(true))
act(() => void seen.go(-1))
act(() => useNowPlayingUi.getState().setOpen(true))
expect(useNowPlayingUi.getState().open).toBe(true)
expect(seen.where.state).toEqual({ player: true })
})

View file

@ -1,41 +0,0 @@
import { useEffect, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useNowPlayingUi } from '@/player/ui'
/**
* Makes the back button (on a phone, the back gesture) close the full-screen player instead of leaving the page under it.
*
* Opening the player adds one place to the history, on the same page, marked in the state of the location. Back then
* only takes that place away, and this closes the player. Closing it with its own button takes the place out again, and
* following a link inside it closes it. A place with the mark that nobody opened (a reload, or back from the page that was
* opened from the player) is cleaned in place: the player never opens by itself.
*/
export function useBackClosesPlayer() {
const open = useNowPlayingUi((s) => s.open)
const setOpen = useNowPlayingUi((s) => s.setOpen)
const location = useLocation()
const navigate = useNavigate()
const marked = (location.state as { player?: boolean } | null)?.player === true
// True from the moment this hook added the place until it is gone.
const added = useRef(false)
useEffect(() => {
if (!open && !marked) {
added.current = false
} else if (open && !marked && !added.current) {
added.current = true
navigate(location, { state: { player: true } })
} else if (open && !marked) {
// The place is gone and the player is still open: back, or a link, took us away.
added.current = false
setOpen(false)
} else if (!open && marked) {
if (added.current) {
added.current = false
navigate(-1)
} else {
navigate(location, { replace: true, state: null })
}
}
}, [open, marked, location, navigate, setOpen])
}

Some files were not shown because too many files have changed in this diff Show more