feat(web): make Sonda feel like an app on a phone

A review of the phone experience (the issue) found a desktop page made
smaller. What changes:

feat:
- The player bar is one row on a phone (cover, title, play and next, a thin
  line of progress) and is not there while nothing plays. A tap or a swipe up
  on it opens the full-screen player.
- The Back gesture closes the full-screen player instead of leaving the page
  under it; a swipe down closes it too. The full queue is listed on a phone.
- The queue is kept in the browser: a reload, or a tab that Android throws
  away, comes back paused on the same song at the same second. It belongs to
  the person signed in and is forgotten on sign-out.
- Tabs have icons; the page starts at its top on a new route and back goes to
  where the list was; a swipe on the page no longer reloads it.

fix:
- The player now knows when the system pauses the audio (another app, a
  headset), so the button and the lock screen no longer say it plays.
- The lock screen has a working seek bar and the right play/pause state.
- The player bar was not hidden by max-sm:hidden: its grid rules were outside
  the Tailwind layers and won. They are in the components layer now.
- Song rows give the title the room on a phone (no number column).
- The album header is centred and the greeting is smaller on a phone; recent
  songs on Home show the artist.
- Thumbnails ask for the small cover (300 px) and not the 1000 px one.
- Pages use dvh, the viewport covers the notch, and the tabs keep clear of
  the gesture bar; the update notice no longer sits on the bar.
- No grey tap flash, no double-tap delay, no image menu on a long press.
This commit is contained in:
tgiachi 2026-11-16 17:38:58 +01:00
commit 75a7898c68
36 changed files with 892 additions and 91 deletions

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" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<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-screen bg-background" />
return <div role="status" aria-label={t('common.loading')} className="min-h-dvh 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-screen items-center justify-center bg-background p-4">
<main className="flex min-h-dvh 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')
expect(img.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small')
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?access_token=tok1')
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small&access_token=tok1')
act(() => sessionStore.setState({ accessToken: 'tok2' }))
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?access_token=tok2')
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/albums/12/cover?size=small&access_token=tok2')
})
test('a cover that fails to load is replaced by the placeholder', () => {
@ -116,3 +116,10 @@ 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,10 +19,14 @@ 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
const src = albumId === null ? null : mediaUrl(coverPath(friend, albumId))
// 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))
// 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
@ -36,7 +40,16 @@ 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" className="size-full object-cover" onError={() => setFailed(src)} />
<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)}
/>
) : (
<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-5xl')
expect(screen.getByRole('heading', { level: 1 }).className).toContain('text-[2.5rem]')
})

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-5xl leading-none sm:text-7xl' : 'text-4xl leading-tight sm:text-5xl', className)}>
<h1 className={cn('font-extrabold tracking-tight', large ? 'text-[2.5rem] 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-screen bg-background" />
return <div role="status" aria-label={t('common.loading')} className="min-h-dvh bg-background" />
}

View file

@ -29,11 +29,12 @@ 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-[2.5rem_minmax(0,1fr)_4.5rem] items-center gap-3 rounded-lg px-4 text-left',
'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',
disabled && 'opacity-60',
)}
>
<span className={cn('tabular-nums', active ? 'font-bold text-primary' : 'text-muted-foreground')}>
{/* 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')}>
{track.track_no > 0 ? track.track_no : index + 1}
</span>
<span className="min-w-0">

View file

@ -16,6 +16,7 @@ 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'
@ -23,7 +24,9 @@ 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 }) {
@ -69,11 +72,15 @@ export default function NowPlaying() {
if (open && !track) setOpen(false)
}, [open, track, setOpen])
const upNext = queue.slice(index + 1, index + 1 + UP_NEXT)
// 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)
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"
>
@ -158,14 +165,15 @@ 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) => (
<TrackRow
key={`${next.id}-${k}`}
track={next}
index={index + 1 + k}
onPlay={() => jumpTo(index + 1 + k)}
/>
))}
{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>
)
})}
</section>
)}

View file

@ -80,3 +80,12 @@ 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,3 +1,4 @@
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'
@ -20,31 +21,32 @@ export default function PhoneTabs() {
const { t } = useTranslation()
const { pathname } = useLocation()
const hasFriends = (useFriends().data?.length ?? 0) > 0
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) },
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) },
]
return (
<nav aria-label={t('nav.tabs')} className="flex border-t border-border bg-background sm:hidden">
<nav aria-label={t('nav.tabs')} className="flex border-t border-border bg-background pb-[env(safe-area-inset-bottom)] 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.5 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 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 ? ('friend' in tab ? 'bg-friend' : 'bg-primary') : 'bg-transparent')}
className={cn('h-[3px] w-6', tab.current ? (tab.friend ? 'bg-friend' : 'bg-primary') : 'bg-transparent')}
/>
<tab.icon aria-hidden="true" className="size-5" />
<span>{tab.label}</span>
</Link>
))}

View file

@ -112,6 +112,15 @@ 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>
@ -264,8 +273,10 @@ 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' })
expect(within(upNext).getAllByRole('button')).toHaveLength(3)
expect(within(upNext).queryByText('Song 5')).not.toBeInTheDocument()
// 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()
await userEvent.click(within(upNext).getByRole('button', { name: /Song 3/ }))
expect(usePlayer.getState().index).toBe(2)
})
@ -534,3 +545,92 @@ 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,7 +12,9 @@ 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'
@ -40,7 +42,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">
<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">
<span>{formatTime(track ? positionMs : 0)}</span>
<div className="flex-1">
<Scrubber
@ -57,18 +59,40 @@ function PlayerSeek({ track }: { track: QueuedTrack | null }) {
)
}
/** The bar at the bottom of every page: what is playing, the controls and the position. */
/** 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.
*/
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="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"
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',
)}
>
<PhoneProgress track={track} />
<div className="player-info flex min-w-0 items-center gap-3">
{track ? (
<>
@ -102,7 +126,7 @@ export default function PlayerBar() {
</div>
<div className="player-controls flex justify-end sm:justify-center">
<PlayerControls />
<PlayerControls phoneMini />
</div>
<PlayerSeek track={track} />

View file

@ -5,7 +5,16 @@ 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, className }: { large?: boolean; className?: string }) {
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
}) {
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.
@ -19,13 +28,14 @@ export default function PlayerControls({ large = false, className }: { large?: b
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, shuffle ? 'text-primary' : 'text-muted-foreground')}
className={cn(small, extra, shuffle ? 'text-primary' : 'text-muted-foreground')}
aria-label={t('player.shuffle')}
aria-pressed={shuffle}
disabled={none}
@ -33,7 +43,7 @@ export default function PlayerControls({ large = false, className }: { large?: b
>
<Shuffle />
</Button>
<Button variant="ghost" className={small} aria-label={t('player.previous')} disabled={none} onClick={prev}>
<Button variant="ghost" className={cn(small, extra)} aria-label={t('player.previous')} disabled={none} onClick={prev}>
<SkipBack />
</Button>
<Button
@ -53,7 +63,7 @@ export default function PlayerControls({ large = false, className }: { large?: b
</Button>
<Button
variant="ghost"
className={cn(small, repeat === 'off' ? 'text-muted-foreground' : 'text-primary')}
className={cn(small, extra, 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, useLocation } from 'react-router-dom'
import { Outlet, ScrollRestoration, useLocation } from 'react-router-dom'
import SearchBox from '@/components/SearchBox'
import { useRadioRefill } from '@/player/radio'
import { usePlayerEngine } from '@/player/usePlayer'
@ -8,6 +8,7 @@ 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() {
@ -17,8 +18,9 @@ export default function Shell() {
const searching = useLocation().pathname.startsWith('/search')
usePlayerEngine()
useRadioRefill()
useBackClosesPlayer()
return (
<div className="flex min-h-screen flex-col bg-background text-foreground">
<div className="flex min-h-dvh 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"
@ -52,6 +54,8 @@ 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

@ -0,0 +1,81 @@
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

@ -0,0 +1,41 @@
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])
}

View file

@ -66,29 +66,51 @@
}
html {
@apply font-sans;
/* Pulling the page down at its top must not reload it, and a song is not lost to a stray swipe. */
overscroll-behavior-y: contain;
}
/* A finger: no grey flash on a tap, no wait for a double tap, and a tap on a control never selects text. */
a,
button,
label,
summary,
select,
[role='button'],
[role='tab'] {
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
nav a,
nav button,
footer button,
[role='button'] {
user-select: none;
-webkit-touch-callout: none;
}
}
/*
* The player bar. On a phone it is two lines, so that it leaves the page its room: what is playing and the controls on
* the first, the position on the second, and no volume or full-screen (the phone has its own volume, and the cover opens
* the full player). From 640px up the words are on the left, the controls and the position in the middle, the extras
* on the right.
* The player bar. On a phone it is one row, so that it leaves the page its room: what is playing, play and next, and a
* thin line of progress along its top edge (the rest is in the full-screen player, which the cover and the title open;
* the phone has its own volume). While nothing plays it is not there. From 640px up the words are on the left, the
* controls and the position in the middle, the extras on the right.
*/
.player-bar {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-areas: 'info controls' 'seek seek';
align-items: center;
}
.player-info { grid-area: info; }
.player-controls { grid-area: controls; }
.player-seek { grid-area: seek; }
.player-extras { grid-area: extras; }
@media (min-width: 640px) {
@layer components {
.player-bar {
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr) minmax(0, 1fr);
grid-template-areas: 'info controls extras' 'info seek extras';
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-areas: 'info controls';
align-items: center;
}
.player-info { grid-area: info; }
.player-controls { grid-area: controls; }
.player-seek { grid-area: seek; }
.player-extras { grid-area: extras; }
@media (min-width: 640px) {
.player-bar {
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr) minmax(0, 1fr);
grid-template-areas: 'info controls extras' 'info seek extras';
}
}
}

41
web/src/lib/useSwipe.ts Normal file
View file

@ -0,0 +1,41 @@
import { useRef, type TouchEvent } from 'react'
/**
* Handlers for a vertical swipe with a finger: spread them on an element. A swipe counts when it is long enough and goes
* more up or down than sideways, so that a scroll, a tap or a slide of a slider does not trigger it. The browser still
* scrolls as it always did: this only looks at where the finger started and where it left.
*/
export function useSwipe({
onUp,
onDown,
distance = 80,
allow,
}: {
onUp?: () => void
onDown?: () => void
distance?: number
/** Asked when the finger goes down: false ignores this swipe (the page under the finger is scrolled, say). */
allow?: (e: TouchEvent<HTMLElement>) => boolean
}) {
const start = useRef<{ x: number; y: number } | null>(null)
return {
onTouchStart(e: TouchEvent<HTMLElement>) {
const t = e.touches[0]
start.current = t && (allow?.(e) ?? true) ? { x: t.clientX, y: t.clientY } : null
},
onTouchEnd(e: TouchEvent<HTMLElement>) {
const from = start.current
start.current = null
const t = e.changedTouches[0]
if (!from || !t) return
const dy = t.clientY - from.y
const dx = t.clientX - from.x
if (Math.abs(dx) > Math.abs(dy) / 1.5) return
if (dy >= distance) onDown?.()
else if (dy <= -distance) onUp?.()
},
onTouchCancel() {
start.current = null
},
}
}

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