feat(web): search

- search page with a 250 ms pause after typing, the text kept in the address, and at most 200 characters sent
- artists, albums and songs in three groups of six, each with a link to the full list
- accents and capitals are left to the server, which ignores them
- list hooks can take a smaller page size and stay switched off until there is something to ask
This commit is contained in:
tgiachi 2026-11-12 11:38:10 +01:00
commit 77d60664bb
9 changed files with 347 additions and 22 deletions

View file

@ -58,6 +58,22 @@ test('no search text sends no q', async () => {
expect(calls[0].url.searchParams.has('q')).toBe(false)
})
test('a list can ask for a smaller page', async () => {
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(10, artist) })
const { result } = renderHook(() => useArtistList('x', { pageSize: 6 }), { wrapper: createWrapper() })
await waitFor(() => expect(result.current.data?.items).toHaveLength(6))
expect(calls[0].url.searchParams.get('limit')).toBe('6')
expect(result.current.hasNextPage).toBe(true)
})
test('a list that is switched off asks for nothing', async () => {
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(1, artist) })
const { result } = renderHook(() => useArtistList('x', { enabled: false }), { wrapper: createWrapper() })
await new Promise((r) => setTimeout(r, 50))
expect(calls).toHaveLength(0)
expect(result.current.data).toBeUndefined()
})
test('albums can be limited to an artist', async () => {
const { calls } = mockFetch({ 'GET /api/v1/albums': paged(1, (i) => ({ id: i + 1, title: 'A' })) })
const { result } = renderHook(() => useAlbumList({ artistId: 7 }), { wrapper: createWrapper() })

View file

@ -17,12 +17,21 @@ const PAGE_SIZE = 50
type Params = Record<string, string | number | undefined>
export interface ListOptions {
/** How many items one request asks for (default 50). */
pageSize?: number
/** False keeps the list from asking for anything yet (default true). */
enabled?: boolean
}
/** A list the server pages by `limit` and `offset`, read one page after the other. */
function usePagedList<T>(path: string, params: Params) {
function usePagedList<T>(path: string, params: Params, opts: ListOptions = {}) {
const pageSize = opts.pageSize ?? PAGE_SIZE
return useInfiniteQuery({
queryKey: [path, params],
queryKey: [path, params, pageSize],
enabled: opts.enabled ?? true,
initialPageParam: 0,
queryFn: ({ pageParam }) => api.get<Page<T>>(path, { ...params, limit: PAGE_SIZE, offset: pageParam }),
queryFn: ({ pageParam }) => api.get<Page<T>>(path, { ...params, limit: pageSize, offset: pageParam }),
getNextPageParam: (last) => {
const next = last.offset + last.items.length
return last.items.length > 0 && next < last.total ? next : undefined
@ -31,16 +40,18 @@ function usePagedList<T>(path: string, params: Params) {
})
}
export function useArtistList(q?: string) {
return usePagedList<Artist>('/artists', { q: q || undefined })
export function useArtistList(q?: string, list: ListOptions = {}) {
return usePagedList<Artist>('/artists', { q: q || undefined }, list)
}
export function useAlbumList(opts: { q?: string; artistId?: number } = {}) {
return usePagedList<Album>('/albums', { q: opts.q || undefined, artist_id: opts.artistId })
export function useAlbumList(opts: { q?: string; artistId?: number } & ListOptions = {}) {
const { q, artistId, ...list } = opts
return usePagedList<Album>('/albums', { q: q || undefined, artist_id: artistId }, list)
}
export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } = {}) {
return usePagedList<Track>('/tracks', { q: opts.q || undefined, artist_id: opts.artistId, album_id: opts.albumId })
export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } & ListOptions = {}) {
const { q, artistId, albumId, ...list } = opts
return usePagedList<Track>('/tracks', { q: q || undefined, artist_id: artistId, album_id: albumId }, list)
}
export function useArtist(id: number) {

View file

@ -0,0 +1,11 @@
import type { ReactNode } from 'react'
/** A titled part of a page. Its label makes it a landmark ("About", "Tags", "Artists"...). */
export default function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section aria-label={title} className="flex flex-col gap-3">
<h2 className="text-xl font-bold">{title}</h2>
{children}
</section>
)
}

View file

@ -38,6 +38,13 @@
"queue": "Queue",
"nowPlaying": "Now playing"
},
"search": {
"label": "Search your library",
"placeholder": "Artists, albums and songs",
"hint": "Type to search artists, albums and songs.",
"nothingFound": "Nothing found for “{{q}}”.",
"seeAll": "See all"
},
"provider": {
"wikipedia": "Wikipedia",
"lastfm": "Last.fm",

View file

@ -38,6 +38,13 @@
"queue": "Coda",
"nowPlaying": "In riproduzione"
},
"search": {
"label": "Cerca nella libreria",
"placeholder": "Artisti, album e brani",
"hint": "Scrivi per cercare artisti, album e brani.",
"nothingFound": "Non ho trovato niente per “{{q}}”.",
"seeAll": "Mostra tutto"
},
"provider": {
"wikipedia": "Wikipedia",
"lastfm": "Last.fm",

View file

@ -10,7 +10,8 @@ import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import TrackList from '@/components/TrackList'
import { Button } from '@/components/ui/button'
import { usePlayer } from '@/player/store'
import { About, PhotoCredit, Section, Similar, Tags } from './ArtistSections'
import Section from '@/components/Section'
import { About, PhotoCredit, Similar, Tags } from './ArtistSections'
export default function ArtistPage() {
const { t } = useTranslation()

View file

@ -1,23 +1,13 @@
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import { useArtistDescription, useArtistImageCredit, useArtistTags, useSimilarArtists } from '@/api/providers'
import Attribution, { ExternalLink } from '@/components/Attribution'
import ProviderMessage from '@/components/ProviderMessage'
import Section from '@/components/Section'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
const MAX_TAGS = 10
/** A titled part of the artist page. Its label makes it a landmark ("About", "Tags"...). */
export function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section aria-label={title} className="flex flex-col gap-3">
<h2 className="text-xl font-bold">{title}</h2>
{children}
</section>
)
}
export function About({ artistId }: { artistId: number }) {
const { t } = useTranslation()
const query = useArtistDescription(artistId)

View file

@ -0,0 +1,176 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, within } 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 { usePlayer } from '@/player/store'
import { mockFetch, type MockRoutes } from '@/test/mockFetch'
import SearchPage from './SearchPage'
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))
const page = (items: object[], total = items.length) => ({ items, total, limit: 6, offset: 0 })
const artist = (i: number) => ({ id: i + 1, name: `Artist ${i}`, album_count: 1, track_count: 3 })
const album = (i: number) => ({ id: i + 20, title: `Album ${i}`, artist: { id: 1, name: 'Björk' }, track_count: 9, duration_ms: 1 })
const song = (i: number) => ({
id: i + 100,
title: `Song ${i}`,
duration_ms: 200_000,
track_no: i + 1,
disc_no: 1,
album: null,
artists: [{ id: 1, name: 'Björk' }],
format: 'mp3',
})
function routes(over: MockRoutes = {}): MockRoutes {
return {
'GET /api/v1/artists': () => page(Array.from({ length: 6 }, (_, i) => artist(i)), 10),
'GET /api/v1/albums': () => page([album(0), album(1)]),
'GET /api/v1/tracks': () => page([song(0), song(1)]),
...over,
}
}
function Location() {
return <output data-testid="location">{useLocation().pathname + useLocation().search}</output>
}
function renderSearch(path = '/search') {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[path]}>
<Location />
<Routes>
<Route path="/search" element={<SearchPage />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
}
const box = () => screen.getByRole('searchbox', { name: 'Search your library' })
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } })
usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0 })
})
test('typing sends one request per list, once, with the text as it was typed', async () => {
const { calls } = mockFetch(routes())
renderSearch()
await userEvent.type(box(), 'bjork')
expect(await screen.findByRole('region', { name: 'Artists' })).toBeInTheDocument()
for (const key of ['GET /api/v1/artists', 'GET /api/v1/albums', 'GET /api/v1/tracks']) {
const sent = calls.filter((c) => c.key === key)
expect(sent).toHaveLength(1)
expect(sent[0].url.searchParams.get('q')).toBe('bjork')
expect(sent[0].url.searchParams.get('limit')).toBe('6')
}
})
test('the results come in three groups', async () => {
mockFetch(routes())
renderSearch()
await userEvent.type(box(), 'bjork')
const artists = await screen.findByRole('region', { name: 'Artists' })
const albums = await screen.findByRole('region', { name: 'Albums' })
const songs = await screen.findByRole('region', { name: 'Songs' })
expect(within(artists).getAllByRole('link', { name: /Artist \d/ })).toHaveLength(6)
expect(within(albums).getAllByRole('link', { name: /Album \d/ })).toHaveLength(2)
expect(within(songs).getAllByRole('button', { name: /Song \d/ })).toHaveLength(2)
})
test('a group with more results than shown links to the full list with the same search', async () => {
mockFetch(routes())
renderSearch()
await userEvent.type(box(), 'bjork')
const artists = await screen.findByRole('region', { name: 'Artists' })
expect(within(artists).getByRole('link', { name: 'See all' })).toHaveAttribute('href', '/artists?q=bjork')
const albums = await screen.findByRole('region', { name: 'Albums' })
expect(within(albums).queryByRole('link', { name: 'See all' })).not.toBeInTheDocument()
})
test('a click on a found song plays it', async () => {
mockFetch(routes())
renderSearch()
await userEvent.type(box(), 'bjork')
await userEvent.click(await screen.findByRole('button', { name: /Song 1/ }))
expect(usePlayer.getState().queue.map((t) => t.id)).toEqual([100, 101])
expect(usePlayer.getState().index).toBe(1)
})
test('with nothing typed there is a hint and no request', async () => {
const { calls } = mockFetch(routes())
renderSearch()
await wait(350)
expect(screen.getByText('Type to search artists, albums and songs.')).toBeInTheDocument()
expect(calls).toHaveLength(0)
})
test('text that is only spaces is not a search', async () => {
const { calls } = mockFetch(routes())
renderSearch()
await userEvent.type(box(), ' ')
await wait(350)
expect(calls).toHaveLength(0)
})
test('a search in the address fills the box and runs at once', async () => {
const { calls } = mockFetch(routes())
renderSearch('/search?q=x')
expect(box()).toHaveValue('x')
expect(await screen.findByRole('region', { name: 'Artists' })).toBeInTheDocument()
expect(calls[0].url.searchParams.get('q')).toBe('x')
})
test('the address follows what was typed', async () => {
mockFetch(routes())
renderSearch()
await userEvent.type(box(), 'bjork')
await screen.findByRole('region', { name: 'Artists' })
expect(screen.getByTestId('location')).toHaveTextContent('/search?q=bjork')
await userEvent.clear(box())
await wait(350)
expect(screen.getByTestId('location')).toHaveTextContent(/^\/search$/)
})
test('a search longer than the server accepts is cut to 200 characters', async () => {
const { calls } = mockFetch(routes())
renderSearch()
fireEvent.change(box(), { target: { value: 'a'.repeat(201) } })
await screen.findByRole('region', { name: 'Artists' })
expect(calls[0].url.searchParams.get('q')).toHaveLength(200)
})
test('accents and capitals are left to the server', async () => {
const { calls } = mockFetch(routes())
renderSearch()
fireEvent.change(box(), { target: { value: 'BJÖRK' } })
await screen.findByRole('region', { name: 'Artists' })
expect(calls[0].url.searchParams.get('q')).toBe('BJÖRK')
})
test('when nothing matches it says so', async () => {
mockFetch(routes({
'GET /api/v1/artists': () => page([]),
'GET /api/v1/albums': () => page([]),
'GET /api/v1/tracks': () => page([]),
}))
renderSearch()
await userEvent.type(box(), 'zzz')
expect(await screen.findByText('Nothing found for “zzz”.')).toBeInTheDocument()
})
test('a group with no results is left out', async () => {
mockFetch(routes({ 'GET /api/v1/albums': () => page([]) }))
renderSearch()
await userEvent.type(box(), 'bjork')
await screen.findByRole('region', { name: 'Artists' })
expect(screen.queryByRole('region', { name: 'Albums' })).not.toBeInTheDocument()
})

View file

@ -1,6 +1,112 @@
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useSearchParams } from 'react-router-dom'
import { useAlbumList, useArtistList, useTrackList } from '@/api/catalog'
import { AlbumCard, ArtistCard, CARD_GRID } from '@/components/cards'
import Section from '@/components/Section'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import TrackList from '@/components/TrackList'
import { Input } from '@/components/ui/input'
/** Wait this long after the last keystroke before asking the server. */
const DEBOUNCE_MS = 250
/** What the server accepts as search text. */
const MAX_QUERY_LENGTH = 200
/** How many of each kind are shown; the rest is one click away. */
const SHOWN = 6
export default function SearchPage() {
const { t } = useTranslation()
return <h1 className="text-3xl font-extrabold tracking-tight">{t('nav.search')}</h1>
const [params, setParams] = useSearchParams()
const [text, setText] = useState(params.get('q') ?? '')
const [typed, setTyped] = useState(text)
useEffect(() => {
const timer = setTimeout(() => setTyped(text), DEBOUNCE_MS)
return () => clearTimeout(timer)
}, [text])
// Searching by spaces is not searching; the server takes at most 200 characters.
const q = Array.from(typed.trim()).slice(0, MAX_QUERY_LENGTH).join('')
const enabled = q !== ''
useEffect(() => {
setParams(q ? { q } : {}, { replace: true })
}, [q, setParams])
const list = { pageSize: SHOWN, enabled }
const artists = useArtistList(q, list)
const albums = useAlbumList({ q, ...list })
const songs = useTrackList({ q, ...list })
const all = [artists, albums, songs]
const failed = all.find((query) => query.isError)
const seeAll = (page: string) => (
<Link to={`/${page}?q=${encodeURIComponent(q)}`} className="self-start font-semibold text-primary hover:underline">
{t('search.seeAll')}
</Link>
)
return (
<div className="flex flex-col gap-8">
<h1 className="text-3xl font-extrabold tracking-tight">{t('nav.search')}</h1>
<div className="max-w-xl">
<label htmlFor="search" className="sr-only">
{t('search.label')}
</label>
<Input
id="search"
type="search"
value={text}
placeholder={t('search.placeholder')}
autoComplete="off"
onChange={(e) => setText(e.target.value)}
className="h-12 rounded-full px-5"
/>
</div>
{!enabled ? (
<EmptyMessage>{t('search.hint')}</EmptyMessage>
) : failed ? (
<ErrorMessage error={failed.error} onRetry={() => all.forEach((query) => query.refetch())} />
) : all.some((query) => query.isPending) ? (
<Loading />
) : all.every((query) => (query.data?.items.length ?? 0) === 0) ? (
<EmptyMessage>{t('search.nothingFound', { q })}</EmptyMessage>
) : (
<>
{(artists.data?.items.length ?? 0) > 0 && (
<Section title={t('nav.artists')}>
<ul className={CARD_GRID}>
{artists.data!.items.map((artist) => (
<li key={artist.id}>
<ArtistCard artist={artist} />
</li>
))}
</ul>
{artists.data!.total > artists.data!.items.length && seeAll('artists')}
</Section>
)}
{(albums.data?.items.length ?? 0) > 0 && (
<Section title={t('nav.albums')}>
<ul className={CARD_GRID}>
{albums.data!.items.map((album) => (
<li key={album.id}>
<AlbumCard album={album} />
</li>
))}
</ul>
{albums.data!.total > albums.data!.items.length && seeAll('albums')}
</Section>
)}
{(songs.data?.items.length ?? 0) > 0 && (
<Section title={t('nav.songs')}>
<TrackList tracks={songs.data!.items} />
{songs.data!.total > songs.data!.items.length && seeAll('songs')}
</Section>
)}
</>
)}
</div>
)
}