diff --git a/web/src/components/SearchBox.test.tsx b/web/src/components/SearchBox.test.tsx new file mode 100644 index 0000000..b713292 --- /dev/null +++ b/web/src/components/SearchBox.test.tsx @@ -0,0 +1,218 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, 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 SearchBox from './SearchBox' + +const page = (items: object[], total = items.length) => ({ items, total, limit: 5, 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: { id: 20, title: 'Album 0' }, + artists: [{ id: 1, name: 'Björk' }], + format: 'mp3', +}) + +function routes(over: MockRoutes = {}): MockRoutes { + return { + 'GET /api/v1/artists': () => page([artist(0), artist(1)], 9), + 'GET /api/v1/albums': () => page([album(0), album(1)]), + 'GET /api/v1/tracks': () => page([song(0), song(1)]), + ...over, + } +} + +function Location() { + const l = useLocation() + return {l.pathname + l.search} +} + +function renderBox() { + return render( + + + + + + , + ) +} + +const box = () => screen.getByRole('combobox', { name: 'Search your library' }) +const where = () => screen.getByTestId('location').textContent + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) + usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0 }) +}) + +test('with nothing typed it shows no list and asks for nothing', async () => { + const { calls } = mockFetch(routes()) + renderBox() + expect(box()).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + await new Promise((r) => setTimeout(r, 350)) + expect(calls).toHaveLength(0) +}) + +test('typing shows a few artists, albums and songs to choose from, a little each', async () => { + const { calls } = mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + const list = await screen.findByRole('listbox') + expect(box()).toHaveAttribute('aria-expanded', 'true') + expect(within(within(list).getByRole('group', { name: 'Artists' })).getAllByRole('option')).toHaveLength(2) + expect(within(within(list).getByRole('group', { name: 'Albums' })).getAllByRole('option')).toHaveLength(2) + expect(within(within(list).getByRole('group', { name: 'Songs' })).getAllByRole('option')).toHaveLength(2) + expect(within(list).getByRole('option', { name: /Album 1/ })).toHaveTextContent('Björk') + expect(within(list).getByRole('option', { name: /Song 0/ })).toHaveTextContent('Björk') + for (const [key, limit] of [['GET /api/v1/artists', '3'], ['GET /api/v1/albums', '3'], ['GET /api/v1/tracks', '5']]) { + 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(limit) + } +}) + +test('the pictures of artists are not asked for: asking makes the server look them up at a provider', async () => { + const { calls } = mockFetch(routes()) + const { container } = renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + expect(container.querySelector('img[src*="/artists/"]')).toBeNull() + expect(calls.some((c) => c.url.pathname.includes('/image'))).toBe(false) +}) + +test('the arrows move through the choices and Enter opens the one that is marked', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + await userEvent.keyboard('{ArrowDown}') + expect(box().getAttribute('aria-activedescendant')).toBe(screen.getByRole('option', { name: /Artist 0/ }).id) + expect(screen.getByRole('option', { name: /Artist 0/ })).toHaveAttribute('aria-selected', 'true') + await userEvent.keyboard('{ArrowDown}{ArrowDown}') + expect(screen.getByRole('option', { name: /Album 0/ })).toHaveAttribute('aria-selected', 'true') + await userEvent.keyboard('{ArrowUp}{ArrowUp}{Enter}') + expect(where()).toBe('/artists/1') + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() +}) + +test('a click on an album or an artist opens it', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await userEvent.click(await screen.findByRole('option', { name: /Album 1/ })) + expect(where()).toBe('/albums/21') +}) + +test('a click on a song plays it', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await userEvent.click(await screen.findByRole('option', { name: /Song 1/ })) + expect(usePlayer.getState().queue.map((t) => t.id)).toEqual([101]) + expect(usePlayer.getState().playing).toBe(true) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() +}) + +test('the last choice is all the results, and Enter with nothing marked goes there too', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + const all = await screen.findByRole('option', { name: 'See all results for “bjork”' }) + await userEvent.click(all) + expect(where()).toBe('/search?q=bjork') + + await userEvent.type(box(), '{Enter}') + expect(where()).toBe('/search?q=bjork') +}) + +test('the arrow up from the first choice goes to the last, and down from the last to none', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + await userEvent.keyboard('{ArrowUp}') + expect(screen.getByRole('option', { name: /See all results/ })).toHaveAttribute('aria-selected', 'true') + await userEvent.keyboard('{ArrowDown}') + expect(box().getAttribute('aria-activedescendant')).toBeNull() +}) + +test('Escape closes the list and keeps the text', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + await userEvent.keyboard('{Escape}') + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(box()).toHaveValue('bjork') + expect(box()).toHaveAttribute('aria-expanded', 'false') +}) + +test('a click outside closes the list, and typing opens it again', async () => { + mockFetch(routes()) + renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + await userEvent.click(document.body) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + await userEvent.type(box(), 'x') + expect(await screen.findByRole('listbox')).toBeInTheDocument() +}) + +test('with nothing found it says so, and still offers the full search', async () => { + mockFetch(routes({ 'GET /api/v1/artists': () => page([]), 'GET /api/v1/albums': () => page([]), 'GET /api/v1/tracks': () => page([]) })) + renderBox() + await userEvent.type(box(), 'zzz') + expect(await screen.findByText('Nothing matches “zzz”.')).toBeInTheDocument() + expect(screen.queryByRole('group')).not.toBeInTheDocument() +}) + +test('a group with nothing in it is left out', async () => { + mockFetch(routes({ 'GET /api/v1/artists': () => page([]) })) + renderBox() + await userEvent.type(box(), 'bjork') + await screen.findByRole('listbox') + expect(screen.queryByRole('group', { name: 'Artists' })).not.toBeInTheDocument() + expect(screen.getByRole('group', { name: 'Albums' })).toBeInTheDocument() +}) + +test('while the answer is on its way it says so', async () => { + mockFetch(routes({ 'GET /api/v1/artists': () => new Promise(() => undefined) as never })) + renderBox() + await userEvent.type(box(), 'bjork') + expect(await screen.findByText('Searching…')).toBeInTheDocument() +}) + +test('a search that fails says so and can be tried again', async () => { + let fail = true + mockFetch(routes({ 'GET /api/v1/tracks': () => (fail ? new Response('{}', { status: 500 }) : page([song(0)])) })) + renderBox() + await userEvent.type(box(), 'bjork') + const retry = await screen.findByRole('button', { name: 'Try again' }) + fail = false + await userEvent.click(retry) + expect(await screen.findByRole('option', { name: /Song 0/ })).toBeInTheDocument() +}) + +test('text that is only spaces is not a search', async () => { + const { calls } = mockFetch(routes()) + renderBox() + await userEvent.type(box(), ' ') + await new Promise((r) => setTimeout(r, 350)) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(calls).toHaveLength(0) +}) diff --git a/web/src/components/SearchBox.tsx b/web/src/components/SearchBox.tsx new file mode 100644 index 0000000..7d060af --- /dev/null +++ b/web/src/components/SearchBox.tsx @@ -0,0 +1,240 @@ +import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react' +import { useTranslation } from 'react-i18next' +import { useNavigate } from 'react-router-dom' +import { useAlbumList, useArtistList, useTrackList } from '@/api/catalog' +import ArtistPhoto from '@/components/ArtistPhoto' +import Cover from '@/components/Cover' +import { ErrorMessage } from '@/components/Status' +import { Input } from '@/components/ui/input' +import { cn } from '@/lib/utils' +import { usePlayer } from '@/player/store' + +/** Wait this long after the last keystroke before asking the server. */ +const DEBOUNCE_MS = 200 +/** What the server accepts as search text. */ +const MAX_QUERY_LENGTH = 200 +/** How many of each kind the list shows: a preview, not the results (the page of the search has those). */ +const ARTISTS = 3 +const ALBUMS = 3 +const SONGS = 5 + +interface Choice { + id: string + /** The words of the row, and what it says under them. */ + title: string + note: string + picture: React.ReactNode + run(): void +} + +/** + * A search box with a list that opens under it while you type: a few artists, albums and songs, each with its + * picture, to open or play without leaving the page. The arrows move through the list, Enter opens what is marked + * (or, with nothing marked, the page with all the results), Escape closes it. + * + * The pictures of artists are not asked for: asking makes the server look the artist up at the providers, and a list + * of whatever matched a few letters is not something to look up. + */ +export default function SearchBox({ className }: { className?: string }) { + const { t } = useTranslation() + const navigate = useNavigate() + const playTracks = usePlayer((s) => s.playTracks) + const [text, setText] = useState('') + const [typed, setTyped] = useState('') + const [open, setOpen] = useState(false) + const [active, setActive] = useState(-1) + const root = useRef(null) + const listId = useId() + + useEffect(() => { + const timer = setTimeout(() => setTyped(text), DEBOUNCE_MS) + return () => clearTimeout(timer) + }, [text]) + + // A click outside the box and its list closes the list. + useEffect(() => { + if (!open) return + const away = (e: MouseEvent) => { + if (root.current && !root.current.contains(e.target as Node)) setOpen(false) + } + document.addEventListener('mousedown', away) + return () => document.removeEventListener('mousedown', away) + }, [open]) + + // Searching by spaces is not searching; the server takes at most 200 characters. + const clean = (s: string) => Array.from(s.trim()).slice(0, MAX_QUERY_LENGTH).join('') + const q = clean(typed) + const enabled = q !== '' + const artists = useArtistList(q, { pageSize: ARTISTS, enabled }) + const albums = useAlbumList({ q, pageSize: ALBUMS, enabled }) + const songs = useTrackList({ q, pageSize: SONGS, enabled }) + const all = [artists, albums, songs] + const failed = all.find((query) => query.isError) + const pending = all.some((query) => query.isPending) + + const visible = open && clean(text) !== '' + const close = () => { + setOpen(false) + setActive(-1) + } + const go = (path: string) => { + close() + navigate(path) + } + const seeAll = () => go(`/search?q=${encodeURIComponent(clean(text))}`) + + const groups: { key: string; label: string; choices: Choice[] }[] = [] + if (enabled && !failed && !pending) { + groups.push({ + key: 'artists', + label: t('nav.artists'), + choices: (artists.data?.items ?? []).map((a) => ({ + id: `${listId}-artist-${a.id}`, + title: a.name, + note: t('search.kind.artist'), + picture: , + run: () => go(`/artists/${a.id}`), + })), + }) + groups.push({ + key: 'albums', + label: t('nav.albums'), + choices: (albums.data?.items ?? []).map((a) => ({ + id: `${listId}-album-${a.id}`, + title: a.title, + note: [t('search.kind.album'), a.artist?.name].filter(Boolean).join(' · '), + picture: , + run: () => go(`/albums/${a.id}`), + })), + }) + groups.push({ + key: 'songs', + label: t('nav.songs'), + choices: (songs.data?.items ?? []).map((s) => ({ + id: `${listId}-song-${s.id}`, + title: s.title, + note: [t('search.kind.song'), s.artists.map((a) => a.name).join(', ')].filter(Boolean).join(' · '), + picture: , + run: () => { + close() + playTracks([s], 0) + }, + })), + }) + } + const shown = groups.filter((g) => g.choices.length > 0) + const nothing = enabled && !failed && !pending && shown.length === 0 + const everyChoice: Choice[] = shown.flatMap((g) => g.choices) + if (shown.length > 0) { + everyChoice.push({ id: `${listId}-all`, title: t('search.seeAllFor', { q: clean(text) }), note: '', picture: null, run: seeAll }) + } + const activeChoice = visible ? everyChoice[active] : undefined + + function onKeyDown(e: KeyboardEvent) { + switch (e.key) { + case 'ArrowDown': + case 'ArrowUp': { + e.preventDefault() + if (!visible) { + setOpen(true) + return + } + // The choices and "none" go round: down from the last is none, up from none is the last. + const n = everyChoice.length + const step = e.key === 'ArrowDown' ? 1 : -1 + setActive(((active + 1 + step + (n + 1)) % (n + 1)) - 1) + return + } + case 'Enter': + e.preventDefault() + if (activeChoice) activeChoice.run() + else if (clean(text) !== '') seeAll() + return + case 'Escape': + if (visible) { + e.preventDefault() + close() + } + return + } + } + + return ( +
+ 0 ? listId : undefined} + aria-autocomplete="list" + aria-activedescendant={activeChoice?.id} + value={text} + placeholder={t('search.placeholder')} + autoComplete="off" + onChange={(e) => { + setText(e.target.value) + setOpen(true) + setActive(-1) + }} + onFocus={() => setOpen(true)} + onKeyDown={onKeyDown} + className="h-11 px-4" + /> + {visible && enabled && ( +
+ {failed ? ( +
+ all.forEach((query) => query.refetch())} /> +
+ ) : pending ? ( +

+ {t('search.searching')} +

+ ) : nothing ? ( +

{t('search.nothingFound', { q })}

+ ) : ( +
+ {shown.map((g) => ( +
+
+ {g.label} +
+ {g.choices.map((c) => ( + setActive(everyChoice.indexOf(c))} /> + ))} +
+ ))} +
+ setActive(everyChoice.length - 1)} + /> +
+
+ )} +
+ )} +
+ ) +} + +function Row({ choice, selected, onHover }: { choice: Choice; selected: boolean; onHover(): void }) { + return ( +
+ {choice.picture && {choice.picture}} + + {choice.title} + {choice.note && {choice.note}} + +
+ ) +} diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index a230c2b..70ecdf5 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -41,6 +41,17 @@ test('at /artists the Artists link is the current page and the others are not', } }) +test('every page but the search has a search box on top, with a list that opens under it', async () => { + await renderAt('/albums') + expect(screen.getByRole('combobox', { name: 'Search your library' })).toBeInTheDocument() +}) + +test('the search page has its own box and not this one', async () => { + await renderAt('/search') + expect(screen.queryByRole('combobox', { name: 'Search your library' })).not.toBeInTheDocument() + expect(screen.getByRole('searchbox', { name: 'Search your library' })).toBeInTheDocument() +}) + const adminRoutes = { 'GET /api/v1/libraries': () => ({ libraries: [] }), 'GET /api/v1/library/scan': () => ({ running: false }), diff --git a/web/src/components/layout/Shell.tsx b/web/src/components/layout/Shell.tsx index 61cd4e7..c491ff2 100644 --- a/web/src/components/layout/Shell.tsx +++ b/web/src/components/layout/Shell.tsx @@ -1,6 +1,7 @@ import { useRef } from 'react' import { useTranslation } from 'react-i18next' -import { Outlet } from 'react-router-dom' +import { Outlet, useLocation } from 'react-router-dom' +import SearchBox from '@/components/SearchBox' import { usePlayerEngine } from '@/player/usePlayer' import UpdateNotice from '@/pwa/UpdateNotice' import PhoneTabs from './PhoneTabs' @@ -11,6 +12,8 @@ import Sidebar from './Sidebar' export default function Shell() { const { t } = useTranslation() const main = useRef(null) + // The search page has its own box, and a phone has the Search tab. + const searching = useLocation().pathname.startsWith('/search') usePlayerEngine() return (
@@ -33,6 +36,11 @@ export default function Shell() { tabIndex={-1} className="min-w-0 flex-[999_1_560px] px-5 py-6 outline-none sm:px-14 sm:py-11" > + {!searching && ( +
+ +
+ )}
diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 0895c2d..12aff00 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -742,7 +742,14 @@ "label": "Search your library", "placeholder": "Artists, albums and songs", "hint": "Type to search artists, albums and songs.", - "nothingFound": "Nothing matches “{{q}}”." + "nothingFound": "Nothing matches “{{q}}”.", + "seeAllFor": "See all results for “{{q}}”", + "searching": "Searching…", + "kind": { + "artist": "Artist", + "album": "Album", + "song": "Song" + } }, "provider": { "wikipedia": "Wikipedia", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 9db85ea..3e99b05 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -742,7 +742,14 @@ "label": "Cerca nella libreria", "placeholder": "Artisti, album e brani", "hint": "Scrivi per cercare artisti, album e brani.", - "nothingFound": "Nessun risultato per «{{q}}»." + "nothingFound": "Nessun risultato per «{{q}}».", + "seeAllFor": "Mostra tutti i risultati per «{{q}}»", + "searching": "Cerco…", + "kind": { + "artist": "Artista", + "album": "Album", + "song": "Brano" + } }, "provider": { "wikipedia": "Wikipedia",