feat(web): the Discover page with its three tabs, a sidebar link and a route

The tab is kept in the address (?tab=) and moves with the arrow keys; only the open tab asks the server for its list. README now describes Discover in the web app.
This commit is contained in:
tgiachi 2026-11-12 14:11:27 +01:00
commit 88d3df9f61
8 changed files with 186 additions and 4 deletions

View file

@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
## What is not there yet
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no Discover or admin screens yet.
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no admin screens or Lidarr button yet.
## Requirements
@ -328,9 +328,9 @@ 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. 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 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. 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). Discover, the admin screens and serving the app from the binary come later.
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 Lidarr button, the admin screens and serving the app from the binary come later.
## Development

View file

@ -28,7 +28,7 @@ test('at /artists the Artists link is the current page and the others are not',
renderAt('/artists')
const nav = within(mainNav())
expect(nav.getByRole('link', { name: 'Artists' })).toHaveAttribute('aria-current', 'page')
for (const name of ['Home', 'Search', 'Albums', 'Songs', 'Settings']) {
for (const name of ['Home', 'Search', 'Discover', 'Albums', 'Songs', 'Settings']) {
expect(nav.getByRole('link', { name })).not.toHaveAttribute('aria-current')
}
})
@ -59,6 +59,7 @@ test.each([
['/artists', 'Artists'],
['/albums', 'Albums'],
['/songs', 'Songs'],
['/discover', 'Discover'],
['/settings', 'Settings'],
])('the route %s opens a page headed %s', (path, heading) => {
renderAt(path)

View file

@ -5,6 +5,7 @@ import { cn } from '@/lib/utils'
const LINKS = [
{ to: '/', key: 'nav.home', end: true },
{ to: '/search', key: 'nav.search', end: false },
{ to: '/discover', key: 'nav.discover', end: false },
{ to: '/artists', key: 'nav.artists', end: false },
{ to: '/albums', key: 'nav.albums', end: false },
{ to: '/songs', key: 'nav.songs', end: false },

View file

@ -7,6 +7,7 @@
"main": "Main",
"home": "Home",
"search": "Search",
"discover": "Discover",
"artists": "Artists",
"albums": "Albums",
"songs": "Songs",
@ -60,6 +61,12 @@
},
"discover": {
"title": "Discover",
"tabs": {
"label": "Discover sections",
"suggestions": "Suggestions",
"wishlist": "Wishlist",
"dismissed": "Not interested"
},
"score": "{{percent}}% match",
"because": "Because of {{names}}",
"inLibrary": "In your library",

View file

@ -7,6 +7,7 @@
"main": "Principale",
"home": "Home",
"search": "Cerca",
"discover": "Discover",
"artists": "Artisti",
"albums": "Album",
"songs": "Brani",
@ -60,6 +61,12 @@
},
"discover": {
"title": "Discover",
"tabs": {
"label": "Sezioni di Discover",
"suggestions": "Suggerimenti",
"wishlist": "Wishlist",
"dismissed": "Non mi interessa"
},
"score": "{{percent}}% di affinità",
"because": "Per via di {{names}}",
"inLibrary": "Nella tua libreria",

View file

@ -0,0 +1,91 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { mockFetch } from '@/test/mockFetch'
import DiscoverPage from './DiscoverPage'
const empty = { items: [], total: 0, limit: 50, offset: 0 }
function routes() {
return {
'GET /api/v1/me/settings': () => ({ discover_from_listening: false }),
'GET /api/v1/me/taste': () => ({ artists: [], tags: [] }),
'GET /api/v1/wishlist': () => empty,
'GET /api/v1/discover/dismissed': () => empty,
'GET /api/v1/discover': () => ({ provider_status: 'ok', attribution: '', from_listening: false, seeds: [], items: [] }),
}
}
function Where() {
const { pathname, search } = useLocation()
return <output data-testid="where">{pathname + search}</output>
}
function renderPage(path = '/discover') {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[path]}>
<Where />
<Routes>
<Route path="/discover" element={<DiscoverPage />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
}
const tab = (name: string) => screen.getByRole('tab', { name })
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
})
test('it opens on the suggestions', async () => {
mockFetch(routes())
renderPage()
expect(screen.getByRole('heading', { level: 1, name: 'Discover' })).toBeInTheDocument()
expect(tab('Suggestions')).toHaveAttribute('aria-selected', 'true')
expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'false')
expect(await screen.findByText('Pick an artist to start from, or let Discover start from your listening.')).toBeInTheDocument()
})
test('the address names the tab, and only that tab asks the server for its list', async () => {
const { calls } = mockFetch(routes())
renderPage('/discover?tab=wishlist')
expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'true')
expect(await screen.findByText('Nothing on your wishlist yet. Add artists from the suggestions.')).toBeInTheDocument()
expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/discover')
expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/discover/dismissed')
})
test('choosing a tab changes the address', async () => {
mockFetch(routes())
renderPage()
await userEvent.click(tab('Not interested'))
expect(screen.getByTestId('where')).toHaveTextContent('/discover?tab=dismissed')
expect(await screen.findByText('You have not dismissed any artist.')).toBeInTheDocument()
})
test('a tab that does not exist falls back to the suggestions', () => {
mockFetch(routes())
renderPage('/discover?tab=bogus')
expect(tab('Suggestions')).toHaveAttribute('aria-selected', 'true')
})
test('the arrow keys move between the tabs', async () => {
mockFetch(routes())
renderPage()
tab('Suggestions').focus()
await userEvent.keyboard('{ArrowRight}')
expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'true')
expect(tab('Wishlist')).toHaveFocus()
await userEvent.keyboard('{ArrowLeft}{ArrowLeft}')
expect(tab('Not interested')).toHaveAttribute('aria-selected', 'true')
})

View file

@ -0,0 +1,73 @@
import { useRef, type KeyboardEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router-dom'
import { cn } from '@/lib/utils'
import MarkedList from './discover/MarkedList'
import SuggestionsTab from './discover/SuggestionsTab'
const TABS = [
{ id: 'suggestions', key: 'discover.tabs.suggestions' },
{ id: 'wishlist', key: 'discover.tabs.wishlist' },
{ id: 'dismissed', key: 'discover.tabs.dismissed' },
] as const
type TabId = (typeof TABS)[number]['id']
function parse(value: string | null): TabId {
return TABS.find((tab) => tab.id === value)?.id ?? 'suggestions'
}
export default function DiscoverPage() {
const { t } = useTranslation()
const [params, setParams] = useSearchParams()
const current = parse(params.get('tab'))
const buttons = useRef<Record<string, HTMLButtonElement | null>>({})
function choose(id: TabId) {
setParams(id === 'suggestions' ? {} : { tab: id })
}
function onKeyDown(event: KeyboardEvent) {
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0
if (step === 0) return
event.preventDefault()
const at = TABS.findIndex((tab) => tab.id === current)
const next = TABS[(at + step + TABS.length) % TABS.length].id
choose(next)
buttons.current[next]?.focus()
}
return (
<div className="flex flex-col gap-6">
<h1 className="text-3xl font-extrabold tracking-tight">{t('discover.title')}</h1>
<div role="tablist" aria-label={t('discover.tabs.label')} onKeyDown={onKeyDown} className="flex flex-wrap gap-2">
{TABS.map((tab) => (
<button
key={tab.id}
ref={(el) => {
buttons.current[tab.id] = el
}}
type="button"
role="tab"
id={`tab-${tab.id}`}
aria-selected={current === tab.id}
aria-controls="discover-panel"
tabIndex={current === tab.id ? 0 : -1}
onClick={() => choose(tab.id)}
className={cn(
'min-h-11 rounded-lg px-4 font-semibold',
current === tab.id ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground',
)}
>
{t(tab.key)}
</button>
))}
</div>
<div role="tabpanel" id="discover-panel" aria-labelledby={`tab-${current}`}>
{current === 'suggestions' ? <SuggestionsTab /> : <MarkedList key={current} kind={current} />}
</div>
</div>
)
}

View file

@ -4,6 +4,7 @@ import AlbumPage from '@/pages/AlbumPage'
import AlbumsPage from '@/pages/AlbumsPage'
import ArtistPage from '@/pages/ArtistPage'
import ArtistsPage from '@/pages/ArtistsPage'
import DiscoverPage from '@/pages/DiscoverPage'
import HomePage from '@/pages/HomePage'
import NotFoundPage from '@/pages/NotFoundPage'
import SearchPage from '@/pages/SearchPage'
@ -16,6 +17,7 @@ export const routes: RouteObject[] = [
children: [
{ path: '/', element: <HomePage /> },
{ path: '/search', element: <SearchPage /> },
{ path: '/discover', element: <DiscoverPage /> },
{ path: '/artists', element: <ArtistsPage /> },
{ path: '/artists/:id', element: <ArtistPage /> },
{ path: '/albums', element: <AlbumsPage /> },