diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx
index 1ba7ae4..84dbfb6 100644
--- a/client/src/App.test.tsx
+++ b/client/src/App.test.tsx
@@ -163,6 +163,36 @@ describe('App search', () => {
expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument();
});
+ it('writes the query to the URL on submission and not while typing', async () => {
+ renderApp([mockSearch('Abbey')]);
+
+ fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Abb' } });
+ fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Abbey' } });
+ await act(() => new Promise((resolve) => setTimeout(resolve, 400)));
+
+ // Typing alone touches neither the URL nor the network.
+ expect(window.location.search).toBe('');
+ expect(screen.getByRole('searchbox')).toHaveValue('Abbey');
+
+ fireEvent.submit(screen.getByRole('search'));
+ await screen.findByRole('article', { name: 'Abbey Road' });
+ expect(window.location.search).toBe('?q=Abbey');
+ });
+
+ it('treats a pasted whitespace-only query as no query at all', async () => {
+ // Without trimming on parse this counted as an active search and went to
+ // the backend, which trimmed it to nothing and returned an empty result.
+ window.history.replaceState({}, '', '/?q=%20%20');
+ renderApp([mockSearch('Abbey')]);
+
+ expect(screen.getByRole('searchbox')).toHaveValue('');
+ expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist');
+ expect(screen.queryByText('Searching albums…')).not.toBeInTheDocument();
+ expect(screen.queryByText('No albums found')).not.toBeInTheDocument();
+ await act(() => new Promise((resolve) => setTimeout(resolve, 150)));
+ expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist');
+ });
+
it('shows loading and then renders GraphQL result metadata after submission', async () => {
renderApp([mockSearch('Abbey')]);
submitSearch(' Abbey ');
diff --git a/client/src/api/searchAlbums.ts b/client/src/api/searchAlbums.ts
index becb99c..eb5a00c 100644
--- a/client/src/api/searchAlbums.ts
+++ b/client/src/api/searchAlbums.ts
@@ -1,8 +1,16 @@
import { gql } from '@apollo/client';
import type { TypedDocumentNode } from '@apollo/client';
-export type AlbumSort =
- 'RELEVANCE' | 'TITLE_ASC' | 'RELEASE_YEAR_DESC' | 'AVERAGE_RATING_DESC';
+// The runtime list and the type come from one place, so URL parsing in
+// useSearchState cannot drift away from what the schema accepts.
+export const ALBUM_SORTS = [
+ 'RELEVANCE',
+ 'TITLE_ASC',
+ 'RELEASE_YEAR_DESC',
+ 'AVERAGE_RATING_DESC',
+] as const;
+
+export type AlbumSort = (typeof ALBUM_SORTS)[number];
export interface AlbumSearchInput {
query: string;
diff --git a/client/src/components/SearchForm.test.tsx b/client/src/components/SearchForm.test.tsx
index 2f06426..67688b3 100644
--- a/client/src/components/SearchForm.test.tsx
+++ b/client/src/components/SearchForm.test.tsx
@@ -9,44 +9,41 @@ function type(query: string) {
fireEvent.change(screen.getByRole('searchbox'), { target: { value: query } });
}
+function submit() {
+ fireEvent.submit(screen.getByRole('search'));
+}
+
function advance(milliseconds: number) {
act(() => vi.advanceTimersByTime(milliseconds));
}
describe('SearchForm', () => {
- it('waits 300 ms after the last change and submits only the latest text', () => {
+ it('does not submit while typing', () => {
const onSearch = vi.fn();
render();
- type('Abb');
- advance(200);
+ type('A');
+ type('Ab');
type('Abbey');
- advance(299);
+ advance(1000);
expect(onSearch).not.toHaveBeenCalled();
- advance(1);
- expect(onSearch).toHaveBeenCalledExactlyOnceWith('Abbey');
+ expect(window.location.search).toBe('');
});
- it.each(['form', 'button'])(
- 'submits immediately through %s and cancels the debounce',
- (method) => {
- const onSearch = vi.fn();
- render();
- type(' Abbey ');
- if (method === 'form') fireEvent.submit(screen.getByRole('search'));
- else fireEvent.click(screen.getByRole('button', { name: 'Search' }));
- expect(onSearch).toHaveBeenCalledExactlyOnceWith('Abbey');
- advance(300);
- expect(onSearch).toHaveBeenCalledTimes(1);
- },
- );
+ it.each(['form', 'button'])('submits once through %s', (method) => {
+ const onSearch = vi.fn();
+ render();
+ type(' Abbey ');
+ if (method === 'form') submit();
+ else fireEvent.click(screen.getByRole('button', { name: 'Search' }));
+ expect(onSearch).toHaveBeenCalledExactlyOnceWith('Abbey');
+ });
- it('submits immediately on Enter and cancels the debounce', () => {
+ it('submits once on Enter and keeps the focus in the input', () => {
const onSearch = vi.fn();
render();
const input = screen.getByRole('searchbox');
input.focus();
type(' Abbey ');
- expect(onSearch).not.toHaveBeenCalled();
const defaultAllowed = fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });
// jsdom does not perform implicit form submission for keyboard events.
@@ -55,37 +52,47 @@ describe('SearchForm', () => {
expect(input).toHaveFocus();
expect(onSearch).toHaveBeenCalledExactlyOnceWith('Abbey');
- advance(300);
- expect(onSearch).toHaveBeenCalledTimes(1);
});
- it('cancels pending work when unmounted', () => {
+ it('keeps the typed text in the box', () => {
+ // The URL write used to come back round and reset the input mid-word, which
+ // is what made typing feel like a reload. Nothing commits while typing, so
+ // the box has to hold what was typed.
const onSearch = vi.fn();
- const view = render();
+ render();
type('Abbey');
- view.unmount();
- advance(300);
- expect(onSearch).not.toHaveBeenCalled();
+ advance(1000);
+ expect(screen.getByRole('searchbox')).toHaveValue('Abbey');
});
- it('does not resubmit a committed query', () => {
+ it('mirrors an external query change into the input', () => {
+ // Back/forward and a pasted link both change the URL without the form
+ // being involved, and the box has to follow.
const onSearch = vi.fn();
- const view = render();
- type('Abbey');
- view.rerender();
- advance(300);
- expect(onSearch).not.toHaveBeenCalled();
+ const { rerender } = render();
+ rerender();
+ expect(screen.getByRole('searchbox')).toHaveValue('blue');
});
- it('waits until composition input has finished', () => {
+ it('does not submit in the middle of a composition', () => {
const onSearch = vi.fn();
render();
- fireEvent.compositionStart(screen.getByRole('searchbox'));
+ const input = screen.getByRole('searchbox');
+ fireEvent.compositionStart(input);
type('Abbey');
- advance(300);
+ submit();
expect(onSearch).not.toHaveBeenCalled();
- fireEvent.compositionEnd(screen.getByRole('searchbox'));
- advance(300);
+
+ fireEvent.compositionEnd(input);
+ submit();
expect(onSearch).toHaveBeenCalledExactlyOnceWith('Abbey');
});
+
+ it('submits the trimmed text, so an empty box does not search', () => {
+ const onSearch = vi.fn();
+ render();
+ type(' ');
+ submit();
+ expect(onSearch).toHaveBeenCalledExactlyOnceWith('');
+ });
});
diff --git a/client/src/components/SearchForm.tsx b/client/src/components/SearchForm.tsx
index 333e27e..4c23b71 100644
--- a/client/src/components/SearchForm.tsx
+++ b/client/src/components/SearchForm.tsx
@@ -1,41 +1,39 @@
import './SearchForm.css';
-import { useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
interface Props {
query: string;
onSearch: (query: string) => void;
}
+/**
+ * The text box and the Search button. Typing only edits a local draft:
+ * nothing is committed and nothing is requested until the form is submitted,
+ * by the button or by Enter. That keeps the URL stable while someone is
+ * mid-word and avoids a request per keystroke.
+ */
export default function SearchForm({ query, onSearch }: Props) {
const [draft, setDraft] = useState(query);
const [previousQuery, setPreviousQuery] = useState(query);
const [composing, setComposing] = useState(false);
- const timer = useRef | undefined>(undefined);
+ // The committed query can change without this form causing it: back/forward
+ // and a pasted link both move the URL. Mirror those into the input. Typing
+ // never commits on its own, so this cannot clobber text that is mid-edit.
if (query !== previousQuery) {
setPreviousQuery(query);
setDraft(query);
}
- // Keep typing responsive; wait for a pause before committing a new query.
- useEffect(() => {
- if (composing || draft.trim() === query) return;
-
- timer.current = setTimeout(() => onSearch(draft.trim()), 300);
- return () => clearTimeout(timer.current);
- }, [draft, query, composing, onSearch]);
-
return (