Search with a preview while I type #24

Merged
squid merged 1 commit from feat/search-preview into main 2026-11-16 10:43:08 +00:00
6 changed files with 494 additions and 3 deletions

View file

@ -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 <output data-testid="location">{l.pathname + l.search}</output>
}
function renderBox() {
return render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<MemoryRouter initialEntries={['/albums']}>
<SearchBox />
<Location />
</MemoryRouter>
</QueryClientProvider>,
)
}
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)
})

View file

@ -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<HTMLDivElement>(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: <ArtistPhoto artistId={a.id} name={a.name} size={40} photo={false} />,
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: <Cover albumId={a.id} size={40} />,
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: <Cover albumId={s.album?.id ?? null} size={40} />,
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<HTMLInputElement>) {
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 (
<div ref={root} className={cn('relative w-full max-w-xl', className)}>
<Input
type="search"
role="combobox"
aria-label={t('search.label')}
aria-expanded={visible}
aria-controls={visible && shown.length > 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 && (
<div className="absolute inset-x-0 top-full z-30 mt-1 max-h-[70vh] overflow-y-auto border border-border bg-card p-1 text-card-foreground">
{failed ? (
<div className="p-3">
<ErrorMessage error={failed.error} onRetry={() => all.forEach((query) => query.refetch())} />
</div>
) : pending ? (
<p role="status" className="p-3 text-muted-foreground">
{t('search.searching')}
</p>
) : nothing ? (
<p className="p-3 text-muted-foreground">{t('search.nothingFound', { q })}</p>
) : (
<div id={listId} role="listbox" aria-label={t('search.label')}>
{shown.map((g) => (
<div key={g.key} role="group" aria-labelledby={`${listId}-${g.key}`}>
<div id={`${listId}-${g.key}`} className="px-3 pt-2 pb-1 text-[13px] font-medium text-muted-foreground">
{g.label}
</div>
{g.choices.map((c) => (
<Row key={c.id} choice={c} selected={c.id === activeChoice?.id} onHover={() => setActive(everyChoice.indexOf(c))} />
))}
</div>
))}
<div role="presentation" className="sticky bottom-0 mt-1 border-t border-border bg-card pt-1">
<Row
choice={everyChoice[everyChoice.length - 1]}
selected={everyChoice[everyChoice.length - 1].id === activeChoice?.id}
onHover={() => setActive(everyChoice.length - 1)}
/>
</div>
</div>
)}
</div>
)}
</div>
)
}
function Row({ choice, selected, onHover }: { choice: Choice; selected: boolean; onHover(): void }) {
return (
<div
id={choice.id}
role="option"
aria-selected={selected}
onClick={choice.run}
onMouseEnter={onHover}
className={cn('flex min-h-12 cursor-pointer items-center gap-3 px-3 py-1.5', selected && 'bg-secondary')}
>
{choice.picture && <span className="flex-none">{choice.picture}</span>}
<span className="flex min-w-0 flex-col">
<span className={cn('truncate', choice.picture ? 'font-semibold' : 'font-semibold text-primary')}>{choice.title}</span>
{choice.note && <span className="truncate text-sm text-muted-foreground">{choice.note}</span>}
</span>
</div>
)
}

View file

@ -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 }),

View file

@ -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<HTMLElement>(null)
// The search page has its own box, and a phone has the Search tab.
const searching = useLocation().pathname.startsWith('/search')
usePlayerEngine()
return (
<div className="flex min-h-screen flex-col bg-background text-foreground">
@ -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 && (
<div className="sticky top-0 z-20 -mx-14 -mt-11 mb-8 bg-background px-14 py-3 max-sm:hidden">
<SearchBox />
</div>
)}
<Outlet />
</main>
</div>

View file

@ -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",

View file

@ -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",