From 77d60664bb7c150d7d3e48bbeab40cf0ec513324 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 11:38:10 +0100 Subject: [PATCH] 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 --- web/src/api/catalog.test.tsx | 16 +++ web/src/api/catalog.ts | 29 +++-- web/src/components/Section.tsx | 11 ++ web/src/i18n/locales/en.json | 7 ++ web/src/i18n/locales/it.json | 7 ++ web/src/pages/ArtistPage.tsx | 3 +- web/src/pages/ArtistSections.tsx | 12 +- web/src/pages/SearchPage.test.tsx | 176 ++++++++++++++++++++++++++++++ web/src/pages/SearchPage.tsx | 108 +++++++++++++++++- 9 files changed, 347 insertions(+), 22 deletions(-) create mode 100644 web/src/components/Section.tsx create mode 100644 web/src/pages/SearchPage.test.tsx diff --git a/web/src/api/catalog.test.tsx b/web/src/api/catalog.test.tsx index 0aba465..5f9a8e2 100644 --- a/web/src/api/catalog.test.tsx +++ b/web/src/api/catalog.test.tsx @@ -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() }) diff --git a/web/src/api/catalog.ts b/web/src/api/catalog.ts index 2617a6a..5cfe6ec 100644 --- a/web/src/api/catalog.ts +++ b/web/src/api/catalog.ts @@ -17,12 +17,21 @@ const PAGE_SIZE = 50 type Params = Record +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(path: string, params: Params) { +function usePagedList(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>(path, { ...params, limit: PAGE_SIZE, offset: pageParam }), + queryFn: ({ pageParam }) => api.get>(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(path: string, params: Params) { }) } -export function useArtistList(q?: string) { - return usePagedList('/artists', { q: q || undefined }) +export function useArtistList(q?: string, list: ListOptions = {}) { + return usePagedList('/artists', { q: q || undefined }, list) } -export function useAlbumList(opts: { q?: string; artistId?: number } = {}) { - return usePagedList('/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('/albums', { q: q || undefined, artist_id: artistId }, list) } -export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } = {}) { - return usePagedList('/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('/tracks', { q: q || undefined, artist_id: artistId, album_id: albumId }, list) } export function useArtist(id: number) { diff --git a/web/src/components/Section.tsx b/web/src/components/Section.tsx new file mode 100644 index 0000000..225f527 --- /dev/null +++ b/web/src/components/Section.tsx @@ -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 ( +
+

{title}

+ {children} +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index e63efd3..70d1242 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 0ac2c78..c9445e1 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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", diff --git a/web/src/pages/ArtistPage.tsx b/web/src/pages/ArtistPage.tsx index 4291ee8..7f8881f 100644 --- a/web/src/pages/ArtistPage.tsx +++ b/web/src/pages/ArtistPage.tsx @@ -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() diff --git a/web/src/pages/ArtistSections.tsx b/web/src/pages/ArtistSections.tsx index b726511..69fab3f 100644 --- a/web/src/pages/ArtistSections.tsx +++ b/web/src/pages/ArtistSections.tsx @@ -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 ( -
-

{title}

- {children} -
- ) -} - export function About({ artistId }: { artistId: number }) { const { t } = useTranslation() const query = useArtistDescription(artistId) diff --git a/web/src/pages/SearchPage.test.tsx b/web/src/pages/SearchPage.test.tsx new file mode 100644 index 0000000..31e16b1 --- /dev/null +++ b/web/src/pages/SearchPage.test.tsx @@ -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 {useLocation().pathname + useLocation().search} +} + +function renderSearch(path = '/search') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + + + } /> + + + , + ) +} + +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() +}) diff --git a/web/src/pages/SearchPage.tsx b/web/src/pages/SearchPage.tsx index 434868d..462ec86 100644 --- a/web/src/pages/SearchPage.tsx +++ b/web/src/pages/SearchPage.tsx @@ -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

{t('nav.search')}

+ 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) => ( + + {t('search.seeAll')} + + ) + + return ( +
+

{t('nav.search')}

+
+ + setText(e.target.value)} + className="h-12 rounded-full px-5" + /> +
+ + {!enabled ? ( + {t('search.hint')} + ) : failed ? ( + all.forEach((query) => query.refetch())} /> + ) : all.some((query) => query.isPending) ? ( + + ) : all.every((query) => (query.data?.items.length ?? 0) === 0) ? ( + {t('search.nothingFound', { q })} + ) : ( + <> + {(artists.data?.items.length ?? 0) > 0 && ( +
+
    + {artists.data!.items.map((artist) => ( +
  • + +
  • + ))} +
+ {artists.data!.total > artists.data!.items.length && seeAll('artists')} +
+ )} + {(albums.data?.items.length ?? 0) > 0 && ( +
+
    + {albums.data!.items.map((album) => ( +
  • + +
  • + ))} +
+ {albums.data!.total > albums.data!.items.length && seeAll('albums')} +
+ )} + {(songs.data?.items.length ?? 0) > 0 && ( +
+ + {songs.data!.total > songs.data!.items.length && seeAll('songs')} +
+ )} + + )} +
+ ) }